大模型-位置编码RoPE的具体实现

python 复制代码
def precompute_pos_cis(dim: int, end: int = int(32*1024), theta: float =1e6):
    """位置编码预处理

    Args:
        dim (int): 输入的维度
        end (int, optional): 最大输出Token数. Defaults to int(32*1024).
        theta (float, optional): 控制频率衰减的参数. Defaults to 1e6.
    """
    freqs = 1.0 / (theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim)) # freq=1/e^freq,频率的多尺度和dim有关
    t = torch.arange(end ,device = freqs.device) # (end,) 表示输出序列最大长度
    freqs = torch.outer(t, freqs).float() # (end, dim//2),外积,表示每一个位置带有不同频率的旋转
    pos_cis = torch.polar(torch.ones_like(freqs), freqs) # polar(单位阵, 频率阵), 生成复数矩阵
    return pos_cis

解释:

python 复制代码
def apply_rotary_emb(xq,xk, pos_cis):
    """RoPE位置编码

    Args:
        xq (_type_): Q矩阵 (batchsize, seqlen, heads, dim//2)
        xk (_type_): K矩阵 (batchsize, seqlen, heads, dim//2)
        pos_cis (_type_): 预处理后的旋转频率矩阵 (end, dim//2)
    """
    def unite_shape(pos_cis, x):
        """对预处理后的旋转频率矩阵进行广播

        Args:
            pos_cis (_type_): 旋转频率矩阵
            x (_type_): 输入
        """
        ndim = x.ndim # 维度,4 (batchsize, seqlen, heads, dim//2)
        assert 0 <= 1 < ndim
        assert pos_cis.shape == (x.shape[1], x.shape[-1]) # (x.shape[1], x.shape[-1]) = (seqlen, dim//2)
        shape = [d if i == 1 or i == ndim - 1 else 1 for i, d in enumerate(x.shape)] # reshape x = (1, seqlen, 1, dim//2)
        return pos_cis.view(*shape) # reshape pos_cis (1, 1, end. dim//2)
    
    xq_ = torch.view_as_complex(xq.float().reshape(*xq.shape[:-1], -1, 2))
    xk_ = torch.view_as_complex(xk.float().reshape(*xk.shape[:-1], -1 ,2))
    pos_cis = unite_shape(*(pos_cis, xq_))
    xq_out = torch.view_as_real(xq_ * pos_cis).flatten(3)
    xk_out = torch.view_as_real(xk_ * pos_cis).flatten(3)
    
    return xq_out.type_as(xq), xk_out.type_as(xk)      

解释:

相关推荐
Narrastory12 小时前
明日香 - Pytorch 快速入门保姆级教程(一)
人工智能·pytorch·深度学习
Narrastory12 小时前
明日香 - Pytorch 快速入门保姆级教程(二)
人工智能·pytorch·深度学习
程序员打怪兽2 天前
详解Visual Transformer (ViT)网络模型
深度学习
CoovallyAIHub4 天前
仿生学突破:SILD模型如何让无人机在电力线迷宫中发现“隐形威胁”
深度学习·算法·计算机视觉
CoovallyAIHub4 天前
从春晚机器人到零样本革命:YOLO26-Pose姿态估计实战指南
深度学习·算法·计算机视觉
CoovallyAIHub4 天前
Le-DETR:省80%预训练数据,这个实时检测Transformer刷新SOTA|Georgia Tech & 北交大
深度学习·算法·计算机视觉
CoovallyAIHub4 天前
强化学习凭什么比监督学习更聪明?RL的“聪明”并非来自算法,而是因为它学会了“挑食”
深度学习·算法·计算机视觉
CoovallyAIHub4 天前
YOLO-IOD深度解析:打破实时增量目标检测的三重知识冲突
深度学习·算法·计算机视觉
用户1474853079744 天前
AI-动手深度学习环境搭建-d2l
深度学习
OpenBayes贝式计算4 天前
解决视频模型痛点,TurboDiffusion 高效视频扩散生成系统;Google Streetview 涵盖多个国家的街景图像数据集
人工智能·深度学习·机器学习