下列文本提取自本地原版 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 查看记录 ↗