# -*- coding: utf-8 -*-
"""
Created on Fri Feb 28 14:53:30 2025
@author: chengxf2
"""
import torch
import math
import torch.nn as nn
import matplotlib.pyplot as plt
def showEncoding(pe):
plt.figure(figsize=( 12 , 8 ))
plt.imshow(pe, cmap= 'coolwarm' , vmin=- 1 , vmax= 1 )
plt.colorbar()
plt.title( '正弦位置编码' )
plt.xlabel( '维度' )
plt.ylabel( '位置' )
plt.tight_layout()
plt.show()
plt.figure(figsize=( 12 , 6 ))
Dimensions = [ 0 , 21 ]
for d in Dimensions:
plt.plot(pe[:, d], label= f'Dim {d} ' )
plt.legend()
plt.title( '特定维度的正弦位置编码' )
plt.xlabel( '位置' )
plt.ylabel( '值' )
plt.tight_layout()
plt.show()
class PositionalEncoding(nn.Module):
def __init__(self, d_model=128, max_seq_len=100):
super(PositionalEncoding,self).__init__()
#创建一个位置编码矩阵
pe = torch.zeros(max_seq_len,d_model)
position = torch.arange(0, max_seq_len, dtype=torch.float).unsqueeze(1)
div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model))
pe[:,0::2] = torch.sin(position*div_term)
pe[:,1::2] = torch.cos(position*div_term)
self.register_buffer("pe", pe)
def forward(self, x):
batch_size,seq_len, d_model = x.shape
x = x+self.pe[:,:seq_len]
return x
net = PositionalEncoding()
pe = net.pe.numpy()
showEncoding(pe)
三 ROPE(Rotary Position Embedding,旋转位置编码)
一般都是作用再query,key上面,不是直接作用在词向量上
++3.1 公式++
基于Transformer的语言模型通常利用各个标记(token)的位置信息实现自注意力机制如方程(2)所示,通常能够实现不同位置标记之间的知识传递。为了融入相对位置信息,我们需要让查询向量 和键向量 的内积通过一个函数 g 来计算.该函数仅将词嵌入 和它们的相对位置 m - n 作为输入变量。换句话说,我们希望内积仅以相对形式编码位置信息: