# LLM Foundation Models Explained: Transformer Architectures (Part 2)

> This article introduces the three major Transformer architectures behind today's LLMs: Encoder-only (like BERT), Encoder-Decoder (like T5), and Decoder-only (like the GPT series). It also covers common NLP task types, evaluation metrics, and the evolutionary path of large language models to help readers quickly grasp the structure and characteristics of foundation models.

- Source: https://www.waytoagi.com/en/kb/learning-path/llm-base-model-overview
- Original (Feishu, Chinese): https://waytoagi.feishu.cn/wiki/UU9pwtOFtiKIqAkQiSVc3Zdun7e
- Updated: 2026-12-02

---

> Author: Xiao A, aaronxic, [Zhihu Profile](https://www.zhihu.com/people/aaronxic)
>
> Publication Date: July 8, 2023
>
> Original Link: https://zhuanlan.zhihu.com/p/640784855
![](https://www.waytoagi.com/api/kb-media/DvyobgAm6oUtoPxgtIscynzanhg)


## Introduction

Hello everyone, I’m Xiao A. Today I’m bringing you the second article in this series, which mainly introduces the three common Transformer architectures found in LLM base models: **encoder-only**, **encoder-decoder**, and **decoder-only**.


## Quick Overview of NLP Tasks

Before diving into the network structures of LLMs, let’s first briefly review the types of tasks that fall under NLP (Natural Language Processing). They are mainly divided into three major categories:

- **Natural Language Understanding (NLU)**. These tasks involve seeing the complete context and then performing generalized classification. Typical examples include text sentiment analysis, part-of-speech tagging, information retrieval, etc.

- **Conditioned Natural Language Generation (conditioned-NLG)**. These are seq2seq tasks. Classic examples are machine translation, automatic summarization, and so on.

- **Unconditioned Natural Language Generation (unconditioned-NLG)**. These involve open-ended sentence generation. Representative tasks include question answering (QA), conversational chatbots (ChatBot), etc.

In the early days, different models were used for different tasks. Later, it was discovered that NLG models could also handle NLU tasks through **in-context learning + prompting**. As a result, the field gradually converged toward NLG-style models.


## Evaluation Metrics

As mentioned in the previous article, entropy-like metrics (such as cross-entropy) are commonly used during training to indicate model convergence and can also be used for simple evaluation on test sets (e.g., Perplexity). However, for rich and complex downstream applications, these metrics are far from sufficient.

Deriving all possible metrics from first principles is not realistic. The following is a simplified reference to the metrics listed in the HELM paper. You don’t need to study them in depth — just getting a general idea is enough.

- **Accuracy**
  - Information retrieval tasks: **NDCG@K**, which primarily measures whether the most relevant documents are ranked sufficiently high.
  - Summarization tasks: Usually evaluated with **ROUGE**. ROUGE is a family of metrics with four major categories. The simplest is ROUGE-2, which segments both the prediction and ground truth into 2-grams, counts their frequencies, and calculates the recall between them.
  - Text generation tasks: **Bits-per-Byte**, which is conceptually similar to the Perplexity metric.

- **Calibration and Uncertainty**
  - For binary classification tasks, **ECE (Expected Calibration Error)** is commonly used. It measures how well the model’s predicted probability *p* aligns with the actual correctness rate.

- **Robustness**. Divided into two types:
  - **Invariance**: Adding noise that does not change semantics (e.g., changing case, introducing typos).
  - **Equivariance**: Using contrast sets to alter semantics — for example, changing key words and phrases to flip a positive review into a negative one.

- **Fairness**: Checks whether the model’s outputs are fair. For instance, swapping gender or race to see if the output changes.

- **Bias and Stereotypes**: Examines whether the model exhibits bias or stereotypical impressions — e.g., whether it assumes “Asians are good at studying and can play the piano.”

- **Toxicity**: Assesses whether the model’s outputs contain toxic or harmful content.

## The Evolution Tree of LLMs

After gaining a basic understanding of NLP, let’s look at a widely circulated diagram. This chart contains a large amount of information. The most important observation is that it clearly diverges into three distinct branches. From left to right, they are:

- The pink branch: **Encoder-only** framework (also known as Auto-Encoder), with typical representatives such as BERT.
- The green branch: **Encoder-Decoder** framework, with typical representatives such as T5 and GLM.
- The blue branch: **Decoder-only** framework (also known as Auto-Regressive), with typical representatives such as the GPT series, LLaMA, PaLM, etc.

![](https://www.waytoagi.com/api/kb-media/Nz80bm5KUo0Kkyxeks5cnIM1nsb)

**Harnessing the Power of LLMs in Practice**

At first, these three framework names may sound a bit confusing. Don’t worry — let’s build some intuition first. As shown below:

- The horizontal axis represents input tokens, and the vertical axis represents the corresponding output token at each position.
- The left diagram is **Encoder-only**: every output token can see all input tokens. For example, the row for `y_1` can see inputs `x_1 ~ x_5`.
- The middle diagram is **Decoder-only**: each output token can only see historical input tokens. For example, the row for `y_3` can only see inputs `x_1 ~ x_3`; it cannot see `x_4` and `x_5`.
- The right diagram is **Encoder-Decoder**: the first *k* output tokens can see all *k* input tokens. Starting from the (*k*+1)th output token, it can only see historical input tokens. For example, `y_1` (and `y_3`) can see inputs `x_1 ~ x_3`, while starting from `y_4`, it can only see inputs `x_1 ~ x_4`.

![](https://www.waytoagi.com/api/kb-media/Gqn3brNsuoIW6cxYVzccPv1YnJc)

**PS**: For easier understanding, the encoder-decoder structure is simplified here using “causal with prefix” for illustration. See the dedicated Encoder-Decoder chapter for details.

These three different LLM architectures are typically good at handling different types of tasks. A summary is provided below:

> 📊 This is an embedded Feishu content (table/whiteboard, etc.). [View the full version in the Feishu Knowledge Base](https://waytoagi.feishu.cn/wiki/UU9pwtOFtiKIqAkQiSVc3Zdun7e)

## Encoder-only (BERT)

Although GPT-1 appeared earlier than BERT, BERT seems to have had a greater impact. Therefore, we will use BERT as the starting point to introduce the basic structure of the Transformer.

### GEMM-like Operators

From a macro perspective, the structure of BERT is very simple. The Base and Large models consist of 12 and 24 repetitions of the basic Transformer block, respectively.

![](https://www.waytoagi.com/api/kb-media/LY77b1YBRocsD5xI4mecJgSGneb)

BERT-base and BERT-large

There is abundant information online about the detailed structure of the Transformer block. Here, we will try to explain it from a dataflow perspective. As shown below, it mainly consists of three types of structures:

- **MHA (Multi-Head Attention)**: Multi-head attention module (green part in the figure below).
- **Add & Norm**: Normalization module (blue part in the figure below).
- **FFN**: Feed-forward network module (pink part in the figure below).

![](https://www.waytoagi.com/api/kb-media/UGp7bB1UMoXa4BxP3q0c4bXGnAb)

BERT Transformer block

The parameters of the GEMM-like operators are summarized in the table below, where **B** is batch size, **L** is sequence length, **A** is the number of heads, **d** is the feature dimension per head, and note that **D = A × d**.

> 📊 This is an embedded Feishu content (table/whiteboard, etc.). [View the full version in the Feishu knowledge base](https://waytoagi.feishu.cn/wiki/UU9pwtOFtiKIqAkQiSVc3Zdun7e)

From the table above, it is straightforward to derive the formulas for the parameter count and computational cost of a single Transformer block:

- **Parameter count**: 3D² + D² + 4D² + 4D² = **12D²**  
  (Note: Only dense operators have parameters)

- **Computational cost**: 12BLD² + 2BDL² = **12LD² + 2DL²**  
  (assuming B = 1)

We can see that both the parameter count and computational cost are independent of the number of heads. The division into multiple heads is primarily a way to improve accuracy through feature subspace partitioning, rather than to save parameters or computation.

When we substitute specific values of L and D into the expressions, we can obtain the parameter counts for BERT-base and BERT-large (where the feature length of each token in the vocabulary is D).

> 📊 This is an embedded Feishu content (table/whiteboard, etc.). [View the full version in the Feishu knowledge base](https://waytoagi.feishu.cn/wiki/UU9pwtOFtiKIqAkQiSVc3Zdun7e)

### LayerNorm

**Post-Norm vs. Pre-Norm**

BERT originally used a Post-Norm structure. GPT-1 from the same period also adopted this structure, while later GPT-2 switched to Pre-Norm.

![](https://www.waytoagi.com/api/kb-media/FVgTbT6eioOoU5xozEdcofRonbh)

Post-LN vs. Pre-LN vs. Sandwich-LN

Pre-Norm is easier to tune than Post-Norm, but the final model accuracy is slightly lower than that of Post-Norm. To explain this phenomenon, we can start by considering the following question:

**Question**: For a structure of the form **x + F(x)**, where should the normalization be inserted?

- **Method 1 (Post-Norm)**: The naive approach — normalize after the residual connection:  
  x_{t+1} = Norm(x_t + F(x_t))

- **Method 2 (Pre-Norm)**: The “lazy” approach — normalize only when needed:  
  x_{t+1} = x_t + F(Norm(x_t))

Before expanding the recurrence, let’s first recall the computation formula for Norm. Assume x and y are independent random variables with mean 0 and variance 1:

Norm(x + y) = (x + y − E(x + y)) / √Var(x + y) = (x + y − E(x) − E(y)) / √(Var(x) + Var(y)) = (x + y) / √2

Simplifying Method 1’s recurrence using the above formula gives:

x_{t+1} = (x_t + F_t(x_t)) / √2 = x_t/√2 + F_t(x_t)/√2

Recursively expanding this, we eventually obtain:

x_t = x_0 / 2^{t/2} + F_0(x_0) / 2^{t/2} + F_1(x_1) / 2^{(t-1)/2} + F_2(x_2) / 2^{(t-2)/2} + ⋯ + F_{t-1}(x_{t-1}) / √2

It can be seen that the “ancient” features from the bottom layers are heavily attenuated — for example, scaled down by a factor of 2^{t/2}. This causes the residual channel to exist in name only, making the network much harder to train. This explains why Post-Norm is difficult to tune.

Similarly, by expanding the recurrence formula of Method 2, we obtain:

$$
x_t = x_0 + F_0(x_0) + F_1(x_1/\sqrt{2}) + F_2(x_2/\sqrt{3}) + \cdots + F_{t-1}(x_{t-1}/\sqrt{t})
$$

From this we can see that:

- The variance of the output will be very large, so an extra LayerNorm needs to be added after the output (as done in GPT-2).
- Pre-Norm effectively makes the actual depth of the network shallower while increasing its width.
- The layer count of a Pre-Norm network contains “moisture” (i.e., is somewhat inflated), which may be one reason why the final accuracy of Pre-Norm models is usually lower than that of Post-Norm models.

A summary of the characteristics of the two normalization strategies is as follows:

- **Post-Norm** weakens the effect of residual connections. It preserves full depth but is difficult to converge and tune.
- **Pre-Norm** turns the network into a shallower but wider structure. It converges easily but incurs some loss in final accuracy.

### Sandwich-Norm

In addition to the two positions above, there is a third variant called **Sandwich-Norm**, which adds one more LayerNorm on top of the Pre-Norm structure.

### Deep-Norm

Later, an improvement based on Post-Norm was proposed: **Deep-Norm**, which enables stable training of Transformers with up to 1000 layers. The authors provide an empirical table for choosing the hyperparameters $\alpha$ and $\beta$, which can be used directly.

```python
def deepnorm(x):
    return LayerNorm(x * alpha + f(x))

def deepnorm_init(w):
    if w in ['ffn', 'v_proj', 'out_proj']:
        nn.init.xavier_normal_(w, gain=β)
    elif w in ['q_proj', 'k_proj']:
        nn.init.xavier_normal_(w, gain=1)
```

Besides the placement of normalization, another source of confusion regarding LayerNorm is its exact reduction behavior:

- In CV, for an input feature of shape (B, C, H, W), **LayerNorm** performs reduction along the C, H, and W dimensions, producing mean and std of shape (B, 1, 1, 1).
- In CV, for the same input, **InstanceNorm** performs reduction only along the H and W dimensions, producing mean and std of shape (B, C, 1, 1).
- In NLP, for an input of shape (N, L, D), **LayerNorm** performs reduction along the D dimension only, producing mean and std of shape (N, L, 1). The learnable parameters $\gamma$ and $\beta$ have shape (1, 1, D).

From the above, it is clear that LayerNorm in the NLP context is essentially equivalent to InstanceNorm in the CV context.

So far we have covered:

- Three different positions for placing normalization: **Post-Norm**, **Pre-Norm**, and **Sandwich-Norm**.
- Two normalization methods: **LayerNorm** and **Deep-Norm**.

### GeLU Activation Function

You are probably already familiar with **GeLU** (Gaussian Error Linear Unit). Its Chinese name is Gaussian Error Linear Unit. The idea was inspired by both ReLU and Dropout.

- ReLU multiplies by 0 when the input is small.
- Dropout randomly multiplies by 0.
- GeLU multiplies by 0 in a probabilistic manner (but unlike Dropout, it uses a deterministic mathematical expression).

Assume $X$ is a random variable that follows a standard Gaussian distribution. Then:

$$
\text{GeLU}(x) = x \cdot P(X \leq x) = x \Phi(x) = x \cdot \frac{1}{2}\left[1 + \text{erf}\left(\frac{x}{\sqrt{2}}\right)\right]
$$

where

$$
\text{erf}(z) = \frac{2}{\sqrt{\pi}} \int_0^z e^{-t^2} \, dt
$$

Here $P(X \leq x)$ means integrating the Gaussian probability density function up to $x$. The smaller $x$ is, the smaller this integral becomes.

- When $x = -\infty$, $P(X \leq x) = 0$.
- When $x = \infty$, $P(X \leq x) = 1$.

The shape of the function is shown in the left figure below. In deployment, it is commonly approximated using tanh, as shown in the right figure:

$$
x\Phi(x) \approx \frac{1}{2}x\left[1 + \tanh\left(\sqrt{\frac{2}{\pi}}(x + 0.044715x^3)\right)\right]
$$

![](https://www.waytoagi.com/api/kb-media/AjqUbYIv4oKAZLxxwXYckeFen8c)

### Attention Softmax

The core formula of Multi-Head Attention (MHA) consists of two batched matrix multiplications (BMM) with a Softmax in between (often called the “sandwich” structure):

$$
\text{Attention}(Q, K, V) = \text{softmax}\left(\frac{QK^T}{\sqrt{d_k}}\right)V
$$

Here’s an interesting operation: dividing by \(\sqrt{d_k}\), i.e., dividing by the square root of the feature dimension. The importance of this step is often underestimated. The derivation is as follows.

It is easy to see that each element of \(QK^T\) is obtained by summing \(d_k\) element-wise multiplications. Assuming that every element in \(Q\) and \(K\) already has zero mean and unit variance, then each element in the attention matrix has mean 0 and variance \(d_k\):

$$
\text{Var}(QK^T) = \text{Var}\left(\sum_i^{d_k} q_i k_i\right) = \sum_i^{d_k} \text{Var}(q_i) \text{Var}(k_i) = d_k
$$

From the properties of the Gaussian distribution, we know that most of the energy lies within \(3\sigma\), i.e., in the range \([-3\sqrt{d_k}, 3\sqrt{d_k}]\). If \(d_k = 64\), the Gaussian range becomes \([-24, 24]\). After the softmax operation, the difference in magnitude becomes enormous — the “wealth gap” is too large (e.g., \(e^{-24}\) vs \(e^{24}\)), which is detrimental to model convergence.

Therefore, to keep the variance of \(QK^T\) within a reasonable range, we need to divide by \(\sqrt{d_k}\).

In addition, the **bmm–softmax–bmm** sandwich structure is crucial for accelerating Transformers. There is a lot of related work in this area, such as FastTransform and FlashAttention. More details will be covered in the later TVM quantization and deployment chapters.

### Tokenization

Tokenization is where all the beautiful stories in NLP begin — just like how photons in CV pass through the ISP to become pixel values. However, determining the right granularity for tokenization is not an easy task. Early approaches were mainly word-based and character-based, but both had drawbacks:

- **Word-based**: The vocabulary becomes far too large because there are too many unique words.
- **Character-based**: The sequence becomes excessively long, and individual characters carry little semantic meaning.

A trade-off solution emerged: **subword-based** tokenization. The principle for splitting into subwords is:

- Break rare words into more frequently occurring parts.
- Do not break frequent words into multiple pieces.

**Byte-Pair Encoding (BPE)** is the most commonly used tokenization method in current state-of-the-art language models.

- Start with individual characters (bytes), count their frequencies, build the initial vocabulary, and mark the end of each word with a special separator.
- Count the frequency of every pair of adjacent tokens, merge the most frequent pair into a new token, add it to the vocabulary, and update the frequencies.
- Repeat this process until the vocabulary reaches the preset size.
- For a detailed derivation, see [this article](https://towardsdatascience.com/byte-pair-encoding-subword-based-tokenization-algorithm-77828a70bee0).

BERT uses **WordPiece**, which is an improved version of BPE. Both are subword tokenizers. It is generally accepted that **1 token ≈ 0.75 words**.

In addition, BERT uses a vocabulary of 30k tokens, where each token is represented by a learnable vector of dimension \(D\).

### Position Encoding

![](https://www.waytoagi.com/api/kb-media/MfkWbHpZeo6coqxK15hcnBibnPd)

Since the attention mechanism in Transformers is inherently position-agnostic, but tokens in language modeling are ordered, position information must be injected into the Transformer architecture. This is the role of **position encoding**. Early approaches used absolute encoding schemes, assigning each token position a static, unique vector. Common methods included sinusoidal (triangular) position encoding and learnable position embeddings.

The original Transformer paper (*Attention Is All You Need*) used **sinusoidal (triangular) position encoding**:

- It has a flavor of Fourier spectrum transformation, aiming to represent different feature dimensions (analogous to frequencies) using combinations of cosine and sine functions.
- For example, in BERT-base where `dim = 768`, 384 groups of trigonometric functions are used.
- The frequencies of these trigonometric functions form a geometric sequence from \((2\pi, 10000 \cdot 2\pi]\) (note: left-open, right-closed). The common ratio is \(q = 10000^{1/(d/2)}\).
- The frequency of the \(k\)-th group is \(f_k = 2\pi \cdot 10000^{2k/d}\), where \(k = 1, \cdots, d/2\).
- The corresponding angular frequency is \(w_k = 2\pi / f_k = 1 / 10000^{2k/d}\).
- Ultimately, the sinusoidal position encoding for the \(t\)-th token at the \(k\)-th feature dimension is:

**Positional Encoding Formula**

$$
f^i(t) =
\begin{cases}
\sin\left(\frac{1}{10000^{2k/d}} \cdot t\right), & \text{if } i = 2k \\
\cos\left(\frac{1}{10000^{2k/d}} \cdot t\right), & \text{if } i = 2k + 1
\end{cases}
$$

For a deeper understanding of trigonometric absolute positional encoding, you can refer to this [blog post](https://link.zhihu.com/?target=https%3A//kexue.fm/archives/8231).

BERT uses **learnable positional encodings**. The preset number of positions is 512, so the maximum sequence length is 512.

### BERT Training

![](https://www.waytoagi.com/api/kb-media/PLrvblUXRoq6fax28cucVXIdnZe)

**BERT Pre-training & Fine-Tuning**

During unsupervised pre-training, BERT uses two tasks:

![](https://www.waytoagi.com/api/kb-media/DgcWbVyenoL9X0xFGAYcR9fGnvf)

**BERT Pre-training Tasks**

- **Masked LM task**: Randomly mask some tokens and let the model predict the masked words based on the surrounding context.
- **Next Sentence Prediction task**: Determine whether two sentences are consecutive in the original text.

In the fine-tuning stage, the pre-trained network weights are reused:

- For classification tasks, the vector of the `[CLS]` token can be passed through a softmax layer for supervised training.
- For more complex tasks, the output vectors of the corresponding tokens can be passed through a softmax layer for supervised training.

### Limitations of BERT

Although BERT is simple to train, it has two notable limitations:

- **Limitation 1**: It does not handle consecutive masked tokens well.
- **Limitation 2**: It cannot be directly used for variable-length text generation tasks.

Later, we will see how the encoder-decoder architecture improves upon these two issues.

## Encoder-Decoder

From the introduction to BERT, we already know that an encoder-only architecture allows every output token to attend to all past and future input tokens. This is naturally well-suited for NLU tasks. However, for seq2seq tasks such as machine translation, this structure is not a perfect fit, as it is relatively difficult to directly use it for generating translation outputs.

A straightforward solution is to add a decoder for predictive generation, which forms the encoder-decoder architecture, as shown below:

![](https://www.waytoagi.com/api/kb-media/SSLBb0zdQo6EixxN6OucxgZEn5c)

**Classic Transformer Block**

- The first MHA in the decoder is changed to masked-MHA, using the causal attention mask from the preceding text. This ensures that each current output token can only attend to previously generated tokens.
- The decoder adds a second MHA, where the K and V come from the encoder’s output. This enables the model to attend to the entire original input.

At this point, we can summarize the two main ways of implementing encoder-decoder architectures:

![](https://www.waytoagi.com/api/kb-media/NFQkbG0j4oVvchxB0TTcllI9nah)

- **Separated**: The standard original structure. A and B use fully-visible attention masks, while C uses a causal attention mask.
- **Fused**: The first half uses fully-visible attention, and the second half uses causal attention. D corresponds to a “causal with prefix” attention mask.

### T5

T5 (Text-to-Text Transfer Transformer) is one of the representative works of the first type of encoder-decoder architecture. Developed by Google, its two core contributions are:

- Reformulating all four major NLP tasks as text-to-text problems — taking text as input and producing text as output. This includes machine translation, question answering, summarization, and text classification.
- The introduction of the C4 (Colossal Clean Crawled Corpus) dataset, which is 750GB in size.

The overall usage is shown below. The model is prompted with prefix instructions to guide it toward the desired output. Both “cola” and “stsb” are part of the nine datasets in the GLUE benchmark, a classic NLU dataset.

![](https://www.waytoagi.com/api/kb-media/Pq7jbh21noKmFJxn0MnciK2pnAd)

In terms of network architecture, T5 introduces several improvements over the standard Transformer:

- It removes the beta parameters from LayerNorm and the dense layers in the FFN, which reportedly leads to more stable training.
- It moves LayerNorm from outside the residual block to inside, placing it after the MHA instead of before it as in pre-norm.
- It adopts a simple relative positional encoding with a maximum distance of 128 tokens.

The training process consists of two stages: pre-training and fine-tuning, as illustrated below:

- Pre-training draws inspiration from SpanBERT by masking spans of consecutive tokens and replacing them with sentinel tokens `<M>`. The decoder is then required to predict the content at those sentinel positions.
- In the fine-tuning stage, multiple tasks are mixed. Task-specific prefixes are prepended to the original training samples, and the model is trained directly.

![](https://www.waytoagi.com/api/kb-media/R8Abbsb0KoHcQHxDfUFcy6FXnEg)

**T5 Pre-training & Fine-tuning**

![](https://www.waytoagi.com/api/kb-media/Ur6ube9Reo8dexxtyDXcsbtknWc)

### GLM-130B

GLM (General Language Model) is a foundational model proposed by Tsinghua University. It belongs to the Prefix LM paradigm. According to the authors, their motivation was:

- To achieve state-of-the-art performance simultaneously across three types of NLP tasks.
- To avoid the doubled computational cost typically introduced by a standard encoder-decoder architecture.

Viewed from another angle, this paper can be seen as an attempt to improve BERT by addressing two of its major shortcomings:

- Shortcoming 1: Poor handling of consecutive masked tokens → The solution is to merge consecutive mask tokens into a single `[M]` token.
- Shortcoming 2: Inability to directly perform variable-length text generation → The solution is to allow arbitrary-length expansion at the `[M]` position.

The resulting approach is to first use a bidirectional encoder to “understand” the prompt (the given context), and then use a decoder-only style to expand and answer at the `[M]` positions. The final network resembles a weight-sharing version of an encoder-decoder, which significantly reduces computational cost.

The specific implementation is shown below. The key lies in constructing **seq A** and **seq B**:

![](https://www.waytoagi.com/api/kb-media/LYVxbdaykoTgtyxsJAocxICHn1c)

- From sequence A, sample several groups of consecutive tokens and replace them with the mask token [M]. As shown in the figure below, in the original text `x_1 x_2 x_3 x_4 x_5`, `x_3` and `x_5 x_6` are replaced by [M], resulting in `x_1 x_2 [M] x_4 [M]`. This becomes seq A.

- Randomly shuffle the order of all tokens at the [M] positions in seq A and add the prefix [S]. For example, after swapping the order of `x_3` and `x_5 x_6` and adding the prefix, the new sequence becomes `[S] x_5 x_6 [S] x_3`. This becomes seq B.

- Concatenate seq A and seq B. Within seq A, attention is bidirectional (part A in the right figure (d) above). Seq B uses unidirectional (causal) attention: it can see information from seq A but cannot see subsequent information in seq B (parts B+C in the right figure (d) above).

- The correct labels come from the next token in the original text. Note that at the end of each group, the model is required to output the [E] token to indicate the termination of the current group.

- Position encoding uses a two-level hierarchical scheme:
  - Position 1 represents the character’s position index in the original text. Note that tokens within the same [M] group use the position of [M] in seq A.
  - Position 2 represents the relative offset within the group. For seq A, this defaults to 0.

- Additionally, depending on the number of mask tokens, three masking strategies can be freely configured: word-level (MASK), sentence-level (sMASK), and document-level (gMASK).

When fine-tuning GLM on downstream tasks, the approach is as follows:

![](https://www.waytoagi.com/api/kb-media/GtdNbIojFo8cAExLDQxcyBdHnMf)

**GLM Fine-tuning**

- For classification tasks, a template sentence is added. For example, for sentiment classification, the template `It is really [M]` is used, and seq B performs classification token prediction at the [M] position.

- For generation tasks, simply pad a [M] token at the end of seq A. Seq B then performs continuation (next-token prediction) at the [M] position to achieve text generation.

GLM-130B is a relatively late model that incorporated several newer techniques:

- It adopted the Post-Deep-Norm normalization method.
- It used the GeGLU activation function.

**GeGLU Activation Function**

The GeGLU activation function consists of two parts: GeLU and GLU. Among them, GLU (Gated Linear Unit) is a bilinear function with the general form:

$$
\text{GLU}(x, W, V, b, c)=\sigma(xW+b)\otimes (xV+c)
$$

where ⊗ denotes element-wise multiplication. The first part uses sigmoid activation and the second is linear. GeGLU simply replaces the sigmoid with GeLU:

$$
\text{GeGLU}(x, W, V, b, c, \beta)=\text{GeLU}(xW+b)\otimes (xV+c)
$$

### UL2

UL2 (Unifying Language Learning Paradigms) is an improved version of T5 and also belongs to the encoder-decoder architecture.

UL2 is somewhat similar to GLM. It further develops and unifies the masked-span paradigm by abstracting three variables to parameterize masked-span prediction:

- Span length — one parameter:
  - $\mu$: average number of tokens per span

- Number of spans — two alternative parameters:
  - $r$: probability of a masked span occurring
  - $n$: number of masked spans

With the parameterized masked-span, the authors proposed three masking strategies: R-Denoiser, S-Denoiser, and X-Denoiser, as shown below:

![](https://www.waytoagi.com/api/kb-media/O9g5bPSVfoFnhYx7ooQcyr5zn4Y)

Assuming the input sequence length is $L$, the three masking strategies can be parameterized as follows:

- **R-Denoiser** (Regular Denoising): mimics the T5 approach. Span length $\mu=3$ or $8$, span occurrence probability $r=0.15$.

- **S-Denoiser** (Sequential Denoising): mimics the decoder-only approach. Span length $\mu=L/4$, number of spans $n=1$.

- **X-Denoiser** (Extreme Denoising): simulates long-sequence generation under severely limited information, lying between R-Denoiser and S-Denoiser. Span length $\mu=3$ or $8$ or $64$, span occurrence probability $r=0.5$.

## Decoder-only

Finally, let’s look at the decoder-only family, which is currently the hottest and most dominant architecture. It is clearly the most prolific and robust branch. This family contains a very large number of large language models. Since this article focuses primarily on LLM base models, topics such as instruction tuning, Reward Models, and RLHF will be covered in the next article, “How Are ChatBots Trained?”

### GPT Series

First, we look at OpenAI’s flagship GPT series. This [article](https://link.zhihu.com/?target=https%3A//www.notion.so/GPT-3-5-360081d91ec245f29029d37b54573756%3Fpvs%3D21) provides a very detailed overview of the relationships between all GPT models. The key evolutionary path is highlighted in blue boxes. As you can see, all of these developments came after GPT-3. This tuning process is generally referred to as **alignment**, with the goal of making the model communicate in a more human-like way—gradually transforming the raw LLM base model into a ChatBot.

![](https://www.waytoagi.com/api/kb-media/NJYGbdyE8oNYwZxLb1Zc8Drsnif)

Below we examine the changes in the Transformer architecture from the foundational works GPT-1, GPT-2, and GPT-3. Unfortunately, the changes are actually quite minor: the main updates are switching from Post-Norm to Pre-Norm and adding a final LayerNorm before output. The following diagram is borrowed from [here](https://link.zhihu.com/?target=https%3A//blog.csdn.net/weixin_36378508/article/details/121809595).

![](https://www.waytoagi.com/api/kb-media/YsexbZsIQomTgyxMfYbci0xNnTg)

GPT-1/2/3 primarily explored how to achieve better generation performance. GPT-2 attempted to solve tasks in a zero-shot manner but found it extremely difficult. As a result, GPT-3 shifted toward few-shot learning.

One noteworthy feature of decoder-only models is that they can use **KV-cache** technology during inference. This is because the causal attention mask ensures that past information cannot be altered. You only need to store the attention matrix from previous tokens; when a new token arrives, you only compute the new row, while the columns for future positions are simply filled with `-inf`.

(Of course, this also brings the disastrous side effect of a very low compute-to-memory-access ratio, which significantly increases the difficulty of deployment and acceleration.)

![](https://www.waytoagi.com/api/kb-media/OTLFbcxv1o4RKyxTmjMcgkBfntb)

Decoder-only attention mask

GPT only truly began to shine starting with GPT-3.5. The details will be covered in the next article, “How Are ChatBots Trained?”

### LLaMA

Meta is undoubtedly the leading force in open-source LLMs, and LLaMA is its flagship. It comes in four different model sizes. The design philosophy was as follows:

- Use only publicly available datasets to ensure everyone has equal access to the training data.
- Train smaller networks with more data—for example, training 7B and 13B models on 1T tokens, and 33B and 65B models on 1.4T tokens. This approach was inspired by the conclusions of the Chinchilla paper.

The network architecture is also decoder-only. Compared with GPT-3, the main similarities and differences are:

- Uses SentencePiece-based BPE tokenizer.
- Adopts Pre-Norm for more stable convergence. It also uses RMSNorm, which is a LayerNorm variant that removes the mean subtraction and beta terms.
- Uses SwiGLU activation (Swish + GeLU gating). Because SwiGLU introduces additional parameter matrices, the original FFN dimensions are scaled down accordingly.
- Employs Rotary Position Embedding (RoPE) proposed by Su Jianlin. The core idea is to achieve relative positional encoding using absolute positional encoding. For the theoretical derivation, see the [original article](https://zhuanlan.zhihu.com/p/359502624).

**RMSNorm**

RMSNorm is the third type of normalization introduced in this article. RMS stands for root mean square:

$$
\text{RMS}(x)=\sqrt{\frac{1}{d}\sum_{i=1}^d x_i^2}
$$

By also removing the beta term, we obtain:

$$
\text{RMSNorm}(x)=\frac{x}{\text{RMS}(x)} \cdot \gamma
$$

**SwiGLU Activation Function**

SwiGLU is very similar to the previously introduced GeGLU, except that the GeLU activation is replaced with Swish:

$$
\text{SwiGLU}(x, W, V, b, c, \beta) = \text{Swish}_{\beta}(xW+b)\otimes (xV+c)
$$

where $\otimes$ denotes element-wise multiplication, and

$$
\text{Swish}_{\beta}(x)=x\sigma(\beta x)
$$

Compared with the first dense multiplication in the original FFN:

FFN$_{\text{expansion}}$(x, W, b) = GeLU(xW + b)

It can be seen that SwiGLU introduces an additional element-wise multiplication term. Therefore, to keep the computational complexity the same as the original, the dense layer in the FFN needs to be correspondingly reduced in size.

![](https://www.waytoagi.com/api/kb-media/OKZDbK5aZoNw4YxsGjCcVX8xnEh)

Starting with LLaMA, the “alpaca army” has continued to grow. Almost all of them are built by performing instruction tuning and RLHF training on top of LLaMA. We will cover this in detail in the next article, “How Are ChatBots Trained?”

### OPT

- OPT was Meta’s earlier open-source model effort. It comes in 8 different sizes. The original motivation was purely out of passion (“for the love of it”), aiming to explore an open-source path that could reproduce GPT-3.

- The model configuration is largely consistent with GPT-3: learnable absolute positional encodings, Pre-LayerNorm, and ReLU as the activation function.

- However, the training process was extremely difficult, with frequent interruptions, adjustments to the learning rate, optimizer changes, etc. The training curves below illustrate this clearly.

- The final model performance was not particularly strong. It struggled with declarative instructions, produced high toxicity, and was prone to repetitive loops.

- For more details, see [this video](https://link.zhihu.com/?target=https%3A//www.youtube.com/watch%3Fv%3Dp9IxoSkvZ-M).

![](https://www.waytoagi.com/api/kb-media/KRbGbGvT4o8rtfxr75IcDvolncg)

OPT training curve

### PaLM

A product from Jeff Dean is bound to be excellent. PaLM once again demonstrates Google’s formidable hardware-software system capabilities. In summary, PaLM was trained using the Pathways framework on 6144 TPUs, with a 540B-parameter model trained on 780B tokens, achieving approximately 50% peak utilization.

The key architectural improvements are as follows:

- SwiGLU activation (already introduced earlier).

- Structural parallelization change: the original serial structure of MHA was changed to parallel. (Yes, they really did that.)

**Serial**
$$
y = x + \text{MLP}(\text{LayerNorm}(x + \text{Attention}(\text{LayerNorm}(x))))
$$

**Parallel**
$$
y = x + \text{MLP}(\text{LayerNorm}(x)) + \text{Attention}(\text{LayerNorm}(x))
$$

- Adopted MQA (Multi-Query Attention) for acceleration. This shares the Key and Value across different heads in MHA, reducing their dimensions to [B·1, L, d], while Query retains the original [B·A, L, d] dimension. Here A is the number of attention heads.

- Positional encoding uses RoPE Embeddings (already introduced earlier).

- Shares the input and output embedding matrices.

- Removes bias terms from the dense layers and LayerNorm to improve training stability.

Finally, a few words about TPUs and the Pathways training framework.

![](https://www.waytoagi.com/api/kb-media/BH4bbJdDEoLz4ixzeBxc9M2Cnkh)

TPU Pod

- Multiple high-speed interconnected hardware computing devices are generally regarded as an “island.” For example, a single GPU node with 8 cards connected via NVLink, or a TPU Pod consisting of up to 1024 cards — the large square matrix of hardware shown above is also called a Pod.

- GPU programming follows the SIMT model. Multiple warps can concurrently switch and execute on an SM, making GPUs preemptive.

- TPUs rely more heavily on compiler scheduling and static orchestration, so they only support serial kernels. Otherwise, Gang Scheduling issues arise — when multiple related programs run simultaneously across multiple executors, deadlocks may occur.

- Therefore, Google believes that a multi-controller architecture is not the future trend for ML systems; a centralized single-controller design is the way forward. (The term “multi-controller” implicitly refers to GPU-style designs.)

- Pathways solved the limitation that JAX could only schedule within a single Pod, extending support to multiple Pods and enabling PaLM’s cross-Pod parallel training.

### LaMDA

LaMDA is the large language model Google announced at the 2021 I/O Developer Conference, specifically designed for dialogue. It has 137B parameters. In addition to the pre-training stage, it also includes a fine-tuning stage.

The LaMDA paper does not go into much detail about the network architecture:

- It uses learnable relative positional encodings, the same as T5.

- It employs GeGLU as the activation function.

### Chinchilla

When it comes to matters concerning humanity’s AGI future, DeepMind cannot be absent. Following Gopher, DeepMind introduced the Chinchilla model, which has fewer parameters but achieves higher accuracy.

In the paper, DeepMind directly answers a core question that everyone cares about:

**Q: Under a fixed computational FLOPs budget, how should one trade off model size against the number of training tokens?**

**A: Model Size and Token Count Are Equally Important**

Using their own Gopher model as the baseline, they trained a model that was only one-quarter the size (approximately 70B parameters) but used 4× more tokens (about 1.4T tokens). The resulting model achieved higher accuracy than Gopher.

The model architecture was largely inherited from Gopher:

- Normalization method: Pre-Layer-Norm
- Positional encoding: Relative positional encoding, drawing from Transformer-XL’s parameter-free sinusoid matrix (i.e., fixed relative PE)

### BLOOM

BigScience is a research-oriented collaborative organization involving Hugging Face as well as French institutions GENCI and IDRIS. Their BLOOM model was trained on the Jean Zay supercomputer operated by IDRIS, using the ROOTS dataset. The training ran on 384 GPUs with the Megatron-DeepSpeed framework, employing 3D parallelism combining Data Parallelism (DP) + Pipeline Parallelism (PP) + Tensor Parallelism (TP).

The BLOOM network architecture is shown below:

![](https://www.waytoagi.com/api/kb-media/EvHvbezOeoVFxyxaPQ4cNt7Wnlh)

**BLOOM architecture**

- A LayerNorm is added after word embedding, which helps with convergence. This was inspired by the StableEmbedding approach from [bitsandbytes](https://github.com/facebookresearch/bitsandbytes).
- Pre-Layer-Norm and GeLU activation are used.
- Positional encoding adopts the ALiBi (Attention with Linear Biases) method.

Below is a brief introduction to ALiBi’s relative positional encoding mechanism.

The motivation behind ALiBi is to improve the extrapolation capability of positional encodings, since the input token length in real-world usage can be much longer than the maximum token length used during training.

The method is straightforward: for the attention matrix entry \( q_i \cdot k_j \), the relative position \( i - j \) is multiplied by a coefficient \( m \) and then directly added to the attention scores.

![](https://www.waytoagi.com/api/kb-media/LLdfbTAOFoLGKCxtkdBchpkynXg)

**ALiBi**

The coefficient \( m \) depends on the total number of heads \( n \). For the \( t \)-th head, the coefficient is calculated as:

\[ m_t = \left( \frac{1}{\sqrt[n]{2^8}} \right)^t, \quad t = 1, \cdots, n \]

For example:

- When there are 8 heads: \( 2^{-1}, 2^{-1.5}, \cdots, 2^{-8} \)
- When there are 16 heads: \( 2^{-0.5}, 2^{-1}, 2^{-1.5}, \cdots, 2^{-8} \)

The author mentioned that the training process was “tight at the beginning and smooth at the end.” In the early stages, many foundational infrastructure and preparation tasks had to be completed, and everyone was under pressure. Once the pipeline was fully operational, however, everything went surprisingly smoothly.

Another highlight of BLOOM is that it provides a concrete demonstration of how to perform DP + PP + TP 3D parallel training based on the Megatron-DeepSpeed framework. This topic will be covered in detail in a later article in this series titled “Distributed Training of LLMs.”

## Final Notes

At the end, we have compiled a summary of the LLM backbone models from the three major families mentioned earlier for easy reference.

Due to space limitations, many excellent LLM models are not covered. For a more complete collection of LLM model information, please refer to [this Survey](https://link.zhihu.com/?target=https%3A//arxiv.org/abs/2303.18223).

> 📊 Feishu embedded content (table/artboard, etc.) is shown here. [View the full version in the Feishu knowledge base](https://waytoagi.feishu.cn/wiki/UU9pwtOFtiKIqAkQiSVc3Zdun7e)

In summary, this article mainly introduced the three common Transformer architectures found in LLM backbone models: encoder-only, encoder-decoder, and decoder-only. The model components discussed include:

- 3 types of Norm positioning: Post-Norm, Pre-Norm, and Sandwich-Norm
- 3 types of Norm methods: LayerNorm, DeepNorm, and RMSNorm
- 3 types of activation functions: GeLU, GeGLU, and SwiGLU
- 6 types of PE methods: Fixed Absolute, Learned Absolute, Fixed Relative, Learned Relative, RoPE, and ALiBi

**Coming up next:** The planned next article is “How Is a ChatBot Built?”, which will focus on instruction tuning, Reward Models, and RLHF-related techniques. Stay tuned.

**P.S.:** Since the author, Aaron, has not personally implemented every detail mentioned above, most of the content was summarized in a bottom-up manner through studying code and carefully reading excellent papers. Essentially, this is a collection and re-organization of knowledge from others — ultimately just “talking on paper.” Therefore, I sincerely welcome experts with real-world experience to critique and correct it. Sparks are born from the collision of ideas, and truth becomes clearer through debate.

If you would like to learn more about Transformer algorithms in NLP, CV, and multimodal domains, knowledge of distributed training, or how to perform PTQ quantization and deployment on TVM, feel free to follow aaronxic~ [Zhihu Profile](https://www.zhihu.com/people/aaronxic)

![](https://www.waytoagi.com/api/kb-media/VLtJbYAowosddkxTiupcjwUVnIh)
