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

Knowledge Base · Learning paths

Decoding the Transformer Architecture

This article breaks down the Transformer architecture piece by piece, providing a clear explanation of Tokenization, Embedding, Positional Encoding, Multi-Head Attention, Feed-Forward Networks, Residual Connections, and the Encoder-Decoder structure. Readers will gain a deep understanding of how data flows through the model and why the Transformer has become the foundation of all modern large language models (LLMs).

Transformer architectureTransformer explainedMulti-Head AttentionPositional EncodingLarge Language Models

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

Original post link: https://x.com/amitiitbhu/status/2041479290580287543

In this blog post, we will break down the Transformer architecture piece by piece. We’ll explore the role of each component, how they work together, and why this architecture powers every modern large language model (LLM).

When we hear the word “Transformer,” it sounds complicated. But don’t worry. If we break it down into its individual parts, each one is actually quite simple. The complexity comes from how these parts are stacked and combined, not because any single piece is inherently difficult.

Our goal is to explain this architecture clearly enough that, by the end, you’ll be able to explain how a Transformer works to anyone.

We will cover the following topics:

  • Why we need Transformers
  • The two main halves of the architecture
  • Tokenization, Embedding, and Positional Encoding
  • The Attention Mechanism and Multi-Head Attention
  • Feed-Forward Networks, Residual Connections, and Layer Normalization
  • How the Encoder and Decoder work
  • How data flows through the entire architecture
  • Three variants of the Transformer
  • Why Transformers are so powerful

I’m Amit Shekhar, from Outcomes Academy, where I teach Artificial Intelligence and Machine Learning.

Let’s get started.

Overall Overview

Before diving into the details, let’s first understand the big picture.

A Transformer takes a sequence of tokens as input and outputs a sequence of tokens. That’s it. At a very high level, it’s a “tokens in, tokens out” machine. And since those tokens come from text and ultimately turn back into text, we can also think of it as a “text in, text out” machine.

For example, if we input “Translate: I love learning,” it outputs “J'adore apprendre.” If we input “What is the capital of France?”, it outputs “The capital of France is Paris.”

But how does it actually do this? Let’s find out.

Why Do We Need Transformer Models?

Before Transformers existed, models processed words sequentially — reading a sentence from left to right, one word at a time.

This created two major problems:

Problem 1: Forgetting. Once a sentence became long, the model would start forgetting earlier words. By the time it reached the 50th word, its memory of the first word had become very weak.

Problem 2: Slowness. Because words were processed one after another, the second word had to wait for the first to finish, the third had to wait for the second, and so on. This made training extremely slow.

So, the Transformer arrived to solve these issues. It processes all input tokens at the same time and allows every token to directly look at every other token. Long-range dependencies are no longer a major problem. And because everything happens in parallel, training is also much faster. We’ll see exactly how this works in the following sections.

The Transformer was introduced in 2017 by Google researchers in the famous paper “Attention Is All You Need.” It changed everything.

The Architecture Is Divided into Two Main Parts

The original Transformer consists of two primary halves:

  • The Encoder, which reads and understands the input
  • The Decoder, which generates the output

You can think of it as a conversation between a reader and a writer. The reader (encoder) carefully reads the document and takes detailed notes. The writer (decoder) uses those notes to produce a new document. The reader focuses on understanding. The writer focuses on creation.

Now, let’s look at what happens inside each half. But before jumping into the encoder and decoder, we first need to understand what happens to the input before it even reaches them.

Decoding Step 1: Turning Text into Numbers

Models don’t understand words. They only understand numbers. So the first step is to convert words into numbers.

This process happens in two stages:

Tokenization: The input text is split into small pieces called tokens. A token can be a whole word, part of a word, or even a single character. For simplicity, let’s treat each word as one token.

“I love learning” becomes three tokens: “I”, “love”, “learning”.

Word Embedding: Next, each token is converted into a vector of numbers — this is called an embedding. An embedding is like a numerical fingerprint of a word. Words with similar meanings will have similar fingerprints.

For example, the embeddings of “happy” and “joyful” will be very close because they mean almost the same thing. But the embeddings of “happy” and “car” will be very different because they are unrelated.


Decoding Step 2: Adding Positional Information

There’s one crucial detail here. The Encoder processes all input tokens at the same time, not one by one. This is great for speed, but it also means the model has no idea which word comes first, second, or third.

To the model, “I love AI” and “AI love I” look exactly the same. But their meanings are completely different.

