Open the WaytoAGI knowledge base on Feishu · 100M+ visits, open to everyone →
WaytoAGI

Knowledge Base · Learning paths

Transformer Explained in One Article: Attention, QKV, Residual Connections, and Why It Replaced RNNs

This comprehensive guide breaks down the core concepts of the Transformer architecture, including how self-attention enables direct token-to-token interaction, the mathematics behind QKV matrices, multi-head attention, residual connections, and LayerNorm. It explains why Transformers completely replaced RNNs and became the foundation of all modern large language models.

Transformer explainedself-attention mechanismQKV matrixmulti-head attentionresidual connection

Translated from Chinese by AI. Spotted an issue? Use the feedback button.

🔗 Original Link: https://x.com/xuanyuanzhifeng/status/209...

Xuanyuan Zhifeng · X · @xuanyuanzhifeng · 2026-09-02 15:02

📌 This article is reposted. All copyrights belong to the original author. The full text is subject to the original link.

Have you ever wondered how an AI large language model like GPT actually understands our prompts and then generates answers word by word?

In the previous episode, we covered the technological development path before the birth of the Transformer.

If you haven’t watched the last episode, no problem — let’s do a quick recap.

At the very beginning, there was N-gram. Its idea was very simple: count what word most commonly follows a given sequence of previous words.

But N-gram only performs statistics. It doesn’t understand any semantic relationships between different words.

Then came word vectors, also known as word embeddings.

Word embeddings convert each word into a high-dimensional vector of numbers. The meaning of words is mapped into these numbers, so words with similar meanings are positioned close to each other in vector space.

After having word embeddings, we fed these vectors into feedforward neural networks, allowing the networks to learn more complex language patterns and predict the next word.

However, feedforward neural networks can only accept a fixed number of tokens at a time. Once earlier content is too far away, the model can no longer “see” it.

So RNNs — Recurrent Neural Networks — were introduced.

RNNs added a hidden state that is continuously passed backward, essentially giving the model a form of memory so that information from earlier tokens can keep flowing forward.

But RNNs had poor long-term memory. As the distance grew, important information from the beginning was easily lost gradually.

Then came LSTM.

LSTM introduced a dedicated long-term memory channel and several “gates,” allowing the model to learn for itself what to remember, what to forget, and when to retrieve that information for use.

Up to this point, things already looked pretty good.

However, LSTM still had two very troublesome problems.

The first problem was that it had to compute one token after another in strict sequential order. The next token could not start processing until the previous one was finished. For long inputs, this made the process extremely inefficient.

The second problem was that for two tokens far apart to exchange information, the data still had to travel step by step through all the tokens in between.

For example, we used this sentence in the previous episode:

Xuanyuan raised a budgerigar when he was little.

It had green feathers and could mimic human speech.

Later, Xuanyuan went away to study and didn’t see it for many years.

But he always remembered the one he kept as a child: ____.

The final “one” is clearly directly related to the much earlier word “budgerigar.”

So why should the information about “budgerigar” have to be passed through dozens of intermediate tokens one by one before reaching “one”?

Wouldn’t it be simpler to let the word “one” establish a direct connection with the earlier word “budgerigar”?

Yes, we can — and that’s exactly where the story of the Transformer officially begins.

The Transformer comes from the famous 2017 paper Attention Is All You Need. In today’s video, we’re going to thoroughly understand what this ancestor of today’s AI large language models — the Transformer — really is.

Welcome everyone. If you find this helpful, please like, subscribe, and turn on notifications. Let’s begin today’s journey.

1. Stop Passing Messages — Let Tokens Look for Themselves

Let’s temporarily forget the name “Transformer” and return to our word-guessing game.

When we humans read the phrase “but he always remembered the one he raised as a child,” our brains naturally look back for information related to “the one.”

However, we don’t re-analyze the entire preceding text from beginning to end.

Instead, we scan the previous content in a single glance and instantly notice that “tiger-striped parakeet” has the strongest connection with “the one.”

So, can we make neural networks do the same?

We can give every Token in a sentence the ability to directly look at all the other Tokens.

Then each Token asks: “Among these words, which ones are most relevant to me?”

To make it easier to understand, let’s use a shorter example.

Suppose we have this sentence: “Xuanyuan raised a tiger-striped parakeet. It has green feathers.”

We are currently processing the Token “It.”

Humans obviously know that “It” most likely refers to the “tiger-striped parakeet” mentioned earlier, and definitely not to Xuanyuan.

