C2Medium★ 工业基石 (核心高频)Part C · 位置编码演进
RoPE 旋转位置编码(复数旋转矩阵与张量分块)
现代大模型(LLaMA/Mistral/DeepSeek/Qwen)通用标配,复数平面 2D 旋转保持点积内积的纯相对位置依赖。
⏱️ 时间复杂度:
O(B * H * S * D) 纯逐元素乘加💾 空间复杂度:
O(S * D) 只读旋转缓存🎯 免登录实战自测闭环(先做再看答案)
按「机制回忆 → 关键行填空 → 边界反例 → 追问与错题记录」顺序自测,进度自动保存在本地。
Step 1 · 机制口述与数值稳定性自检
Step 2 · 核心代码关键行补全
import numpy as np
def rotate_half(x: np.ndarray) -> np.ndarray:
"""
将最后一维两两配对交错取负:[-x2, x1, -x4, x3, ...]
常见工业实现:拆分为前半段与后半段 [-x2, x1]
"""
d = x.shape[-1]
x1 =
x2 = x[..., d // 2:]
return np.concatenate([-x2, x1], axis=-1)
def apply_rotary_pos_emb(x: np.ndarray, cos: np.ndarray, sin: np.ndarray) -> np.ndarray:
"""
参数:
x: (B, H, S, D) Query 或 Key 张量
cos, sin: (1, 1, S, D) 预计算的旋转角度矩阵
返回:
旋转后的张量,形状恒为 (B, H, S, D)
"""
return (x * cos) + (rotate_half(x) * sin)
def precompute_rope_freqs(seq_len: int, dim: int, theta_base: float = 10000.0):
"""预计算 cos 与 sin 缓存"""
# 频率维度 half_dim
half_dim = dim // 2
freqs = 1.0 / (theta_base ** (np.arange(0, half_dim) / half_dim))
t = np.arange(seq_len)
# 外积得到角度网格 (S, half_dim)
angles = np.outer(t, freqs)
# 拼接为 (S, dim) 以匹配特征
angles = np.concatenate([angles, angles], axis=-1)
cos = np.cos(angles)[np.newaxis, np.newaxis, :, :] # (1, 1, S, D)
sin = np.sin(angles)[np.newaxis, np.newaxis, :, :]
return
Step 3 · 反例与边界断言核对
💡
实战一句话记忆口诀
两两拆对做复数,x 乘 cos 伴旋转,加上负半分乘 sin,点积内积只看差
📐 核心数学公式与机理推导
### 复数内积恒等性
苏剑林(Jianlin Su)在 2021 年提出 RoPE。其核心诉求是寻找一个变换 和 ,使得它们的内积只依赖于相对位移 :
在 2D 复数平面中,将向量乘以 相当于逆时针旋转 角:
高维空间只需将 维向量拆为 个正交的 2 维子空间,分别独立旋转。
在张量实现中,将 分块变换:
苏剑林(Jianlin Su)在 2021 年提出 RoPE。其核心诉求是寻找一个变换 和 ,使得它们的内积只依赖于相对位移 :
在 2D 复数平面中,将向量乘以 相当于逆时针旋转 角:
高维空间只需将 维向量拆为 个正交的 2 维子空间,分别独立旋转。
在张量实现中,将 分块变换:
🔄 张量维度与形状流转说明
x: (B, H, S, D) -> cos/sin: (1, 1, S, D) -> x * cos + rotate_half(x) * sin -> (B, H, S, D)
🛡️ 数值稳定性自检与边界要点
- rotate_half 的切分实现方式有交错配对与前后半切分两种,必须保证 Q 和 K 的实现完全严格对齐
- RoPE 仅作用于 Query 和 Key,严禁作用于 Value 张量!
- 在长文本扩展时,原始 theta_base=10000 会在高频段分辨率不足,LLaMA-3 将 base 提升至 500000
💻 完整参考代码实现
import numpy as np
def rotate_half(x: np.ndarray) -> np.ndarray:
"""
将最后一维两两配对交错取负:[-x2, x1, -x4, x3, ...]
常见工业实现:拆分为前半段与后半段 [-x2, x1]
"""
d = x.shape[-1]
x1 = x[..., :d // 2]
x2 = x[..., d // 2:]
return np.concatenate([-x2, x1], axis=-1)
def apply_rotary_pos_emb(x: np.ndarray, cos: np.ndarray, sin: np.ndarray) -> np.ndarray:
"""
参数:
x: (B, H, S, D) Query 或 Key 张量
cos, sin: (1, 1, S, D) 预计算的旋转角度矩阵
返回:
旋转后的张量,形状恒为 (B, H, S, D)
"""
return (x * cos) + (rotate_half(x) * sin)
def precompute_rope_freqs(seq_len: int, dim: int, theta_base: float = 10000.0):
"""预计算 cos 与 sin 缓存"""
# 频率维度 half_dim
half_dim = dim // 2
freqs = 1.0 / (theta_base ** (np.arange(0, half_dim) / half_dim))
t = np.arange(seq_len)
# 外积得到角度网格 (S, half_dim)
angles = np.outer(t, freqs)
# 拼接为 (S, dim) 以匹配特征
angles = np.concatenate([angles, angles], axis=-1)
cos = np.cos(angles)[np.newaxis, np.newaxis, :, :] # (1, 1, S, D)
sin = np.sin(angles)[np.newaxis, np.newaxis, :, :]
return cos, sin
🧪 本地测试与正确性断言
可直接复制到本地 Python / Jupyter 验证:
import numpy as np
B, H, S, D = 1, 2, 4, 8
q = np.random.randn(B, H, S, D)
k = np.random.randn(B, H, S, D)
cos, sin = precompute_rope_freqs(seq_len=S, dim=D)
q_rot = apply_rotary_pos_emb(q, cos, sin)
k_rot = apply_rotary_pos_emb(k, cos, sin)
assert q_rot.shape == (B, H, S, D)
assert k_rot.shape == (B, H, S, D)
print("✓ RoPE 旋转位置编码自测通过")🎯 核心工程追问与标准应答
Q1:为什么 RoPE 仅需作用在 Query 和 Key,而不需要对 Value 旋转?
自注意力中 Value 的作用是提供语义内容表征并通过注意力加权求和,其本身并不参与匹配度的内积计算;若对 Value 进行位置旋转,加权求和后的向量将混淆不同相对位置的旋转相位,破坏表征流形。
⚡
想检验本题的肌肉记忆?进入 3 阶闪卡主动回忆盲测
隐藏答案遮罩,自测:审题锚点 ➔ 数理公式机理 ➔ 工业标杆代码与连环追问。3 分钟攻破认知盲区!