建立輸入嵌入向量
現在要開始打造你自己的 transformer 模型了,第一步是將輸入的權杖 ID 做嵌入!
你將定義一個 InputEmbeddings 類別,包含以下參數:
vocab_size:模型詞彙表的大小d_model:輸入嵌入向量的維度
已為你匯入 torch 與 math 函式庫,以及將 torch.nn 匯入為 nn。這些會在整個課程的練習中持續使用。
本練習屬於課程
Transformer Models with PyTorch
練習說明
- 分別將模型維度與詞彙表大小設為引數
d_model與vocab_size。 - 實例化嵌入層。
- 回傳乘上
self.d_model平方根的嵌入向量。 - 以
vocab_size為 10,000、d_model為 512 來實例化InputEmbeddings,並將其應用於token_ids。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
class InputEmbeddings(nn.Module):
def __init__(self, vocab_size: int, d_model: int) -> None:
super().__init__()
# Set the model dimensionality and vocabulary size
self.d_model = ____
self.vocab_size = ____
# Instantiate the embedding layer
self.embedding = ____
def forward(self, x):
# Return the embeddings multiplied by the square root of d_model
return ____
# Instantiate InputEmbeddings and apply it to token_ids
embedding_layer = ____
output = ____
print(output.shape)