So we also let the model look at all the Tokens in the sentence. We’ll explain exactly how it looks in a moment.

The model might calculate that the relationship between “Xuanyuan” and “It” is relatively weak, the relationship between “raised” and “It” is also weak, while the relationship between “tiger-striped parakeet” and “It” is extremely strong.

Suppose we end up with the following set of weights:

“Xuanyuan” gets 10%, “raised” gets 5%, “tiger-striped parakeet” gets 70%, and the remaining 15% is distributed among the other Tokens.

Next, we mix the information carried by the different Tokens according to these weights.

Since “tiger-striped parakeet” has the highest weight, we take more of its information.

“Raised” has a very low weight, so we take very little of its information.

After all the information is added together according to their respective weights, “It” obtains a new vector.

Notice that this new vector is no longer the original isolated word vector for “It.”

The original word vector mainly expressed what the word “It” itself roughly means.

After the operation we just performed, the new vector now incorporates the context of the current sentence.

In particular, a large amount of information from “tiger-striped parakeet” flows into the new vector for “It.”

This way, when the model later processes “It has green feathers,” it can understand that this “It” has a very strong relationship with the tiger-striped parakeet.

The same method can be applied to every Token in the sentence.

Every Token in the sentence can directly look at all the other Tokens and retrieve the information relevant to itself.

“Green” can look for the “feathers” that are most strongly related to it.

“Raised” can look for “Xuanyuan” and “tiger-striped parakeet,” which are strongly related to it.

The Tokens in a sentence examine each other and exchange information directly.

Whether there is one Token or a hundred Tokens between them, there is no need to pass messages sequentially like in an RNN.

The mechanism we just designed is exactly the core idea behind Attention — the attention mechanism.

In simple terms, “attention” means letting the current Token decide how important other Tokens are to itself, and then focusing on reading the important information.

The description above sounds beautiful, but a question arises: how do we actually implement this?

When one Token looks at other Tokens, how exactly does this “looking” work?

What should it pay attention to, and how are the weight values for those Tokens calculated?

This is the key to understanding the attention mechanism.

II. Attention Mechanism: How Does the Model Know Who to Focus On?

Let’s continue with the previous example.

When the model is processing the token “it,” in order to make the next prediction, it needs to figure out what “it” actually refers to in the preceding sentence.

Before searching, it first needs to express one thing: “What am I looking for right now?”

This is just like when we search for something online — we need to enter a search query.

So we need to prepare a special “search keyword” for each token, specifically for querying.

For example, in the current context, “it” is probably looking for an object that appeared earlier in the sentence — most likely an item or a thing, which is usually a noun. It’s unlikely to be an adjective or an adverb.

Similar to the word vectors we discussed earlier, this “search keyword” is not a text string either. It is still a high-dimensional vector composed of numbers, and the search intent is embedded within it.

This vector used to express “what I’m looking for right now” is called the Query, abbreviated as Q.

But a query alone is not enough.

Each token also needs to declare: “Here’s what information I have available for querying.”

For instance, the token “parakeet” can provide a piece of information suitable for being queried.

“Xuanyuan” also provides its own information.

“Green” also provides its own information.

The vector specifically prepared for matching against a Query is called the Key, abbreviated as K.

Now the token “it” has its own Q, and every token before it has its own K.

Next, “it” can take its own Q and compare it one by one with everyone else’s K.

If “it”’s Q matches very well with the K of “parakeet,” the model knows that “parakeet” deserves a lot of attention.

If it doesn’t match well with the K of “green,” then “green” should receive less attention.

So the question arises: how exactly do Q and K match?

We can compute the dot product between these two vectors.

The dot product produces a single number.

The larger this number is, the better the two vectors are considered to match.

For example:

  • The dot product between “it”’s Q and “Xuanyuan”’s K is 1.2.
  • The dot product between “it”’s Q and “green”’s K is 0.8.
  • The dot product between “it”’s Q and “parakeet”’s K is 6.8.

Clearly, the position of “parakeet” is much more worthy of attention.

These scores are then passed through a Softmax function to convert them into corresponding attention weights.

In this way, the model knows which tokens it should attend to, and how much attention each should receive.

At this point, many people will have a question: how can we guarantee that “it”’s Q will match perfectly with “parakeet”’s K?

The answer is still training.

At the beginning, the matches are completely random. As training progresses, the relevant parameters are continuously adjusted, and the matching between Q and K gradually aligns with the patterns of natural language.

So what happens next? Once the model knows who to focus on, what does it do?

What is truly useful is the actual information carried by the token “parakeet.” It is neither its Q nor its K — those two are only used for querying and being queried.

Therefore, each token needs to prepare a third vector.

This vector is not responsible for searching or matching. It is responsible for storing the real information that others can read.

This vector is called the Value, abbreviated as V.

At this point, we have assembled the three key components of the attention mechanism: Q, K, and V.

  • Q represents “What am I looking for?”
  • K represents “What information do I roughly have here?”
  • V represents “What information am I actually carrying?”

It must be emphasized again that this is only an analogy to aid understanding.

In a real model, there are no literal text labels such as “pet,” “color,” or “person” written into the Q, K, or V.

Their essence is still a set of high-dimensional numbers, and all the above information is encoded within these high-dimensional vectors.

Now a new question arises.

Didn’t each token originally have only one word vector?

How come each token suddenly now has three vectors?

This problem is actually quite easy to solve.

Suppose “parakeet” currently has a several-hundred-dimensional vector.

We pass this vector through one linear transformation to obtain the first new set of numbers: Q.

We pass it through another linear transformation to obtain the second set: K.

Then we pass it through a third linear transformation to obtain the third set: V.

Every token does the same thing.

“Xuanyuan” has its own Q, K, and V. “Raised” has its own Q, K, and V. “Parakeet” also has its own Q, K, and V.

As for how exactly these three linear transformations are performed and what parameters they use, again, programmers do not need to design them manually.

During training, the model gradually learns these parameters through repeated prediction errors and backpropagation.

Once we have Q, K, and V, the rest is straightforward.

We multiply these attention weights by the corresponding V of each token, then add them all up.

Tokens with higher weights contribute more information, while tokens with lower weights contribute less.

The final result is a new vector for the current token that has fused information from the context.

The attention formula in the paper Attention Is All You Need essentially does exactly this.

In the paper’s formula, after the dot product of Q and K, the result is divided by the square root of d.

Here’s the full English translation:


This is mainly because when the vector dimension becomes very high, the dot product results tend to grow very large. After applying Softmax, the values can become extremely extreme.

So we first scale it down slightly, which helps make training more stable.

There’s also another important detail.

Our Q, K, and V all come from the Tokens within the same sentence.

The Tokens in a sentence are looking at each other.

This is called Self-Attention.

In contrast, when attention is computed between Tokens from one sentence and Tokens from another sentence, it is no longer self-attention. It has other names, which we will see shortly.

However, having just one set of Q, K, and V is not enough.

Consider this sentence:

“Xuanyuan kept a parakeet as a child. It had green feathers.”

The relationships between Tokens here are extremely complex.

“It” and “parakeet” have a clear referential relationship.

“Green” and “feathers” have a modification relationship.

“Xuanyuan” and “kept” have an action relationship.

“Kept” and “parakeet” have yet another type of relationship.

In other words, within the same sentence, there can simultaneously exist syntactic relationships, semantic relationships, referential relationships, long-distance dependencies, and many others.

With only one set of Q, K, and V, it is very difficult to capture all these different types of relationships at once.

If one set isn’t enough, then let’s create multiple sets.

We perform multiple parallel Attention calculations on the same sentence.

The first group may focus on referential relationships.

The second group may pay attention to nearby words.

The third group may learn some long-distance relationships.

The fourth group may discover entirely different patterns.

Of course, which head is responsible for reference, which one handles syntax, etc., is not pre-arranged by the programmer.

What each Attention head ultimately learns is entirely determined by the training process itself.

All we do is provide multiple different “observation spaces.”

Finally, we concatenate the results from these different Attention heads to form a richer representation.

This technique of “performing Attention from multiple perspectives simultaneously” is called Multi-Head Attention.

A “head” can be temporarily understood as one independent set of attention computations.

If one angle isn’t enough to understand the full picture, then looking from multiple angles together gives a more comprehensive view.

In the paper Attention Is All You Need, the original Transformer used 8 heads.

This way of computing attention solves both major problems of LSTM.

Two Tokens that are very far apart no longer need to pass information through a long chain of intermediate Tokens — they can establish direct connections.

Moreover, Tokens in a sentence no longer need to be processed one after another as in RNNs and LSTMs.

The Q, K, and V of all Tokens can be computed together.

The matching between all Qs and Ks can also be completed simultaneously through large-scale matrix operations.

Therefore, compared with RNNs and LSTMs, Transformers are much easier to train with massive parallelism on GPUs.

This is also a crucial prerequisite that later enabled models to grow larger and larger.

3. Positional Encoding: How Parallel Computation Knows the Order of Tokens

However, this parallel computation introduces a critical problem: the sequential order information between Tokens is lost.

Original RNNs and LSTMs are naturally sequential because they process data one step at a time.

But parallel computation processes all Tokens at once. How does the model know which one comes first and which comes later?

Consider these two sentences:

“Xuanyuan kept a parakeet.”

“The parakeet kept Xuanyuan.”

Both sentences contain the exact same three Tokens.

But because the order is different, their meanings are completely opposite.

The attention mechanism only calculates the correlation between Tokens. It does not handle word order.

So what should we do?

We can add a special piece of information that represents position to each Token’s original word vector.

The first Token gets information representing position 1.

The second Token gets information representing position 2.

And so on.

In this way, what the model receives is no longer just “what this word is.”

It also knows “where this word is located.”

This additional position data we just added is called Positional Encoding.

The original Transformer used sine and cosine functions to generate positional encodings.

Modern large language models have since developed other approaches.

We won’t dive into these details in this episode.

For now, you only need to remember one sentence:

Embeddings tell the model what a Token means. Positional encodings tell the model the order of the Tokens.

At this point, each Token can carry its own semantic and positional information and exchange information at scale with other Tokens through multi-head attention.

It seems pretty good.

But we are still far from our goal. Our goal is to play the word-guessing game: given the preceding content of a sentence, predict what comes next.

Attention is very good at helping Tokens find information everywhere.

But after the information is retrieved, what do we do next? How do we continue our word-guessing game?

Let’s keep going.

4. Feed-Forward Neural Network: After Gathering the Information, You Still Need to Digest It Yourself

Let’s look at the following sentence:

“Xuanyuan just bought a black Apple for over ten thousand yuan.”

In this context, does “Apple” refer to the fruit or to a product from Apple Inc.?

As a smart human, you can almost instantly realize that there’s no edible apple in the world that costs over ten thousand yuan — and it’s black, too.

So it must be referring to a product from Apple Inc.

Now let’s see how a computer figures this out.

For the sake of simplicity, let’s assume we only extract four features from the original several-hundred-dimensional vector of the word “Apple” for observation:

  • High price
  • Black appearance
  • Fruit attribute
  • Technology attribute

A quick note: in reality, vector semantics are extremely complex. It is extremely rare for individual dimensions to correspond exactly to these four aspects. We have simplified the dimensionality here purely for easier understanding.

At the very beginning, when the model only sees the word “Apple,” its vector might look like this:

0.1, 0.1, 0.6, 0.6

That is, there is currently no information about high price or black color. Both the “fruit” and “tech product” meanings remain possible.

Next, after the attention calculation, “Apple” starts to look at the surrounding tokens.

It retrieves appearance information from the word “black.”

It also pulls back very strong “high price” information from the phrase “over ten thousand yuan.”

So its vector may now become:

0.9, 0.9, 0.6, 0.6

Pay attention here.

Up to this point, what Attention has mainly accomplished is one thing:

It has pulled clues that were originally scattered across other tokens and brought them to “Apple.”

The model now knows that this “Apple”:

  • Is very expensive.
  • Is black.

However, the two possibilities — “fruit” versus “tech product” — have not yet been clearly distinguished.

So what happens next?

We need a new component to further analyze and compute these clues.

At this moment, an old friend from the previous video steps onto the stage: the Feed-Forward Neural Network, also known as FFN.

The FFN no longer looks at other tokens.

It only examines the information that “Apple” currently holds.

It then learns the combinatorial relationships between these features.

For example, consider this “Apple”:

  • Its price is extremely high.
  • It is also black.

When these two features are combined, it becomes highly unlikely to be a piece of fruit.

Instead, it strongly resembles some kind of electronic product from Apple Inc.

Therefore, after passing through the FFN, the vector may further transform into:

0.9, 0.9, 0.1, 0.95

The already-retrieved clues such as high price and black color remain.

But the fruit attribute is significantly suppressed, while the technology attribute is greatly enhanced.

So in reality, Attention and FFN perform quite different functions.

The attention mechanism is responsible for letting tokens exchange information with each other, while the feed-forward neural network is responsible for combining the information within each individual token, analyzing and reasoning about it.

One handles communication, the other handles thinking.

At this point, these two components can be assembled into a small basic unit.

First, information is exchanged through multi-head attention; then it is digested and processed through the feed-forward network.

This is the basic building block of the Transformer.

However, processing with just one unit is not enough. Real-world Transformers usually stack multiple layers, with each layer achieving a deeper level of understanding than the last.

The original paper used six layers, while today’s large language models commonly have dozens or even hundreds of layers.

The knowledge and capabilities of large language models are all stored within the parameters of these networks.

But as the network gets deeper, a new problem arises yet again.

V. Residual Connections: Keeping Training Alive

We just discussed how, in order to understand complex language, the Transformer stacks multiple layers of attention and FFN modules, allowing the model to gradually extract increasingly abstract features.

However, the deeper a network becomes, the more likely training problems will arise.

Model training relies on backpropagation. After a prediction produces an error, the gradient propagates backward from the final layer all the way to the front, telling earlier parameters how they should be adjusted.

This process fundamentally depends on the chain rule of derivatives.

If the gradient keeps shrinking as it passes through layer after layer of computation, by the time it reaches the earliest layers it may have become so weak that it has almost no effect.

The early layers receive no effective update signals and thus become increasingly difficult to train.

This is the classic vanishing gradient problem in deep neural networks.

So what’s the solution?

Researchers came up with a seemingly strange trick: directly add the original input of this layer back to its output.

Suppose the input to this layer is x, and after passing through a certain module it becomes f(x).

Normally we would have:

y = f(x)

Now we add the original x back in:

y = f(x) + x

Wait — if we just add x directly, doesn’t that change the result?

When I first saw this, I was full of question marks too.

The key point is that the function f is not fixed — it is itself learned during training.

Assume the true desired mapping is F(x).

Originally, f would have to learn the entire mapping by itself:

f(x) = F(x)

But now that x is automatically added at the end, f only needs to learn:

f(x) = F(x) - x

Then when we add x back, the result is exactly F(x) again.

So we can think of f as only needing to learn “how much is still missing on top of the original x.”

That “how much is still missing” is the residual.

That’s why this structure is called a residual connection.

The real power of this trick lies in backpropagation.

For y = f(x) + x, the derivative becomes:

y' = f'(x) + 1

The crucial part is that “+1”.

Previously, gradients could only travel forward through the complex path of f.

Now there is an additional shortcut that directly connects the input to the output, and the derivative of this shortcut is simply 1.

So even if the gradient along the f path becomes very small, there is still a much more direct path for the gradient to continue propagating backward.

This doesn’t guarantee the gradient will never shrink, but it greatly alleviates the vanishing gradient problem in deep networks.

Moreover, during forward propagation, the original information can also travel directly through this shortcut to later layers, without having to be completely reprocessed at every single layer.

Therefore, residual connections can be understood as building a highway for the network.

During forward propagation, information can travel deep along this highway.

During backward propagation, gradients can flow back along the same path.

Thanks to this, the Transformer can be stably stacked to dozens or even hundreds of layers.

In actual Transformer implementations, residual connections are usually paired with normalization modules to make training even more stable.

That’s why you often see “Add & Norm” in classic architecture diagrams.

OK. Now tokens can exchange information through attention, FFNs can further refine that information, and residual connections allow these modules to be stacked higher and higher.

But have we forgotten something?

After all this work, we’ve only been continuously processing the vector of each token.

Our ultimate goal from the very beginning was to actually predict the next token based on the preceding content.

How does the Transformer ultimately turn these high-dimensional vectors into a concrete word?

In the final part of today’s article, we’ll complete the last piece of the puzzle.

6. Encoder and Decoder: Understanding a Sentence and Generating a Sentence Are Two Different Things

The paper Attention Is All You Need was originally designed to solve machine translation.

For example, translating:

Xuanyuan raised a budgerigar.

into:

Xuanyuan has a budgie.

The translation process can be broken down into two steps.

First, understand the source text, then generate the translated text.

Accordingly, the Transformer is also split into two parts.

The part responsible for “reading” is called the Encoder.

The part responsible for “writing” is called the Decoder.

The encoder is exactly the structure we built in the previous sections.

The input is first turned into embeddings, positional information is added, and then it passes through multiple layers of self-attention and FFN.

At this stage, every token can attend to all other tokens in the entire sentence, including those that come after it.

This is perfectly fine, because the encoder’s job is to understand a complete, already-existing source sentence.

In the end, each token is transformed into a vector that has fused information from the entire sentence.

The encoder does not generate new tokens; it simply encodes “what the original sentence means” into these vectors.

Next, it’s the decoder’s turn to write the translation.

It does not output the entire sentence at once. Instead, it generates one token at a time.

For example, after it has already generated:

Xuanyuan has a

it now needs to predict:

budgie.

The tokens that have already been generated also need to perform self-attention.

But a problem immediately arises here.

During training, the correct target sentence is already fully available.

If the model is allowed to see the word “budgie” when predicting the next token after “Xuanyuan has a”, it would essentially be copying the answer.

Therefore, the decoder must follow a strict rule:

It can only look at itself and the preceding tokens; it cannot look at future tokens.

How is this achieved?

When computing attention scores, the scores for all future positions are directly replaced with a very small negative number.

After the Softmax operation, the weights for those positions become almost zero — effectively masked out.

This masking operation is called Mask.

Self-attention with a mask added is known as masked self-attention.

However, a new problem emerges.

If the decoder only looks at the English it has already written, how can it know what the original sentence actually said?

For instance, after “Xuanyuan has a”, should the next word be “cat”, “dog”, or “budgie”?

The real answer lies in the source text.

Therefore, while writing, the decoder also needs to look back at the encoder.

It uses its own Q to query the K and V produced by the encoder.

If the model is currently generating “budgie”, its Q is likely to have a high match with the K corresponding to “budgie” in the original sentence, allowing it to pull a large amount of information from that V.

Note that in this case, the Q comes from the Decoder, while the K and V come from the Encoder.

This type of attention performed across the two components is called cross-attention.

So each layer of the decoder can be simply understood as three steps:

  1. Use Masked Self-Attention to look at what it has already written.
  2. Use Cross-Attention to look back at the original text.
  3. Pass the result to the FFN for further processing.

Finally, the Decoder still outputs a set of vectors.

So how does it actually “spit out” a word?

It follows the same process we introduced in the previous episode.

The vector at the last position is fed into the output layer, which assigns a score to every token in the vocabulary.

These scores are then turned into probabilities through Softmax.

The token with the highest probability is usually chosen as the next token.

This new token is then appended to the end, and the process continues to predict the next one.

One token after another is generated this way until the end-of-sequence token is produced.

This is roughly how the original Transformer works.

However, today’s large language models, represented by GPT, differ somewhat from the earliest Transformer architecture.

We will discuss this in more detail later.

VII. Review and Summary

Now let’s take a step back and review everything we covered today.

At the very beginning, the biggest problem with LSTM was that information had to be passed from one token to the next, and computation could only be done sequentially.

So we came up with a solution: allow every token to directly look at all other tokens.

This solution is called Self-Attention.

But which tokens should each token actually look at?

That’s why every token generates its own Q, K, and V.

  • Q (Query) is used to ask questions,
  • K (Key) is used to match those questions,
  • V (Value) is used to actually deliver the information.

What if one single relationship isn’t enough?

Then we run multiple sets of Attention in parallel.

This gives us Multi-Head Attention.

After all tokens are computed in parallel, the original sequential order disappears. What then?

We add positional information on top of the tokens.

This is called Positional Encoding.

Attention is only responsible for finding relevant information. Once the information is retrieved, it still needs further processing. What do we do?

We add a Feed-Forward Neural Network after it.

As the network gets deeper and deeper, the original information tends to get lost, and training becomes increasingly difficult. How do we solve this?

We add a shortcut that allows information to flow directly forward.

This is known as Residual Connections.

When generating text, the model cannot peek at future tokens. How do we prevent that?

We simply mask the future tokens.

This leads to Masked Self-Attention.

In the classic translation model, the Decoder also needs to read information from the Encoder. How do we enable that?

We let the Decoder’s Q attend to the Encoder’s K and V.

This gives us Cross-Attention.

You see, when looking at the Transformer architecture diagram, it’s full of intimidating technical terms.

But if we don’t try to memorize the names directly, and instead reason through the problems one by one, we realize that none of these components appeared out of nowhere.

Every addition was introduced to solve a new problem exposed by the previous design.

These incremental improvements, when combined together, formed the foundational architecture behind nearly all of today’s large language models.

Finally, here’s a thought question for you:

Modern large models often have contexts of 1 million tokens or more. Computing attention between every pair of tokens at this scale results in an enormous computational cost. Is there any way to optimize this?

We’ll reveal the answer together in the next video.