CS336.wiki
CS336 中文实验手册/Transformer 架构
反馈与讨论
ASSIGNMENT 01 / 3.4.3

旋转位置嵌入 RoPE

2026 春季 · v26.0.3原文 p. 22–23对照 PDF ↗

3.4.3 相对位置嵌入#

为了向模型注入位置信息,本作业使用旋转位置嵌入 RoPE(Rotary Position Embeddings) [21]。

设位置 ii 的查询向量为 q(i)=Wqx(i)∈Rdq^{(i)}=W_qx^{(i)}\in\mathbb{R}^d。对其施加成对旋转矩阵 RiR^i,得到:

q′(i)=Riq(i)=RiWqx(i) q'^{(i)}=R^i q^{(i)}=R^iW_qx^{(i)}

给定常数 Θ\Theta,将第 kk 对相邻元素 q2k−1:2k(i)q_{2k-1:2k}^{(i)} 视为二维向量,旋转角度为:

θi,k=iΘ(2k−2)/d,k∈{1,…,d/2} \theta_{i,k}=\frac{i}{\Theta^{(2k-2)/d}}, \qquad k\in\{1,\ldots,d/2\}

因此,RiR^i 是一个 d×dd\times d 的分块对角矩阵,每个二维块为:

Rki=(cos⁡(θi,k)−sin⁡(θi,k)sin⁡(θi,k)cos⁡(θi,k))(8) R^i_k= \begin{pmatrix} \cos(\theta_{i,k}) & -\sin(\theta_{i,k})\\ \sin(\theta_{i,k}) & \cos(\theta_{i,k}) \end{pmatrix} \tag{8}

完整矩阵为:

Ri=(R1i00⋯00R2i0⋯000R3i⋯0⋮⋮⋮⋱⋮000⋯Rd/2i)(9) R^i= \begin{pmatrix} R^i_1 & 0 & 0 & \cdots & 0\\ 0 & R^i_2 & 0 & \cdots & 0\\ 0 & 0 & R^i_3 & \cdots & 0\\ \vdots & \vdots & \vdots & \ddots & \vdots\\ 0 & 0 & 0 & \cdots & R^i_{d/2} \end{pmatrix} \tag{9}

其中 0 表示 2×22\times2 零矩阵。虽然可以构造完整矩阵,但好的实现应利用其结构更高效地进行变换。

我们只关心给定序列内 token 的相对旋转,因此计算出的正弦、余弦值可以跨层、跨批次复用。若要优化,可以让全部层引用同一个 RoPE 模块,在初始化时预计算二维正弦、余弦缓冲区,并通过 register_buffer(persistent=False) 注册。它们应是缓冲区,而不是 nn.Parameter,因为不需要学习固定三角函数值。

对位置 jj 的键向量 k(j)k^{(j)},同样使用对应的 RjR^j 旋转。该层没有可学习参数。

练习 rope2 分

实现 RoPE

交付物: 实现 RotaryPositionalEmbedding 类,将 RoPE 应用于输入张量。

建议构造方法接收:

参数 类型 含义
theta float RoPE 常数 Θ\Theta。
d_k int 查询与键向量维数。
max_seq_len int 最大输入序列长度。
device torch.device | None = None 缓冲区所在设备。

前向方法接收 x 与 token_positions:前者形状为 (..., seq_len, d_k),应容许任意数量的批次维,返回形状相同;后者形状为 (..., seq_len),指定各 token 沿序列维的位置。

应利用这些位置,沿序列维索引可能预计算好的正弦、余弦张量。

完成 adapters.run_rope,通过 uv run pytest -k test_rope。

一起把这一章读得更好

发现翻译、公式或排版错误?欢迎反馈。概念疑问和学习心得,也可以在本章讨论中交流。

直接选中正文,点击旁边的「反馈这处错误」,即可在页内填写并提交,无需登录。
English original 展开本章英文原文 PDF 文本提取

下列文本提取自本地原版 PDF。图表和公式的准确布局请对照 PDF。

3.4.3 Relative Positional Embeddings
To inject positional information into the model, we will implement Rotary Position Embeddings
[J. Su et al., 2021], often called RoPE. For a given query token 𝑞 (𝑖) = 𝑊𝑞 𝑥(𝑖) ∈ ℝ𝑑 at token position 𝑖, we
will apply a pairwise rotation matrix 𝑅𝑖 , giving us 𝑞 ′(𝑖) = 𝑅𝑖 𝑞 (𝑖) = 𝑅𝑖 𝑊𝑞 𝑥(𝑖) . Here, 𝑅𝑖 will rotate pairs of
                         (𝑖)                                            𝑖
embedding elements 𝑞2𝑘−1:2𝑘 as 2d vectors by the angle 𝜃𝑖,𝑘 = Θ(2𝑘−2)/𝑑      for 𝑘 ∈ {1, …, 𝑑/2} and some
constant Θ. Thus, we can consider 𝑅 to be a block-diagonal matrix of size 𝑑 × 𝑑, with blocks 𝑅𝑘𝑖 for 𝑘 ∈
                                       𝑖

{1, …, 𝑑2 }, with

                                                     cos(𝜃𝑖,𝑘 ) − sin(𝜃𝑖,𝑘 )
                                            𝑅𝑘𝑖 = (                         )                                      (8)
                                                     sin(𝜃𝑖,𝑘 ) cos(𝜃𝑖,𝑘 )

Thus we get the full rotation matrix

                                              𝑅1𝑖 0 0 ⋯ 0
                                              0 𝑅2𝑖 0 ⋯ 0
                                         𝑖
                                        𝑅 =   0 0 𝑅3𝑖 ⋯ 0    ,                                             (9)
                                               ⋮ ⋮ ⋮ ⋱ ⋮
                                                        𝑖
                                              0 0 0 ⋯ 𝑅𝑑/2
                                            (              )
where 0s represent 2 × 2 zero matrices. While one could construct the full 𝑑 × 𝑑 matrix, a good solution
should use the properties of this matrix to implement the transformation more efficiently. Since we only
care about the relative rotation of tokens within a given sequence, we can reuse the values we compute for
cos(𝜃𝑖,𝑘 ) and sin(𝜃𝑖,𝑘 ) across layers, and different batches. If you would like to optimize it, you may use a
single RoPE module referenced by all layers, and it can have a 2d pre-computed buffer of sin and cos
values created during init with self.register_buffer(persistent=False), instead of an nn.Parameter
(because we do not want to learn these fixed cosine and sine values). The exact same rotation process we
did for our 𝑞 (𝑖) is then done for 𝑘(𝑗) , rotating by the corresponding 𝑅𝑗 . Notice that this layer has no
learnable parameters.


 Problem (rope): Implement RoPE (2 points)


    Deliverable: Implement a class RotaryPositionalEmbedding that applies RoPE to the input
    tensor.
    The following interface is recommended:
    def __init__(self, theta: float, d_k: int, max_seq_len: int, device=None) Construct the
       RoPE module and create buffers if needed.
     theta: float   Θ value for the RoPE
     d_k: int   dimension of query and key vectors
     max_seq_len: int    Maximum sequence length that will be input
     device: torch.device | None = None      Device to store the buffer on
    def forward(self, x: torch.Tensor, token_positions: torch.Tensor) -> torch.Tensor Process
       an input tensor of shape (..., seq_len, d_k) and return a tensor of the same shape. Note
       that you should tolerate 𝑥 with an arbitrary number of batch dimensions. You should assume
       that the token positions are a tensor of shape (..., seq_len) specifying the token positions of
       𝑥 along the sequence dimension.
    You should use the token positions to slice your (possibly precomputed) cos and sin tensors along
       the sequence dimension.
    To test your implementation, complete [adapters.run_rope] and make sure it passes uv run
    pytest -k test_rope.

关于这一章的疑问、理解与心得,都可以在这里交流。阅读无需登录;发表评论或回复时使用 GitHub 账号。

正在加载本章讨论…

欢迎交流概念与阅读疑问,请勿发布作业完整实现或题目答案。

输入中文、英文术语或题号,例如 RoPE、检查点、train_bpe。