
























Natural Language Processing has undergone a massive evolution in recent years. To understand state-of-the-art models, we first need to look back at how we used to process sequences and the critical bottleneck that led to the invention of Attention.
In traditional Sequence-to-Sequence (Seq2Seq) models—commonly used for tasks like machine translation—the architecture relies on Recurrent Neural Networks (RNNs) and consists of two main components:
The encoder’s final hidden state hTh_T is passed as the initial hidden state of the decoder. This vector—often called the context vector—carries a heavy burden: it must encode all necessary information from the entire input sequence.
The Context Bottleneck
When dealing with long input sequences, a single fixed-size context vector struggles to capture all relevant details. Information inevitably gets lost or diluted, leading to poor model performance on longer text.
To overcome the context bottleneck, the attention mechanism was introduced. It allows the decoder to dynamically focus on different parts of the input sequence at each decoding step, rather than relying on a single static vector.
At decoder timestep tt, the model performs the following operations:
eti=fattn(st−1,hi)e_{ti} = f_{\text{attn}}(s_{t-1}, h_i)
A common mathematical choice for this is:
eti=va⊤tanh(Wa[st−1;hi])e_{ti} = v_a^\top \tanh(W_a [s_{t-1}; h_i])
(Where WaW_a and vav_a are learnable parameters, and [⋅;⋅][\cdot;\cdot] denotes concatenation).
2. Normalize Scores: Use a softmax function to convert the scores into probabilities (attention weights):
αti=exp(eti)∑j=1Texp(etj)\alpha_{ti} = \frac{\exp(e_{ti})}{\sum_{j=1}^T \exp(e_{tj})}
ct=∑i=1Tαtihic_t = \sum_{i=1}^T \alpha_{ti} h_i
In the Seq2Seq model, we can think of the decoder RNN states as Query Vectors and the encoder RNN states as Data Vectors. These get transformed to output Context Vectors. This specific operation is so powerful that it was extracted into a standalone, general-purpose neural network component: the Attention Layer.
To prevent vanishing gradients caused by large similarities saturating the softmax function, modern layers use Scaled Dot-Product Attention. Furthermore, separating the data into distinct “Keys” and “Values” increases flexibility, and processing multiple queries simultaneously maximizes parallelizability.
(Note: The key weights, value weights, and attention weights are all learnable through backpropagation).
K=XWK[NX×DQ]K = X W_K \quad [N_X \times D_Q]
V=XWV[NX×DV]V = X W_V \quad [N_X \times D_V]
E=QKT/DQ[NQ×NX]E = Q K^T / \sqrt{D_Q} \quad [N_Q \times N_X]
Eij=Qi⋅Kj/DQE_{ij} = Q_i \cdot K_j / \sqrt{D_Q}
A=softmax(E,dim=1)[NQ×NX]A = \text{softmax}(E, \text{dim}=1) \quad [N_Q \times N_X]
Y=AV[NQ×DV]Y = A V \quad [N_Q \times D_V]
Yi=∑jAijVjY_i = \sum_j A_{ij} V_j
Depending on how we route the data, attention layers take on different properties:

Under the hood, self-attention boils down to four highly optimized matrix multiplications. However, calculating attention across every token pair requires O(N2)O(N^2) compute.
By taking these attention layers and building around them, we get the modern Transformer:
The Transformer Block
A single block consists of a self-attention layer, a residual connection, Layer Normalization, several Multi-Layer Perceptrons (MLPs) applied independently to each output vector, followed by another residual connection and a final Layer Normalization.
Because they discard the sequential nature of RNNs, Transformers are incredibly parallelizable. Ultimately, a full Transformer Model is simply a stack of these identical, highly efficient blocks working together to process complex sequential data.
The true power of the Transformer lies in its versatility. By simply changing how data is pre-processed and fed into the model, the exact same attention mechanism can solve vastly different problems.
Modern text-generation giants (like GPT-4 or Gemini) are primarily built on decoder-only Transformers. Here is how the pipeline flows:
Who says Transformers are only for text? In 2020, researchers proved that the exact same architecture could achieve state-of-the-art results on images.
[CLS] classification token is used) to make a final prediction about the image.The original “vanilla” Transformer from the 2017 Attention is All You Need paper is rarely used exactly as written today. Researchers have introduced several key modifications to make models train faster, scale larger, and perform better.
The original Transformer applied Layer Normalization after adding the residual connection (Post-Norm). Modern architectures apply it before the Attention and MLP blocks (Pre-Norm). This seemingly minor change drastically improves training stability, allowing researchers to train much deeper networks without the gradients blowing up or vanishing.
Standard Layer Normalization is computationally expensive because it requires calculating the mean to center the data. RMSNorm is a leaner alternative that drops the mean-centering step entirely, scaling the activations purely by their Root Mean Square. This makes training slightly more stable and noticeably faster.
Given an input vector xx of shape DD, and a learned weight parameter γ\gamma of shape DD, the output yy is calculated as:
yi=xiRMS(x)∗γiy_i = \frac{x_i}{RMS(x)} * \gamma_i
Where the Root Mean Square is defined as:
RMS(x)=ϵ+1N∑i=1Nxi2RMS(x) = \sqrt{\epsilon + \frac{1}{N} \sum_{i=1}^N x_i^2}
(Note: ϵ\epsilon is a very small number added to prevent division by zero).
Inside a Transformer block, the output of the attention layer is passed through a Multi-Layer Perceptron (MLP). To understand the modern upgrade, let’s look at the classic setup versus the new standard.
The Classic MLP:
Modern models (like LLaMA) have replaced this with the SwiGLU (Swish-Gated Linear Unit) architecture, which introduces a gating mechanism via element-wise multiplication (⊙\odot):
The SwiGLU MLP:
To ensure this new architecture doesn’t inflate the model’s size, researchers typically set the hidden dimension H=8D/3H = 8D/3, which keeps the total parameter count identical to the classic MLP.
Interestingly, while SwiGLU consistently yields better performance and smoother optimization, the original authors famously quipped about its empirical nature in their paper:
“We offer no explanation as to why these architectures seem to work; we attribute their success, as all else, to divine benevolence.”
As models grow, compute costs skyrocket. MoE is a clever architectural trick to increase a model’s parameter count (its “knowledge”) without proportionately increasing the compute required to run it.
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。