Positional Encoding solves this problem. It adds a special numerical vector to each embedding that represents the word’s position in the sequence. The first word gets a different positional vector from the second, and so on.

You can think of it like seat numbers in a theater. Even if all the audience members arrive at the same time, their seat numbers clearly tell us where each person should sit. Positional encoding is the seat number for every word.

After this step, the positional encoding vector is added directly to the embedding. Now each token carries a single numerical vector that encodes both the meaning of the word and its position in the sentence.

Decoding Step 3: Attention Mechanism

This is the core of the Transformer. The attention mechanism is the most important idea that makes everything work.

Attention allows every word in a sentence to look at all the other words and decide how much attention it should pay to each of them.

Consider this sentence: “The cat sat on the mat because it was tired.”

When the model processes the word “it”, it needs to figure out what “it” refers to. Is it the cat? Or the mat? The attention mechanism helps the model focus more on “cat” and less on “mat”, because in this context, “cat” is more relevant to “it”.

How Attention Works

Each word is transformed into three things:

  • Query (Q): What this word is looking for
  • Key (K): What this word can offer
  • Value (V): The actual information this word carries

We have a detailed blog post on Math behind Attention - Q, K, and V that explains how these vectors are actually calculated.

The process works as follows:

First, each word uses its own Query to perform a dot product with the Keys of all other words. This produces attention scores — numbers that tell the model how strongly related each pair of words is. These scores are then scaled (divided by √dₖ) to keep them in a manageable range. We also have a detailed blog on Scaling Dot Product Attention that explains why this step is necessary. After scaling, the scores are normalized through softmax, turning them into probabilities that sum to 1. Finally, the model performs a weighted sum of all the Values according to these probabilities.

The result is that each word now carries information not only about itself, but also about the words most relevant to it. The word “it” now carries a strong signal from “cat”, because the attention mechanism has discovered the connection between them.

In simple terms, attention lets every token borrow useful information from other relevant tokens before moving on to the next layer.

Multi-Head Attention

A Transformer doesn’t run attention just once. It runs it multiple times in parallel, each time from a different perspective. This is called multi-head attention.

You can think of it as a team of editors reviewing an article. One editor checks grammar, another checks factual accuracy, and another checks flow and style. Each editor is looking at the same article but focusing on different aspects. Together, they produce a complete review.

Each head in multi-head attention focuses on a different type of relationship between words. One head might focus on subject-verb relationships, while another focuses on which adjective modifies which noun. The outputs from all heads are then combined, allowing the model to develop a rich understanding of the text.

Below is a simplified diagram of multi-head attention. All heads run in parallel on the same input, and their outputs are merged at the end:

markdown
Input
                  |
   -------------------------------
   |       |       |       |     |
 Head 1  Head 2  Head 3  ...  Head N    (all running in parallel)
   |       |       |       |     |
   -------------------------------
                  |
              Combined
                  |
                Output

Decoding Step 4: Feed-Forward Neural Network

After the attention mechanism processes the words, the output is passed into a feed-forward network.

You can think of it as a refinement step. If attention is about understanding relationships between words, then the feed-forward network is about deepening the understanding of each word itself.

It takes the enriched representations produced by attention and further processes them — amplifying useful signals and removing noise. Each word passes through the same feed-forward network independently.

Decoding Step 5: Residual Connections and Layer Normalization

Inside each layer, there are two other important components that help the Transformer learn effectively. Let’s look at them one by one.

Residual Connection (Skip Connection): After each sub-layer (either attention or feed-forward network), the original input to that sub-layer is added back to its output. You can think of it like taking notes in class. Even when the teacher adds new information, we keep the original notes and then integrate the new content. This prevents the model from losing important information as data passes through many layers.

In simple terms, the output of each sub-layer is:
output = sub-layer(input) + input

Layer Normalization: After each residual connection, the numbers are normalized — adjusted to a stable range. This prevents values from becoming too large or too small after passing through many layers. It makes the training process more stable and smoother.

These two components appear in every layer of both the encoder and the decoder.


Decoding Step 6: Stacking Multiple Layers

Now comes the really interesting part. So far, we’ve been talking about one multi-head attention sub-layer and one feed-forward sub-layer. These two sub-layers (along with their respective residual connections and layer normalization) together form one layer of the Transformer. You can think of a layer as a complete package: a multi-head attention sub-layer plus a feed-forward sub-layer.

The Transformer doesn’t use just one such layer. It stacks multiple layers on top of each other. This is where its real power comes from.

