首页 > 其他分享 >RoPE

RoPE

时间:2023-07-24 17:44:32浏览次数:27  
标签:cis xk bm torch freqs RoPE xq

目录

Su J., Lu Y., Pan S., Murtadha A., Wen B. and Liu Y. RoFormer: Enhanced transformer with rotary position embedding.

原作者的博客已经讲得非常到位了: [here] and [there].

RoPE

  • RoPE 是一种相对位置编码, 特点是它可以像绝对位置编码一样, 在 embedding 上操作后再进行 attention 的运算, 而不限定于在 score 矩阵上操作.

  • 具体的, 假设 \(\bm{x}_m, \bm{x}_n\) 为位置 \(m, n\) 上的两个 embedding, 令:

    \[\bm{z}_m := \mathbf{R}_m \mathbf{W}_q \bm{x}_m, \\ \bm{z}_n := \mathbf{R}_n \mathbf{W}_q \bm{x}_n, \\ \]

    \[\bm{z}_{m}^T \bm{z}_n \]

    就是吸收了相对位置信息 \((m-n)\) 的 score.

  • 其中 \(\mathbf{R} \in \mathbb{R}^{d \times d}\) 是旋转矩阵, 它作用在向量是相当于对两个两个维度地进行旋转. \(\theta_i = 10000^{-2i/d}\) 和最普通的 Sinusoidal 编码保持一致.

  • \(\mathbf{R}\bm{x}\) 有一种更加高效的方式:

  • 下面是 LLaMA 中的实现方式:


def precompute_freqs_cis(dim: int, end: int, theta: float = 10000.0):
    freqs = 1.0 / (theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim))
    t = torch.arange(end, device=freqs.device)  # type: ignore
    freqs = torch.outer(t, freqs).float()  # type: ignore
    freqs_cis = torch.polar(torch.ones_like(freqs), freqs)  # complex64
    return freqs_cis


def reshape_for_broadcast(freqs_cis: torch.Tensor, x: torch.Tensor):
    ndim = x.ndim
    assert 0 <= 1 < ndim
    assert freqs_cis.shape == (x.shape[1], x.shape[-1])
    shape = [d if i == 1 or i == ndim - 1 else 1 for i, d in enumerate(x.shape)]
    return freqs_cis.view(*shape)


def apply_rotary_emb(
    xq: torch.Tensor,
    xk: torch.Tensor,
    freqs_cis: torch.Tensor,
) -> Tuple[torch.Tensor, torch.Tensor]:
    # x: B, S, H, D
    # freqs_cis: S, D // 2
    xq_ = torch.view_as_complex(xq.float().reshape(*xq.shape[:-1], -1, 2)) # (B, S, H, D // 2)
    xk_ = torch.view_as_complex(xk.float().reshape(*xk.shape[:-1], -1, 2)) # (B, S, H, D // 2)
    freqs_cis = reshape_for_broadcast(freqs_cis, xq_) # (1, S, 1, 1, D // 2)
    xq_out = torch.view_as_real(xq_ * freqs_cis).flatten(3)
    xk_out = torch.view_as_real(xk_ * freqs_cis).flatten(3)
    return xq_out.type_as(xq), xk_out.type_as(xk)

标签:cis,xk,bm,torch,freqs,RoPE,xq
From: https://www.cnblogs.com/MTandHJ/p/17577879.html

相关文章

  • Cannot read properties of undefined (reading 'state') 或者 Cannot read propertie
     第一步,先检查是否在main.js中引入store.js 如果检查完都引入了,且还是存在报错,第二步:在package.json将vuex的版本更换为其它版本,并从新yarn安装,建议vuex版本为3.0然后从新启动项目即可解决......
  • Failed to convert property value of type 'java.lang.String' to required typ
    标题:深入了解Spring框架中的类型转换异常概述:在开发过程中,我们经常会遇到类型转换的问题。尤其是在使用Spring框架进行开发时,经常会遇到“Failedtoconvertpropertyvalueoftype'java.lang.String'torequiredtype”的异常。本文将详细介绍这个异常的原因和解决方法,并提供......
  • Python【9】 @property
    Python内置的@property装饰器能把一个方法变成属性调用参考1:https://www.runoob.com/python/python-func-property.html参考2:https://www.liaoxuefeng.com/wiki/1016959663602400/1017502538658208......
  • struts2 jsonplugin includeProperties中对list集合的正则配置
     1、listAttachment.*\.realName 和listAttachment.* 效果一样,元素中所有的属性都json化了   "listAttachment":[{"encodedRealName":"%E8%AE%A1%E5%88%92%E4%BB%BB%E5%8A%A1%E4%B9%A6%E5%88%97%E8%A1%A820111223102409.xls","id":"408080b7......
  • struts2 property 不起作用
    <s:selectid="select_sbTable<s:propertyvalue='#developTache.tacheName'/>"οnchange="changeState('sbTable<s:propertyvalue='#developTache.tacheName'/>')"cssStyle="font-size:10px;&quo......
  • Mybatis属性配置示例(properties)
    属性(properties)这些属性可以在外部进行配置,并可以进行动态替换。既可以在典型的Java属性文件中配置这些属性,也可以在properties元素的子元素中设置。参考官网:https://mybatis.net.cn/configuration.html#properties首先创建数据库配置文件db.propertiesdriver=com.mysql.c......
  • CF1662C European Trip
    CF1662CEuropeanTrip没有限制怎么做?邻接矩阵\(k\)次方。有限制?设\(A\)为邻接矩阵,\(I\)为单位矩阵,\(deg_u\)为\(u\)的度数,步数为\(k\)是的答案矩阵\(R_k\),即\(R_k[u][v]\)应该表示\(u\tov\)长度为\(k\)的合法路径条数。如果我们知道了\(R_1,R_2,\dots,R_......
  • 十七、QPropertyAnimation属性动画
    1.几何动画(1)setStartValue方法设置开始动画(2)setEndValue方法设置结束动画(3)setDuration方法设置动画时间(4)setLoopCount方法设置动画循环次数(5)setEasingCurve方法设置动画的缓和曲线(6)start方法开始执行动画(7)setKeyValueAt方法设置某个时间段的动......
  • @property 更改方法为属性
    importmathclassCircle:def__init__(self,r):self._r=r@propertydefarea(self):#def---->define定义一个函数或方法求面积mianji=round(self._r**2*math.pi,2)#round四舍五入取小数点后2位returnmianji#实例化出1个c1,......
  • 110.Object.defineProperty介绍
    110.Object.defineProperty介绍?Object.defineProperty函数一共有三个参数,第一个参数是需要定义属性的对象,第二个参数是需要定义的属性,第三个是该属性描述符。一个属性的描述符有四个属性,分别是value属性的值,writable属性是否可写,enumerable属性是否可枚举,configurable......