上公式
P
E
(
p
o
s
,
2
i
)
=
s
i
n
(
p
o
s
1000
0
(
2
i
/
d
m
o
d
e
l
)
)
PE(pos, 2i)=sin(\frac{pos}{10000^(2i/d_{model})})
PE(pos,2i)=sin(10000(2i/dmodel)pos)
P
E
(
p
o
s
,
2
i
+
1
)
=
c
o
s
(
p
o
s
1000
0
(
2
i
/
d
m
o
d
e
l
)
)
PE(pos, 2i+1)=cos(\frac{pos}{10000^(2i/d_{model})})
PE(pos,2i+1)=cos(10000(2i/dmodel)pos)
个人理解
先简化一下,我们只看第一个公式,然后
i
i
i也固定住,假设
i
i
i等于0,d_model=128,就变成了这样
P
E
(
p
o
s
)
=
s
i
n
(
p
o
s
)
PE(pos)=sin(pos)
PE(pos)=sin(pos)
再简化一下,用我们熟悉的字母表示一下
f
(
x
)
=
s
i
n
(
x
)
,
x
∈
(
1
,
n
)
f(x)=sin(x),x\in(1,n)
f(x)=sin(x),x∈(1,n)
n代表这个句子一共有n个单词。
这样是不是就一目了然了呢,也就是说,对于任何一个位置,我就用sin函数求个值来表示。但问题是,这个sin函数是不是功能太弱了呢,确实是周期函数了,但是周期只有一个呀(
2
π
2\pi
2π)。解决的方法简单粗暴,我多来几个周期函数不就行了吗,这样就提取了一大堆位置信息,最后把这些位置信息拼接起来,就是总的了。说干就干,这次,我们把
i
i
i的值取2,d_model=128,得到了一个公式
P
E
(
p
o
s
)
=
s
i
n
(
p
o
s
1000
0
4
/
128
)
=
s
i
n
(
p
o
s
1000
0
1
/
32
)
PE(pos)=sin(\frac{pos}{10000^{4/128}})=sin(\frac{pos}{10000^{1/32}})
PE(pos)=sin(100004/128pos)=sin(100001/32pos)
再用我们喜欢的字母表示一下:
f
(
x
)
=
s
i
n
(
1
1000
0
1
/
32
∗
x
)
,
x
∈
(
1
,
n
)
f(x)=sin(\frac{1}{10000^{1/32}}*x),x\in(1,n)
f(x)=sin(100001/321∗x),x∈(1,n)
还记得sin函数的周期怎么求吗?
T
=
2
π
ω
T=\frac{2\pi}{\omega}
T=ω2π
所以我们就得到了新的周期
2
π
∗
1000
0
1
/
32
2\pi*10000^{1/32}
2π∗100001/32
依次类推,我们就有了很多很多的周期函数,把 i i i取值为64(因为d_model=128,所以 i i i最大就是64),可以知道最后一个sin函数的周期是 20000 π 20000\pi 20000π,每个位置信息都被很多的sin函数编码了,位置信息就得到了。
至于为啥又来个cos函数,是因为第一个周期函数用sin函数,第二个周期函数用cos函数,这样交替使用,提取的位置信息不就更丰富了嘛。