Each of these layers is also called a Transformer block. So when we say “this model has 96 layers,” it means the model consists of 96 Transformer blocks stacked sequentially. Each block has its own multi-head attention sub-layer and its own feed-forward sub-layer.

Note: Layer stacking is different from multi-head attention. Multi-head attention runs multiple attention heads in parallel within a single attention sub-layer. Stacking layers, on the other hand, places complete Transformer blocks one after another in sequence, so the output of one layer becomes the input to the next.

Below is a simple diagram of stacked Transformer layers. Each layer is a complete block, connected sequentially:

markdown
Input
          |
  -----------------
  |   Layer 1     |    (multi-head attention + feed-forward)
  -----------------
          |
  -----------------
  |   Layer 2     |    (multi-head attention + feed-forward)
  -----------------
          |
         ...
          |
  -----------------
  |   Layer N     |    (multi-head attention + feed-forward)
  -----------------
          |
        Output

The original Transformer used 6 layers in both the encoder and the decoder. Modern LLMs use many more — for example, GPT-3 (175B) uses 96 layers.

Each layer builds upon the understanding of the previous one. You can think of it as reading the same book multiple times. The first read gives you a basic understanding. The second read reveals connections you missed before. The third read brings even deeper insights. Each additional layer is like reading the book again — your understanding becomes richer and richer.

Decoding Step 7: Encoder In-Depth

Now that we understand these basic building blocks, let’s see how they come together inside the encoder.

The encoder’s job is to read and understand the input.

Each encoder layer consists of two main components:

  • Self-Attention: Each word looks at all the other words in the input to understand their relationships.
  • Feed-Forward Network: Independently refines the representation of each word.

Both components are followed by a residual connection and layer normalization.

Let’s see what happens when the sentence “I love learning” passes through the encoder.

In the first layer, the self-attention mechanism allows each word to look at all the others. The word “love” begins to notice that “I” is its subject and “learning” is its object. The feed-forward network then further refines this understanding.

By the second layer, these relationships become richer. “Love” no longer just knows “I” and “learning” separately — it starts to understand the combined meaning of “I love learning” as a complete idea.

By the sixth layer, each word carries a deep, context-aware representation. The word “learning” is no longer just its dictionary definition; it now also encodes that, in this specific sentence, it is the thing that “I” love.

After passing through all the encoder layers, we obtain a rich understanding of the input. This understanding is then passed on to the decoder.

Decoding Step 8: Decoder In-Depth

The decoder’s job is to generate the output one token at a time.

Each decoder layer has three main components:

  • Masked Self-Attention: Each output word can only attend to all previous output words — it cannot look at future words, because they don’t exist yet during generation. For example, when generating the word “love”, it can look at “I” but not at “learning”, since “learning” has not been generated yet. This restriction is called causal masking. We have a detailed blog post that explains exactly how it works.

  • Cross-Attention: This is how the decoder connects to the encoder. Every output word attends to the encoder’s output, pulling in relevant information from the input. Here, the Queries come from the decoder, while the Keys and Values come from the encoder’s output. This is what makes it different from self-attention and serves as the bridge between “understanding the input” and “generating the output.”

  • Feed-Forward Network: The same refinement step used in the encoder.

After these three components, residual connections and layer normalization are applied, just like in the encoder.

How the Decoder Chooses the Next Word

Here’s the key question: after the output passes through all the decoder layers, how does the decoder actually pick the next real word? At this point, the output is still a vector of numbers, not a word.

So the decoder first sends these numbers through a linear layer, which converts them into a score for every word in the vocabulary. If the vocabulary contains 50,000 words, we get 50,000 scores.

Then, softmax turns these scores into probabilities — numbers between 0 and 1 that sum to 1. The model then selects the next word based on these probabilities. In practice, models use different strategies such as temperature, top-k, and top-p sampling to control whether the output is more creative or more focused. For simplicity, let’s assume it simply picks the word with the highest probability.

For example, if the model is translating “I love learning” into French and has already generated “J’”, after the linear layer and softmax the probabilities might look like this:

  • “adore”: 0.72
  • “aime”: 0.15
  • “mange”: 0.01
  • … (50,000 words, most with extremely small probabilities)

The model will choose “adore” because it has the highest probability. This is how the decoder decides on the next output word.

Decoding Step 9: The Complete Process

Now that we’ve learned all the individual components, let’s walk through the full workflow with a concrete example. The best way to understand this is to follow along with a specific case.

