Skip to content

RoPE手撕疑问 #2

Description

@kennyWFR

作者你好,我想请教一下,RoPE手撕里的方法rotate_half,对于2维向量 [x1, x2]确实可以转换成 [-x2, x1]。但是当维度提高时似乎有一些问题?
例如输入xq为[q0,q1,q2,q3]的时候,我们预期输出是[-q1,q0,-q3,q2],但是使用chunk后翻转的方法会变成[-q2,-q3,q0,q1],并不符合预期。
以下是手撕代码。

def rotate_half(x):

        """
        将张量分成两半并旋转
        Args:
            x: 输入张量 [..., head_dim]

        Returns:
            旋转后的张量 [..., head_dim]
        """
        # x1, x2: [..., head_dim/2]
        x1, x2 = torch.chunk(x, 2, dim=-1)
        # 拼接为 [-x2, x1]: [..., head_dim]
        return torch.cat((-x2, x1), dim=-1)

    # 设 x = [x1, x2],则 rotate_half(x) = [-x2, x1]
Image

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions