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

Knowledge Base · Learning paths

Transformer Explained: Architecture, Self-Attention, and How It Works

Transformer is the core architecture behind GPT and modern large language models. Based on "Attention Is All You Need," it drops RNNs and CNNs and uses attention alone to process sequences; this guide breaks down the encoder, decoder, self-attention, multi-head attention, and feed-forward networks with simple vector examples.

Transformer architectureself-attentionmulti-head attentionencoder decoderdeep learning

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

We've all been playing with GPT for a while now, and we all know that GPT stands for "Generative Pre-trained Transformer." The first two words are fairly easy to understand, but Transformer is a relatively technical concept. In this article, we'll focus on how Transformer works. The content below involves some linear algebra and probability theory, and I've included some explanations in the specific calculation steps. You can also use AI tools to study the relevant concepts in a targeted way — that will make it easier to follow along.

Basic Concepts

Transformer is a deep learning model whose core idea is "Attention is all you need," a phrase taken from the paper of the same name published by the Google Brain team in 2017. Transformer is mainly used to process sequential data, including the currently hottest NLP tasks. Unlike earlier models, Transformer is built entirely on the attention mechanism and does not use the computational architectures of traditional recurrent neural networks (RNNs) or convolutional neural networks (CNNs).

Model Architecture

The Transformer model consists mainly of two major parts: the encoder and the decoder. Each part is formed by stacking multiple identical layers, and each layer contains a multi-head attention mechanism and a position-wise fully connected feedforward network.

Encoder

You can think of it as converting natural language into vector text, represented by the parameters already present in the model. These parameters contain the original information while also incorporating the relationships between elements within the sequence.

python
 I like cats

For example:

Input: "I like cats"

Convert natural language into word embedding vectors ():

I -> [1, 0]

like -> [0, 1]

cats -> [1, 1]

Self-attention mechanism (covered in detail later)

Output: The encoder outputs a sequence of vectors that represent its understanding of the input sentence.

[1, 0], [0, 1], [1, 1]

Decoder

Based on the encoder's output and the previously generated output, it generates the target sequence step by step — that is, it converts vector text back into natural language.

Here's another example:

Goal: generate the Chinese sentence "I like cats."

Initial input: The decoder receives a start symbol, represented by [0, 0].

Step one, generate "I":

Taking into account the encoder's output and the words generated so far, the decoder decides to generate [1, 0], which in our simplified model corresponds to "I".

Step two, generate "like":

Now the decoder considers the encoder's output [1, 0], [0, 1], [1, 1] and the word generated so far [1, 0] ("I"), and decides to generate [0, 1], which corresponds to "like".

Step three, generate "cats":

Taking all the previous information into account, the decoder generates [1, 1], which corresponds to "cats".

This is a simple conceptual reproduction: once the model obtains parameters with a high degree of matching, it judges the language text to be output one word at a time.

Feedforward Neural Network (FFN)

Its main roles include:

Adding nonlinearity:

Although the self-attention mechanism is very powerful, it is essentially a series of linear operations (weighted sums). By introducing a nonlinear activation function (such as ReLU or GELU) in each layer, the FFN helps the model capture more complex features and patterns.

Enhancing model capability:

The FFN provides additional parameters and computational capacity for each layer of the Transformer, enabling each layer to learn more complex function mappings and thereby improving the expressive power of the entire model.

Processing each position independently:

When processing a sequence, the FFN applies the same transformation independently to each position. This design helps the model retain the information at each position while also learning the complex relationships between different positions.

Calculation Example

We can use a simple calculation example to explain how Transformer's self-attention mechanism works: let's again assume we have a short sentence: "I like what?"

Step 1: Word Embedding:

First, we convert each word in the input sentence into a word embedding vector. Suppose our embedding dimension is 2, and we get the following vectors (these vectors are chosen randomly and are for illustration only):

I = [1, 0]

like = [0, 1]

what = [1, 1]

? = [0, 0]

Step 2: Initialize the Weight Matrices:

In the self-attention mechanism, we need three weight matrices to compute Query, Key, and Value. For simplicity, we assume all three matrices are identity matrices (in practice they are obtained through training).

Step 3: Compute Query, Key, Value:

For each word, we multiply the corresponding vector by the weight matrices for Query, Key, and Value. In this example, since we use identity matrices, Q, K, and V are equal to the word embeddings themselves.

Step 4: Self-Attention Computation:

Next, we compute the self-attention scores. For example, to calculate the attention score for the word "like", we compute the dot product of its Query with the Keys of all words:

e(like, I) = Q(like) · K(I) = [0, 1] · [1, 0] = 0

e(like, like) = Q(like) · K(like) = [0, 1] · [0, 1] = 1

e(like, what) = Q(like) · K(what) = [0, 1] · [1, 1] = 1

