开始使用免费开始使用

创建输入嵌入向量

现在开始动手创建您自己的 transformer 模型吧,第一步是为输入的 token ID 生成嵌入向量!

您将定义一个 InputEmbeddings 类,包含以下参数:

  • vocab_size:模型词表大小
  • d_model:输入嵌入向量的维度

torchmath 库,以及将 torch.nn 引入为 nn,都已为您导入。在本课程的练习中会一直使用这些库。

本练习是课程的一部分

使用 PyTorch 的 Transformer 模型

查看课程

练习说明

  • 将模型维度和词表大小分别设置为 d_modelvocab_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)
编辑并运行代码