建立位置編碼
將權杖(token)轉成嵌入向量(embedding)只是第一步,但這些嵌入仍缺少序列中各權杖的位置資訊。為了解決這個問題,Transformer 架構會使用位置編碼(positional encodings),把每個權杖的位置資訊編入其嵌入向量中。
你將建立一個 PositionalEncoding 類別,包含以下參數:
d_model:輸入嵌入向量的維度max_seq_length:最大序列長度(若每個序列長度相同,則為該序列長度)
本練習屬於課程
Transformer Models with PyTorch
練習說明
- 建立一個維度為
max_seq_length乘以d_model的零矩陣。 - 以
position * div_term進行 sine 與 cosine 計算,產生偶數與奇數位置的嵌入值。 - 確保
pe在訓練過程中不是可學習參數。 - 將轉換後的位置嵌入加到輸入的權杖嵌入向量
x上。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
class PositionalEncoding(nn.Module):
def __init__(self, d_model, max_seq_length):
super().__init__()
# Create a matrix of zeros of dimensions max_seq_length by d_model
pe = ____
position = torch.arange(0, max_seq_length, dtype=torch.float).unsqueeze(1)
div_term = torch.exp(torch.arange(0, d_model, 2).float() * -(math.log(10000.0) / d_model))
# Perform the sine and cosine calculations
pe[:, 0::2] = torch.____(position * div_term)
pe[:, 1::2] = torch.____(position * div_term)
# Ensure pe isn't a learnable parameter during training
self.____('____', pe.unsqueeze(0))
def forward(self, x):
# Add the positional embeddings to the token embeddings
return ____ + ____[:, :x.size(1)]
pos_encoding_layer = PositionalEncoding(d_model=512, max_seq_length=4)
output = pos_encoding_layer(token_embeddings)
print(output.shape)
print(output[0][0][:10])