Transformer 中正弦位置嵌入的单调区间

文献 On Position Embeddings in BERT 给出 sinusoidal PE (正弦位置嵌入) 在 0 到 50 内满足单调性 (The proximity of embedded positions decreases when positions are further apart), 但没有给出证明. 自己首先想用公式推导一下, 但无从下手, 于是尝试用代码验证一下, 如下.

代码结果与论文结果相差不大. 详细地, 不同嵌入维度的单调区间不一样, 例如: 当维度为 768 (BERT base 的 hidden_dim) 时, sinusoidal PE 在 0 到 45 内满足单调性; 当维度为 1024 (BERT large 的 hidden_dim) 时, sinusoidal PE 在 0 到 64 内满足单调性.

import numpy as np
import matplotlib.pyplot as plt


if __name__ == '__main__':
    d_model = 768

    omega = (1 / 10000) ** (2 * np.arange(1, d_model // 2 + 1) / d_model)
    x_y = np.expand_dims(np.arange(0, 100), axis=-1)

    inner_products = np.sum(np.cos(omega * x_y), axis=-1)
    forward_differences = inner_products[1:] - inner_products[:-1]
    inds = np.nonzero(forward_differences * forward_differences[0] < 0)
    sign_change_at = np.min(inds)
    print(sign_change_at + 1)

    plt.subplot(121)
    plt.plot(inner_products)
    plt.subplot(122)
    plt.axhline(y=0, color='r', linestyle='-.')
    plt.plot(np.sign(forward_differences))
    plt.show()

修改历史

  • 20240419 发布

版权声明

署名-非商业性使用-相同方式共享 4.0 国际许可协议

版权归属: 采石工
本文链接: https://quarryman.cn/article/20240419
版权声明: 除特别声明外, 文章采用《署名-非商业性使用-相同方式共享 4.0 国际》许可协议.