大模型-位置编码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)      

解释:

相关推荐
小殊小殊5 小时前
【论文笔记】视频RAG-Vgent:基于图结构的视频检索推理框架
论文阅读·人工智能·深度学习
hans汉斯6 小时前
【数据挖掘】基于深度学习的生产车间智能管控研究
人工智能·深度学习·数据挖掘
brave and determined6 小时前
可编程逻辑器件学习(day34):半导体编年史:从法拉第的意外发现到塑造现代文明的硅基浪潮
人工智能·深度学习·fpga开发·verilog·fpga·设计规范·嵌入式设计
z樾6 小时前
TorchRL-MADDPG
pytorch·python·深度学习
金融小师妹7 小时前
基于机器学习框架的上周行情复盘:非农数据与美联储政策信号的AI驱动解析
大数据·人工智能·深度学习·1024程序员节
盼小辉丶7 小时前
Transformer实战(27)——参数高效微调(Parameter Efficient Fine-Tuning,PEFT)
深度学习·transformer·模型微调
IT阳晨。7 小时前
【神经网络与深度学习(吴恩达)】神经网络基础学习笔记
深度学习·神经网络·学习
智算菩萨7 小时前
类比推理:走向 AGI 的核心能力——《Analogical reasoning as a core AGI capability》深度解读与理论重构
人工智能·深度学习
Forever777777778 小时前
PDF瘦身,告别WPS收费压缩PDF
python·深度学习·pdf·免费
小殊小殊8 小时前
【论文笔记】大型语言模型的知识蒸馏与数据集蒸馏
论文阅读·人工智能·深度学习