Suppose we want to translate “I love learning” into French.

Encoder Stage

The English sentence “I love learning” goes through the following steps:

Tokenize: “I love learning” is split into three tokens: “I”, “love”, “learning”.

Embed: Each token is converted into a numerical vector (embedding).

Add position: Positional encoding is added so the model knows that “I” is the 1st token, “love” is the 2nd, and “learning” is the 3rd.

Pass through 6 encoder layers: In each layer, self-attention allows every word to look at all the other words, while the feed-forward network refines the understanding. Residual connections and layer normalization keep everything stable.

After all 6 layers, the encoder produces a rich representation of the input. Each word now carries deep contextual information. This representation is passed to the decoder.

Decoder Stage

The decoder generates the French words one by one.

Generating “J'” (1st word):

The decoder starts with a special “start” token. Since this is the first token, masked self-attention has nothing to look back at. Cross-attention examines the encoder’s output to understand the English input. The output then passes through a linear layer and softmax. The model selects “J'” as the most probable first word.

Generating “adore” (2nd word):

The decoder now has [“start”, “J'”]. Masked self-attention looks at “start” and “J'” to understand what has been generated so far. Cross-attention again consults the encoder’s output to extract relevant information from the English input. The linear layer and softmax produce probabilities. The model selects “adore”.

Generating “apprendre” (3rd word):

The decoder now has [“start”, “J'”, “adore”]. Masked self-attention looks at these three previous tokens. Cross-attention connects to the encoder’s output. The model selects “apprendre”.

Generating the “end” token:

The decoder generates a special “end” token, signaling that the translation is complete.

Final output: “J'adore apprendre” (which means “I love learning” in French).

This is how a Transformer works from start to finish.

Three Variants

The original Transformer uses both an encoder and a decoder. However, we don’t always need both. This leads to three main variants:

Encoder-Only (e.g. BERT)

Only the encoder is used. The model reads and understands the input but does not generate new text. It is suitable for tasks such as classifying emails as spam or not spam, understanding the sentiment of reviews, or finding answers within a given text.

Decoder-Only (e.g. GPT)

Only the decoder is used. The model generates one token at a time. Each token can attend to all previous tokens but cannot look at future tokens. This is the architecture behind most modern LLMs. It is used for text generation, answering questions, writing code, and having conversations.

Encoder-Decoder (e.g. T5, original Transformer)

Both parts are used. The encoder understands the input, and the decoder generates output based on that understanding. It is ideal for translation, summarization, and other tasks that convert one type of text into another.

We can choose the most appropriate variant according to our specific use case.

Transformer Why So Powerful

Now that we’ve fully decoded the entire architecture, let’s understand why it changed everything:

Parallel processing: The encoder processes all input tokens simultaneously instead of one by one. Even the decoder can run in parallel during training. This makes training dramatically faster and allows the model to learn from massive amounts of data.

No more long-range forgetting: Thanks to attention, every token can directly “look at” every other token. The first word is just as accessible as the 1000th word, largely solving the long-distance memory problems that plagued earlier models.

Scalability: As the number of layers, attention heads, and training data increases, the model keeps getting stronger. This is why we now have models with billions (and even trillions) of parameters. Parameters are simply the numbers the model learns during training.

Versatility: The same architecture can handle a vast range of tasks — translation, question answering, text generation, code writing, summarization, and more. One design, countless applications.

The Transformer is the core architecture behind the entire modern AI revolution. It allows us to accomplish incredibly complex tasks in a remarkably simple way.


Quick Recap

Let’s review everything we’ve decoded:

  • Tokenization and Embedding convert words into numbers the model can process.
  • Positional Encoding adds order information because all tokens are processed in parallel.
  • Attention lets every token look at all other tokens and decide which ones to focus on. Multi-head attention does this from multiple perspectives.
  • Feed-Forward Networks independently refine each token’s representation.
  • Residual Connections and Layer Normalization keep the numerical values stable as data flows through many layers.
  • The Encoder stacks these building blocks to read and understand the input.
  • The Decoder adds cross-attention to connect with the encoder and uses a linear layer + softmax to pick the next token.
  • There are three main variants: encoder-only for understanding, decoder-only for generation, and encoder-decoder for converting one type of text into another.

We have now decoded the Transformer architecture piece by piece and understood how it actually works.

Prepare for AI Engineering Interviews: AI Engineering Interview Questions

That’s it for this series.