e(like, ?) = Q(like) · K(?) = [0, 1] · [0, 0] = 0

We then apply the softmax function to these scores to obtain the attention weights:

Here the formula for Softmax is

For example, for the word "like", softmax is computed as follows:

α(like, I) = exp(0) / (exp(0) + exp(1) + exp(1) + exp(0)) = 0.134471

α(like, like) = exp(1) / (exp(0) + exp(1) + exp(1) + exp(0)) = 0.365529

α(like, what) = exp(1) / (exp(0) + exp(1) + exp(1) + exp(0)) = 0.365529

α(like, ?) = exp(0) / (exp(0) + exp(1) + exp(1) + exp(0)) = 0.134471

This completes one round of weight updating for the output vector.

Step 5: Output Vector Computation:

Using the weights above, we can compute the weighted sum as the output vector:

Output(like) = a(like, I) * V(I) + a(like, like) * V(like) + a(like, what) * V(what) + a(like, ?) * V(?)

In the original vectors, like = [0,1],

After completing the weight update computation, like = [0.5, 0.731059]

From this computation, we can roughly summarize the basic working principle of the Transformer self-attention mechanism: although every element uses the same fully connected layer, each element is computed independently. In multi-head attention, this process is replicated multiple times (hence "multi-head"), with each head using a different set of weights. For example, the recently open-sourced Grok-1 uses a 48-head self-attention architecture.

Step 6: Feed-Forward Neural Network Computation:

After we obtain the updated weights for the "like" vector, we can apply non-linear processing to the vector through a feed-forward neural network. An FFN typically consists of two fully connected layers and a non-linear activation function. We can demonstrate this process with a concrete example:

Assume ReLU is used as the activation function.

Define the two linear layer parameters of the FFN as follows (simplified to 2 dimensions; in practice the dimensions would be higher):

The first layer's weight W1 and bias b1 map from 2 dimensions to some hidden dimension, say 4 (for simplicity, we use 4 directly).

The second layer's weight W2 and bias b2 map from 4 dimensions back to 2.

Assume the parameters are as follows:

First linear transformation:

  • Compute z1 = xW1 + b1, where x = [0.5, 0.731059].

Activation function:

  • Apply the ReLU activation function a1 = max(0, z1).

Second linear transformation:

  • Compute z2 = a1W2 + b2.

Output:

  • The output z2 is the final output of the feed-forward neural network; this output will be passed to the next layer of the model or used for further processing in the decoder.

The specific computation becomes more complex as dimensions increase, so we can use Python instead of manual calculation:

python
import numpy as np


# Define the input
x = np.array([0.5, 0.731059])


# Define weights and biases
W1 = np.array([[1, 2], [3, 4], [5, 6], [7, 8]])
b1 = np.array([1, 1, 1, 1])
W2 = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])
b2 = np.array([1, 1])


# First linear transformation
z1 = np.dot(x, W1.T) + b1  # Note: due to how it is written here, W1 needs to be transposed


# Activation function
a1 = np.maximum(0, z1)  # ReLU

Second Linear Transformation

z2 = np.dot(a1, W2.T) + b2 # Note that W2 also needs to be transposed here

z2


After the feed-forward neural network computation, the new vector representation of "like" [0.5, 0.731059] becomes [79.86354, 186.34826].

This process consists of a linear transformation, a ReLU activation, followed by another linear transformation. In this way, the feed-forward network adds extra non-linear processing to the representation at each position within the Transformer layer, helping to capture more complex features and patterns in the input data. In actual Transformer models, these computations are more complex and involve much higher dimensions, but the fundamental logic remains the same.


## Why Use Transformers Instead of Traditional RNNs or CNNs?

Before the Transformer was introduced, sequence-to-sequence models mainly relied on recurrent neural networks (RNNs) or their variants, such as Long Short-Term Memory (LSTM) networks and Gated Recurrent Units (GRU). Because these approaches must process sequences sequentially, the models suffered from vanishing or exploding gradients when handling long sequences, and their computational efficiency was low.

The Transformer abandons this recurrent computation pattern and uses a parallel processing mode to significantly improve computational efficiency (as shown in our example: “I”, “like”, “what”, “?”). The computation result for each element does not depend on the computation of other elements. The self-attention mechanism allows the model to consider all other elements in the sequence when processing any given element. This global information integration capability greatly enhances the model’s ability to handle long-range dependencies.

Therefore, “Attention is all you need” not only emphasizes the central role of the self-attention mechanism in Transformer models, but also marks a major shift in model architecture within the field of natural language processing. Since then, Transformer-based models such as BERT, GPT, and others have achieved remarkable success across numerous natural language processing tasks, fully demonstrating the effectiveness and versatility of this architecture.