本文介绍了大语言模型如何通过 RoPE 等经典与前沿方法编码和处理 token 位置信息。这是一次全面的探索之旅,我们将结合可视化示例、一些数学推导和小型 PyTorch 实现来逐步剖析其机制。当然,我们也会探讨现代架构如何适配或省略显式的位置编码。
下面是截至 2026 年开源模型中采用的各种位置嵌入选择预览,我们将在讲完底层机制后进一步讨论这些选择。
但为什么要把时间花在这篇关于这一相对次要构建模块的文章上呢?LLM 在不断演进,而我在准备今年最新 LLM 架构趋势文章时发现,我此前从未在任何文章中介绍过 LLM 中使用的位置信息方法。因此,与其让另一篇文章篇幅失控,我认为单独发表这篇作为即将推出的 LLM 架构与趋势分析文章的独立构建模块更为合适。
此外,多年来许多读者都要求我写一篇关于相对位置嵌入(即 RoPE)的教程,以跟上 GPT 中所学绝对嵌入的内容。这早已在我的 TODO 列表中,所以今天我终于重新翻出旧草稿并整理成这篇 walkthrough,将涵盖:
- LLM 中的不同位置方法;
-(终于)RoPE 的工作原理;
- 近期开源 LLM 使用了哪些方法。
请注意,本文假设读者对基础的 LLM 架构有一定了解,适合作为《从零开始构建大型语言模型》的后续阅读。如果你对注意力机制的内部原理(尤其是查询、键和值向量)的概念和计算还有些模糊,建议先复习一下我的自注意力指南:
本文也较为技术化,细节可能对一些读者来说过于深入。不过我确实希望打下这个基础,供后续文章引用。别担心,下一篇文章会回到更轻松的风格。
附:我开始尝试 Substack 的新“福利”系统。作为对支持者的感谢,我已将架构画廊中的图片导出和相关元数据提供给你,可用于你自己的分析。
再附:如果你已经熟悉位置嵌入的工作原理,可以直接跳到第 6 节——现代架构中的位置选择。
请注意,本文在网页浏览器中阅读效果优于邮件客户端。建议在此查看网页版,左侧还有导航栏。
1. 位置信息如何进入 LLM
让我们从整体架构说起。分词器将输入文本编码为 token ID。接下来,LLM 的输入 token 嵌入层将这些 ID 中的每一个映射为一个数值向量。我们通常将该向量中的这些条目称为“特征”(与经典机器学习类似)。LLM 内部的 transformer 块随后通过注意力和前馈层修改这些向量。最后,模型的输出层为下一个 token 生成 logit 分数(转换为概率)。
以下内容展示了这一路径在GPT-2(一种相对经典的LLM)和MiniMax-M3(今年发布的更新型LLM;可代表大多数其他近期llms)中的体现。我们可以看到,两者的架构并无太大差异,但在探讨位置信息部分之前,我们先关注橙色模块(即token embedding layers)及其上方的transformer blocks;其他架构差异本说明无需涉及。
图中所示的token embedding layer将每个token ID映射为vector,之后添加position information。具体而言,正如后文会详细讨论的那样,GPT-2在进入第一个transformer block之前,会在每个token embedding中添加position vector。另一方面,MiniMax-M3则通过attention机制内部的RoPE方法在每个transformer block内添加position information。
我们稍后会详细讨论这些methods,但先来看为什么需要或要添加explicit positional information的总体说明。
1.1 为什么要添加position information?
以以下两个input sentences作为simple example:
- “红色的狐狸跳过了灰色的狐狸。”
- “灰色的狐狸跳过了红色的狐狸。”
改变词序会改变哪只fox进行jumping,如下图所示。
为简化起见,本文的examples中将每个word视为one token。(如您所知,real tokenizers可以将words分割为更小的subword tokens。)因此第一个句子包含8个token positions,从0到7。
# Assume the following small vocabulary.
# Real vocabularies typically have 50k to 200k entries
vocab = {
"The": 0,
"red": 1,
"fox": 2,
"jumps": 3,
"gray": 4,
"over": 5,
"the": 6,
}
(如果你对词汇表是如何构建的感兴趣,可以查看我在 GitHub 上的 tokenizer 相关资料。)注意,输入句子中出现两次的"fox"在两种情况下都获得了相同的 token ID 2。而且因为它们具有相同的 token ID,无论其在输入句子中的位置如何,来自 embedding 层的嵌入向量也会相同。
现在,让我们考虑一种没有位置编码(也没有因果掩码)的常规自注意力机制,在这种机制中,每个输入 token 都可以关注输入中的任何其他 token。在这种场景下,交换任意两个词(如"red"和"gray")仍然会产生相同的嵌入向量和每对 token 之间的注意力分数。
GPT 风格的模型确实使用了因果(自回归)掩码,它将每个 token 的限制范围约束在其自身及更早的 token 上。有趣的是,这种因果掩码为计算提供了一些隐式的顺序信息。在我们的例子中,"jumps"可以在第一句中关注"red",在第二句中关注"gray"。因此,因果 LLM 即使没有显式的位置嵌入,理论上也已经能够区分这两个句子。(我们将在后续讨论"NoPE"概念时回到这个想法。)
尽管如此,GPT-2 和大多数新型 LLM 都包含了显式的位置信息,因为它为注意力提供了关于位置直接信号。这是因为虽然因果掩码决定了哪些 token 是可访问的并提供隐式顺序信息,但它无法区分相隔一个位置和相隔十个位置的差异。因此,显式位置方法仍然有用(甚至是必要的),因为它们提供了这一信息。
如果以上内容听起来令人困惑,别担心,这更多是作为一个概述,我们将在文章的其余部分更慢、更细致地逐步讲解这些概念。
2. 向每个token嵌入添加位置向量
我们曾简要提及通过因果注意力掩码实现的隐式位置信息(稍后会再更详细地回顾这一点)。但现在我们要切换视角,讨论显式添加位置信息的方法。
或许最简单直接的方法(但并非最“廉价”)是为每个序列位置赋予独立向量。我们将该向量加到token嵌入上,这样得到的修改后嵌入向量就会被送入第一个transformer块。以下小节将讨论这一确切流程。
2.1 GPT-2中学习绝对位置嵌入
为了说明如何将显式学习的位置向量添加到输入嵌入中,我们以GPT-2作为具体实例。GPT-2在训练过程中会学习一张位置向量表。下图说明了这些向量在架构中的使用位置,即在token嵌入查表之后、第一个transformer块之前。
图中所示的位置嵌入层与token嵌入层遵循相同的实现方式,即它们具有完全相同的输出维度,以便使生成的输入向量能够相互相加。下面通过GPT-2代码片段展示这一过程:
class GPTModel(nn.Module):
def __init__(self, cfg):
super().__init__()
self.tok_emb = nn.Embedding(cfg["vocab_size"], cfg["emb_dim"])
self.pos_emb = nn.Embedding(cfg["context_length"], cfg["emb_dim"])
self.drop_emb = nn.Dropout(cfg["drop_rate"])
self.trf_blocks = nn.Sequential(
*[TransformerBlock(cfg) for _ in range(cfg["n_layers"])])
self.final_norm = LayerNorm(cfg["emb_dim"])
self.out_head = nn.Linear(
cfg["emb_dim"], cfg["vocab_size"], bias=False
)
def forward(self, in_idx):
```python
batch_size, seq_len = in_idx.shape
tok_embeds = self.tok_emb(in_idx)
pos_embeds = self.pos_emb(torch.arange(seq_len, device=in_idx.device))
x = tok_embeds + pos_embeds # Shape [batch_size, num_tokens, emb_size]
x = self.drop_emb(x)
x = self.trf_blocks(x)
x = self.final_norm(x)
logits = self.out_head(x)
return logits
```
从数学角度,我们可以如下表示。设 $m$ 为位置索引,$x_m$ 为该位置的 token ID。第一个 block 的输入为
$$h_m = E_{\text{token}}(x_m) + P_m$$
其中:
- $E_{\text{token}}$ 是 embedding 层,
- $P_m$ 是由 $m$ 选中的位置信息向量,
- $h_m$ 是得到的求和后的 embedding 与位置向量。
这两个向量的维度相同,因此我们将它们的元素逐个相加。下图 6 用一个小型数值示例直观展示了这一过程。
在上图中,在位置 0,将 token embedding `[1, 1, 1]` 与 position embedding `[1.1, 1.2, 1.3]` 相加,得到 `[2.1, 2.2, 2.3]`。顺便一提,图中的数值是为了让说明更简洁而选取的;在实际例子中,两个 embedding 层(查找表)均使用小的随机值初始化,并在训练过程中进行学习。
因此,本节所介绍的是所谓绝对位置方法(absolute positional method),因为位置 embedding $P_m$ 取决于 token 自身的位置 $m$。在前面的示例句子中,两个 "fox" token 最初具有相同的 token embedding,但由于我们加入了不同的位置向量 $P_2$ 和 $P_7$,它们在进入第一个 transformer block 之前就已经具有了不同的值。因此,注意力机制内部的 query、key 和 value 向量所接收到的表征也已包含了位置信息。
原版 GPT-2 实现包含 1,024 个学习得到的位置向量。这意味着它只能处理不超过 1024 个 token 的输入。如果我们想扩展上下文窗口,就必须扩展这个嵌入表。而且由于该嵌入表(层)在训练过程中像其他层一样被更新,因此上下文长度必须在训练开始前确定。
扩展上下文代价非常高昂,因为该表可能会变得非常大。例如,对于 GPT-2 Medium,位置嵌入层权重仅占总权重的 0.30%,对应 1,024 个位置。然而,如果我们将上下文长度扩展到当今常见的 100k 范围,它们将占模型总权重的 >22%,这在经济上非常不划算。
2.2 原版 Transformer 中的固定正弦/余弦位置编码
2017 年的原始「Attention Is All You Need」Transformer(早于 GPT)使用相同的加法机制,但通过固定的正弦和余弦函数来计算其位置向量。下图 7 展示了在编码器堆栈和解码器堆栈之前所做的加法操作。编码器处理输入序列,解码器生成输出序列。(此处引入的原因在于,在后续讨论 RoPE 时,正弦和余弦函数将再次发挥作用。)
原始 Transformer 还在加入位置向量之前将 token 嵌入缩放 √(dmodel),其中 dmodel 为嵌入宽度。
因此,上一节中 GPT-2 的公式为
原版 Transformer(如图 7 所示)使用的公式为:
这种通过 √(dmodel) 进行的缩放是一个次要的技术细节,但出于好奇的人可能会想了解:transformer 论文中并未解释这一缩放因子的动机,不过正如我在多年前与同事在一条 Twitter 帖子中所讨论的……
本文由 AI图鉴自动抓取并翻译,版权归原作者所有;如需查看原文请点下方链接。
This article explains how LLMs encode and process token position information by covering classic and contemporary methods like RoPE. It’s essentially a comprehensive journey where we will work through the mechanisms with visual examples, a little math, and a small PyTorch implementation. And, of course, we will then also look at how modern architectures adapt or omit explicit positional encodings.
Below, you can find a preview of which positional embedding choices are used in 2026 open-weight models. We will discuss these choices later after covering the underlying mechanisms.
But why spending so much time writing/reading about this rather minor building block? LLMs keep evolving, and as I was preparing a new article on the latest LLM architecture trends this year, I realized that I never covered the positional information methods used in LLMs in any article so far. So, instead of letting the other article get out of hand, I thought it might make sense to publish this as a standalone building block for the upcoming LLM architecture and trends analysis.
Also, over the years, many readers have asked me for a tutorial on relative positional embeddings (aka RoPE) to follow up on the learned absolute embeddings used in GPT. It’s been on my TODO list for a long time, so I finally revisited my old draft and put this walkthrough together, which will cover
- different positional methods in LLMs;
- (finally) how RoPE works;
- what methods are used by recent open LLMs.
Note that this article assumes some familiarity with basic LLM architectures and works well as a follow-up to Build a Large Language Model (From Scratch). If the concepts and computation of the attention internals, particularly query, key, and value vectors, are a little fuzzy, I recommend checking my self-attention walkthrough as a refresher:
The article is also very technical and likely too detailed for some. However, I really wanted to have this foundation out there for future articles to reference. And no worries, the next one will return to a more comfortable style.
PS: I started experimenting with Substack’s new “perks” system. As a thank-you to supporters, I’ve added image exports and metadata from the architecture gallery for you to use in your own analyses.
PPS: If you are already familiar with how position embeddings work, feel free to fast-forward to Section 6, Positional choices in modern architectures.
Note that this article may be best read in a web browser than an email client. I recommend checking out the web view here, which also has a navigation bar on the left side.
1. Where position information enters an LLM
Let’s start with the overall architecture. A tokenizer encodes the input text into token IDs. Next, the input token embedding layer of an LLM maps each of these IDs to a vector of numbers. We usually refer to these entries in that vector as “features” (similar to classic ML). The transformer blocks inside the LLM then modify these vectors using attention and feedforward layers. Lastly, the model’s output layer produces logit scores (converted into probabilities) for the next token.
The following shows this path in GPT-2 (a relatively classic LLM) and MiniMax-M3 (a more recent LLM released this year; a placeholder for most other recent LLMs). As we can see, the architectures are not too different from each other, but before we get to the positional information parts, let’s focus on the orange blocks for now (the token embedding layers) and the transformer blocks above them; the other architecture differences aren’t needed for this explanation.
A token embedding layer, shown in the figure above, maps each token ID to a vector. Position information is then added afterward. Concretely, and as we will discuss in more detail later, GPT-2 adds a position vector to each token embedding before the modified embedding enters the first transformer block. On the other hand, MiniMax-M3 adds the positional information in each transformer block using a method called RoPE inside attention.
We will talk about these methods in more detail later, but first, let’s start with the big picture information explaining why explicit positional information is added or needed.
1.1 Why add positional information?
Consider the following two input sentences as a simple example:
- “The red fox jumps over the gray fox.”
- “The gray fox jumps over the red fox.”
Changing the word order changes which fox does the jumping, as illustrated in the following figure.
For the examples in this article, we will treat each word as one token for simplicity. (As you know, real tokenizers can split words into smaller subword tokens.) The first sentence then has eight token positions, from 0 through 7.
# Assume the following small vocabulary.
# Real vocabularies typically have 50k to 200k entries
vocab = {
"The": 0,
"red": 1,
"fox": 2,
"jumps": 3,
"gray": 4,
"over": 5,
"the": 6,
}
(If you are interested in how vocabularies are built, check out my tokenizer materials on GitHub.)
Note that “fox”, which appears twice in the input sentence, gets the same token ID 2 in both cases. And since they both have the same token ID, irrespective of the position in the input sentence, they would get the same embedding vector from the embedding layer.
Now, let’s consider a regular self-attention mechanism with no positional encoding (and no causal mask), where every input token can attend to every other token in the input. In this scenario, swapping any two words, like “red” and “gray”, would still result in the same embeddings and attention scores between each token pair.
GPT-style models do use a causal (autoregressive) mask, which restricts each token to itself and earlier tokens. Interestingly, this causal mask gives the computation some implicit order information. In our example, “jumps” can attend to “red” in the first sentence and “gray” in the second. So, a causal LLM can theoretically already distinguish these sentences even without explicit positional embeddings. (We will return to this idea later when discussing the “NoPE” concept.)
Nonetheless, GPT-2 and most newer LLMs include explicit positional information because it gives attention a direct signal about positions. That’s because even though the causal mask determines which tokens are accessible and provides implicit order information, it doesn’t distinguish a separation of one position from a separation of ten, for example. So, explicit positional methods are still useful (or even essential), since they supply that information.
If this all sounded confusing, don’t worry, it was more meant as an overview, and we will step through these concepts a bit more slowly in the remaining article.
2. Adding a position vector to each token embedding
We briefly talked about implicit positional information through causal attention masks (and we will revisit this again in more detail later). However, we now switch gears and talk about the explicit ways to add positional information.
The perhaps simplest and most direct (but not “cheapest”) approach is to give each sequence position its own vector. We add that vector to the token embedding, so the resulting, modified embedding vector is then passed to the first transformer block. This exact procedure is discussed in the following subsections.
2.1 Learned absolute position embeddings in GPT-2
To illustrate the use of an explicit, learned positional vector to the input embeddings, let’s consider GPT-2 as a concrete example. GPT-2 learns a table of position vectors during training. The following figure illustrates where these vectors are used in the architecture, that is, immediately after the token embedding lookup and before the first transformer block.
The positional embedding layer depicted in the figure above follows the same implementation as the token embedding layer, i.e., they have exactly the same output dimensions so that the resulting input vectors can be added to each other. The code below shows that with an excerpt of a GPT-2 code implementation:
class GPTModel(nn.Module):
def __init__(self, cfg):
super().__init__()
self.tok_emb = nn.Embedding(cfg["vocab_size"], cfg["emb_dim"])
self.pos_emb = nn.Embedding(cfg["context_length"], cfg["emb_dim"])
self.drop_emb = nn.Dropout(cfg["drop_rate"])
self.trf_blocks = nn.Sequential(
*[TransformerBlock(cfg) for _ in range(cfg["n_layers"])])
self.final_norm = LayerNorm(cfg["emb_dim"])
self.out_head = nn.Linear(
cfg["emb_dim"], cfg["vocab_size"], bias=False
)
def forward(self, in_idx):
batch_size, seq_len = in_idx.shape
tok_embeds = self.tok_emb(in_idx)
pos_embeds = self.pos_emb(torch.arange(seq_len, device=in_idx.device))
x = tok_embeds + pos_embeds # Shape [batch_size, num_tokens, emb_size]
x = self.drop_emb(x)
x = self.trf_blocks(x)
x = self.final_norm(x)
logits = self.out_head(x)
return logits
And in mathematical terms, we can write it as follows. Let m be a position index and xm the token ID at that position. The input to the first block is
Here,
- Etoken is the embedding layer,
- Pm is the position info vector selected by m,
- and hm is the resulting summed embedding and position vector.
The two vectors have the same width, so we add their entries element-wise. Figure 6 below shows this visually with a small numerical example.
In the figure above, at position 0, adding the token embedding [1, 1, 1] to the position embedding [1.1, 1.2, 1.3] gives [2.1, 2.2, 2.3]. By the way, the values in the figure are chosen to keep the illustration simple; in a real example, both embedding layers (tables) are initialized with small random values and learned during training.
So, what we covered in this section is a so-called absolute positional method because the positional embedding Pm depends on the token’s own position m. In the previous example sentence, the two “fox” tokens have initially the same token embeddings, but because we are adding different positional vectors P2 and P7, they have different values before they enter the first transformer block. And consequently, the query, key, and value vectors inside the attention mechanisms then also receive representations that already include position information.
Note that the original GPT-2 implementation has 1,024 learned position vectors. This means it only works with inputs with 1024 or fewer tokens. If we want to extend the context window, we would have to extend this embedding table. And since the embedding table (layer) is updated like any other layer during training, the context length would have to be decided before the training starts.
Extending the context would be very expensive since the table can become very large. For example, in the case of GPT-2 Medium, the positional embedding layer weights only make up 0.30% of the total weights at 1,024 positions. However, if we increased the context length to a nowadays common 100k range, they would make up >22% of the total model weights, which would be very uneconomic.
2.2 Fixed sinusoidal position encodings in the original transformer
The original “Attention Is All You Need” transformer from 2017, which predates GPT, uses the same addition mechanism, but computes its position vectors with fixed sine and cosine functions. Figure 7 below shows this addition before both the encoder and decoder stacks. The encoder processes the input sequence, and the decoder generates the output sequence. (The reason why it’s introduced here is that the sine and cosine functions will become relevant again later when discussing RoPE.)
The original transformer also scales its token embeddings by √(dmodel) before adding the position vectors, where dmodel is the embedding width.
So, while GPT-2 in the previous section had the formula
the formula used in the original transformer (depicted in Figure 7) is:
This scaling by √(dmodel) is a minor technical detail, but for those who are curious, the motivation behind this scaling factor is not explained in the transformer paper, but as I discussed with colleagues on a Twitter thread many years a
Auto-fetched and translated by AI Atlas. All rights belong to the original author.