位置编码 鼻状,ROPE,ALiBi
Type: Build
Languages: Python
Prerequisites: Phase 7 · 02 (Self-Attention), Phase 7 · 03 (Multi-Head Attention)
Time: ~45 minutes
问题
关注点产品的规模是顺序盲目的.softmax(Q K^T / √d) V通过对式相似性计算.X没有什么在注意力中关心位置.
对于语言,代码,音频,视频,任何有序的东西都意味着,
解决方案是以某种方式注入位置.
- Absolute sinusoidal加入
sin/cos简单,无需学习,不适合超越训练的长度. - RoPE — Rotary Position Embeddings旋转Q和K向量以与位置相对的角度. 编码直在点数中 相对位置. 2026年占主导地位.
- ALiBi — Attention with Linear Biases根据距离,对注意力分数添加一个每头线性罚款. 极好的长度抽出.
截至2026年,基本上每个边境开放模型都使用RoPE:Llama 2/3/4,Qwen 2/3,Mistral,Mixtral,DeepSeek-V3,Kimi.少数长文本模型使用ALiBi或其现代变体.绝对突形是历史性的.
概念
!Sinusoidal absolute vs RoPE rotations vs ALiBi distance bias
绝对的阴影状
预先计算一个固定矩阵PE形状(max_len, d_model)其他:
那么X' = X + PE[:N]模型学会从相模式中读取位置. 失败超出了max_len没有什么告诉模型在2048位置发生什么,当它只看到位置02047时.
子
转换Q和K向量 (不是嵌入式).(2i, 2i+1)其他:
按位置的键进行相同的旋转pos_k点的产品q'_m \cdot k'_n成为一个函数(m - n)只有一个人.the attention score depends only on the relative distance虽然旋转是绝对位置的.
扩展ROPE: base通过这种方式,Llama 3从8K到128K的环境扩展.
鱼
忽略嵌入技巧. 偏见的注意力直接得分:
在哪里?m_h是一个特定的头斜率 (例如 1 / 2^{8h/H}报纸显示,长度抽出比较像座形状,与RoPE在原始训练长度上相匹配.
2026年要选择什么
| Variant | Extrapolation | Training cost | Used by |
|---|---|---|---|
| Absolute sinusoidal | poor | free | original transformer, early BERT |
| Learned absolute | none | tiny | GPT-2, GPT-3 |
| RoPE | good with scaling | free | Llama 2/3/4, Qwen 2/3, Mistral, DeepSeek-V3, Kimi |
| RoPE + YaRN | excellent | fine-tune stage | Qwen2-1M, Llama 3.1 128K |
| ALiBi | excellent | free | BLOOM, MPT, Baichuan |
由于它没有改变建筑,它编码相对位置,它引起了人们的注意.base超参数为长文本细调提供了清洁的按.
建立它
步骤1:突状编码
看到code/main.py计算四行:
def sinusoidal(N, d):
pe = [[0.0] * d for _ in range(N)]
for pos in range(N):
for i in range(d // 2):
theta = pos / (10000 ** (2 * i / d))
pe[pos][2 * i] = math.sin(theta)
pe[pos][2 * i + 1] = math.cos(theta)
return pe在第一层注意力之前,将此添加到嵌入矩阵中.
步骤2:对Q,K应用的RoPE
罗佩在Q和K上在现场运行.
def apply_rope(x, pos, base=10000):
d = len(x)
out = list(x)
for i in range(d // 2):
theta = pos / (base ** (2 * i / d))
c, s = math.cos(theta), math.sin(theta)
a, b = x[2 * i], x[2 * i + 1]
out[2 * i] = a * c - b * s
out[2 * i + 1] = a * s + b * c
return out关键:在位置上将相同的函数应用到Q$m$,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.n他们的点产品接收了一个\cos((m-n) \cdot \theta_i)关注可以免费学习相对位置.
步骤3:ALiBi斜率和偏差
def alibi_bias(n_heads, seq_len):
# slope_h = 2 ** (-8 * h / n_heads) for h = 1..n_heads
slopes = [2 ** (-8 * (h + 1) / n_heads) for h in range(n_heads)]
bias = []
for m in slopes:
row = [[-m * abs(i - j) for j in range(seq_len)] for i in range(seq_len)]
bias.append(row)
return bias # add to attention scores before softmax加入bias[h]对于(seq_len, seq_len)注意力分数矩阵h接着是软max.
步骤4:检查RoPE的相对距离特性
选择两个随机向量a, b旋转(pos_a, pos_b)然后,通过(pos_a + k, pos_b + k)两种点产品必须在浮点误差内匹配.该属性是RoPE的整点,它与绝对的偏移不变,只有相对差距才有意义.
用它
托尔奇2.5+ 运输了RoPE公用品torch.nn.functional生产代码的大部分使用flash_attn或xformers在注意内核内应用RoPE.
from transformers import AutoModel
model = AutoModel.from_pretrained("meta-llama/Llama-3.2-3B")
# model.config.rope_scaling → {"type": "yarn", "factor": 32.0, "original_max_position_embeddings": 8192}Long-context tricks in 2026:
- NTK-aware interpolation.重新扩展
base为了base * (scale_factor)^(d/(d-2))在4K到16K+的时间内. - YaRN.智能的插射,可以在长度的环境中保持注意力缩.
- LongRoPE.微软的2024方法,使用进化搜索来选择每维度尺度的因素.
- Position interpolation + fine-tuning.只是缩小位置,扩展因素, 调整15B代币.
运送它
看到outputs/skill-positional-encoding-picker.md技能选择一个新模型编码策略,考虑到目标背景长度,外分需求和培训预算.
运动
- Easy.绘制一个突形图
PE作为热图的矩阵max_len=512, d=128确认"随着尺寸指数的增长,条纹变得更宽". - Medium.运行NTK知性ROPE扩展. 训练一个小的LM在长度256的序列,然后测试在长度1024的与没有扩展. 测量困难.
- Hard.运用 ALiBi 和 RoPE 在同一注意力模块中. 训练一个4层变压器在长度512的序列复制任务上. 在测试时,将其推移到2048年. 进行降解比较.
关键词
| Term | What people say | What it actually means |
|---|---|---|
| Positional encoding | "Tells attention about order" | Any signal added to embeddings or attention that encodes position. |
| Sinusoidal | "The original one" | sin/cos at geometric frequencies added to embeddings; doesn't extrapolate. |
| RoPE | "Rotary embeddings" | Rotate Q, K by position-dependent angle; dot product encodes relative distance. |
| ALiBi | "Linear bias trick" | Add -m \cdot \lvert i-j \rvert to attention scores; no embedding needed, great extrapolation. |
| base | "RoPE's knob" | The frequency scaler in RoPE; increase to extend context at inference. |
| NTK-aware | "A RoPE scaling trick" | Rescale base so high-frequency dims aren't squeezed when context expands. |
| YaRN | "The fancy one" | Per-dimension interpolation+extrapolation that preserves attention entropy. |
| Extrapolation | "Works beyond trained length" | Can the position scheme serve correct output past max_len seen in training? |
进一步阅读
- Vaswani et al. (2017). Attention Is All You Need §3.5原始的鼻状.
- Su et al. (2021). RoFormer: Enhanced Transformer with Rotary Position Embedding 纸
- Press, Smith, Lewis (2021). Train Short, Test Long: Attention with Linear Biases Enables Input Length Extrapolation
- Peng et al. (2023). YaRN: Efficient Context Window Extension of Large Language Models最新的ROPE扩展.
- Chen et al. (2023). Extending Context Window of Large Language Models via Positional InterpolationMeta的Llama2长文本论文.
- Ding et al. (2024). LongRoPE: Extending LLM Context Window Beyond 2 Million Tokens Phi-3-Long使用的微软方法,并引用在使用它部分.
- HuggingFace Transformers —
modeling_rope_utils.py每一个RoPE扩展方案的生产级实施 (默认,线性,动态,YaRN,LongRoPE,Llama-3).
This free lesson is part of the AI Engineering from Scratch curriculum. Read the full explanation, run the lesson code, and verify the result in the interactive reader or from the repository source.
Browse the complete course catalog or open this lesson on GitHub.