CS336.wiki
CS336 中文实验手册/Transformer 架构
反馈与讨论
ASSIGNMENT 01 / 3.3

Linear 与 Embedding

2026 春季 · v26.0.3原文 p. 17–19对照 PDF ↗

3.3 基础组件:Linear 与 Embedding#

3.3.1 参数初始化#

有效训练神经网络往往需要仔细初始化参数。较差的初始化可能导致梯度消失或爆炸。预归一化 Transformer 对初始化较鲁棒,但初始化仍会显著影响训练速度与收敛。

本作业已经较长,具体原理留待作业 3;目前使用以下通常有效的近似配置:

参数 初始化
线性层权重 均值为 0、方差为 2/(din+dout)2/(d_{\mathrm{in}}+d_{\mathrm{out}}) 的正态分布,在 [−3σ,3σ][-3\sigma,3\sigma] 截断。
嵌入矩阵 均值为 0、方差为 1 的正态分布,在 [−3,3][-3,3] 截断。
RMSNorm 全 1。

使用 torch.nn.init.trunc_normal_ 初始化截断正态权重。这是本节原文明确指定的初始化 API。

3.3.2 Linear 模块#

线性层是 Transformer 和一般神经网络的基本组件。首先实现继承 torch.nn.Module 的 Linear 类,执行:

y=Wx(3) y=Wx \tag{3}

遵循多数现代大语言模型,本作业不使用偏置项。

练习 linear1 分

实现线性模块

交付物: 实现继承 torch.nn.Module 的 Linear 类。接口应与 PyTorch 的 nn.Linear 类似,但不包含偏置参数或对应构造参数。

构造方法接收:

参数 类型 含义
in_features int 输入的最后一维大小。
out_features int 输出的最后一维大小。
device torch.device | None = None 参数所在设备。
dtype torch.dtype | None = None 参数数据类型。

forward 接收输入张量,返回执行线性变换后的张量。

要求:继承 nn.Module;调用父类构造函数;以 WW 而不是 W⊤W^\top 的布局存储参数,并包装为 nn.Parameter;不得使用 nn.Linear 或 nn.functional.linear。按前述配置,用 torch.nn.init.trunc_normal_ 初始化权重。

实现适配器 adapters.run_linear。适配器应将给定权重加载到你的模块,可使用 Module.load_state_dict。运行 uv run pytest -k test_linear。

3.3.3 Embedding 模块#

Transformer 的第一层将整数 token ID 映射到 dmodeld_{\mathrm{model}} 维向量空间。需要实现自定义的 Embedding,继承 torch.nn.Module,不能使用 nn.Embedding。

前向方法根据形状为 (batch_size, sequence_length) 的 torch.LongTensor,从形状为 (vocab_size, d_model) 的嵌入矩阵中索引出各 token 的向量。

练习 embedding1 分

实现嵌入模块

交付物: 实现进行嵌入查找的 Embedding 类,接口遵循 PyTorch 内置嵌入模块。

构造方法接收:

参数 类型 含义
num_embeddings int 词表大小。
embedding_dim int 嵌入维数,即 dmodeld_{\mathrm{model}}。
device torch.device | None = None 参数设备。
dtype torch.dtype | None = None 参数类型。

forward 接收 token ID 张量,返回对应嵌入向量。

要求:继承 nn.Module 并调用父类构造函数;将嵌入矩阵初始化为 nn.Parameter;存储布局的最后一维是 d_model;不得使用 nn.Embedding 或 nn.functional.embedding。按前述配置初始化。

实现 adapters.run_embedding,运行 uv run pytest -k test_embedding。

一起把这一章读得更好

发现翻译、公式或排版错误?欢迎反馈。概念疑问和学习心得,也可以在本章讨论中交流。

直接选中正文,点击旁边的「反馈这处错误」,即可在页内填写并提交,无需登录。
English original 展开本章英文原文 PDF 文本提取

下列文本提取自本地原版 PDF。图表和公式的准确布局请对照 PDF。

3.3 Basic Building Blocks: Linear and Embedding Modules
3.3.1 Parameter Initialization
Training neural networks effectively often requires careful initialization of the model parameters—bad
initializations can lead to undesirable behavior such as vanishing or exploding gradients. Pre-norm
transformers are unusually robust to initializations, but they can still have a significant impact on
training speed and convergence. Since this assignment is already long, we will save the details for
assignment 3, and instead give you some approximate initializations that should work well for most cases.
For now, use:
                                   2
• Linear weights: 𝒩︀(𝜇 = 0, 𝜎2 = 𝑑 +𝑑 ) truncated at [−3𝜎, 3𝜎].
                                    in   out
                           2
• Embedding: 𝒩︀(𝜇 = 0, 𝜎 = 1) truncated at [−3, 3]
• RMSNorm: 𝟙
You should use torch.nn.init.trunc_normal_ to initialize the truncated normal weights.

3.3.2 Linear Module
Linear layers are a fundamental building block of Transformers and neural nets in general. First, you will
implement your own Linear class that inherits from torch.nn.Module and performs a linear
transformation:

                                                 𝑦 = 𝑊 𝑥.                                            (3)

Note that we do not include a bias term, following most modern LLMs.


 Problem (linear): Implementing the linear module (1 point)


   Deliverable: Implement a Linear class that inherits from torch.nn.Module and performs a linear
   transformation. Your implementation should follow the interface of PyTorch’s built-in nn.Linear
   module, except for not having a bias argument or parameter. We recommend the following
   interface:
   def __init__(self, in_features, out_features, device=None, dtype=None) Construct a linear
       transformation module. This function should accept the following parameters:
    in_features: int    final dimension of the input
    out_features: int    final dimension of the output
    device: torch.device | None = None     Device to store the parameters on
    dtype: torch.dtype | None = None     Data type of the parameters
   def forward(self, x: torch.Tensor) -> torch.Tensor Apply the linear transformation to the
       input.
   Make sure to:
   • subclass nn.Module
   • call the superclass constructor
   • construct and store your parameter as 𝑊 (not 𝑊 ⊤ ), putting it in an nn.Parameter
   • of course, don’t use nn.Linear or nn.functional.linear
   For initializations, use the settings from above along with torch.nn.init.trunc_normal_ to
   initialize the weights.
   To test your Linear module, implement the test adapter at [adapters.run_linear] . The adapter
   should load the given weights into your Linear module. You can use Module.load_state_dict for
   this purpose. Then, run uv run pytest -k test_linear.


3.3.3 Embedding Module
As discussed above, the first layer of the Transformer is an embedding layer that maps integer token IDs
into a vector space of dimension d_model. We will implement a custom Embedding class that inherits from
torch.nn.Module (so you should not use nn.Embedding). The forward method should select the embedding
vector for each token ID by indexing into an embedding matrix of shape (vocab_size, d_model) using a
torch.LongTensor of token IDs with shape (batch_size, sequence_length).


 Problem (embedding): Implement the embedding module (1 point)


   Deliverable: Implement the Embedding class that inherits from torch.nn.Module and performs an
   embedding lookup. Your implementation should follow the interface of PyTorch’s built-in
   nn.Embedding module. We recommend the following interface:

   def __init__(self, num_embeddings, embedding_dim, device=None, dtype=None) Construct an
       embedding module. This function should accept the following parameters:
     num_embeddings: int    Size of the vocabulary
     embedding_dim: int    Dimension of the embedding vectors, i.e., 𝑑model
     device: torch.device | None = None     Device to store the parameters on
     dtype: torch.dtype | None = None     Data type of the parameters
   def forward(self, token_ids: torch.Tensor) -> torch.Tensor Lookup the embedding vectors
       for the given token IDs.
   Make sure to:
   • subclass nn.Module
   • call the superclass constructor
   • initialize your embedding matrix as an nn.Parameter
   • store the embedding matrix with the d_model being the final dimension
   • of course, don’t use nn.Embedding or nn.functional.embedding
   Again, use the settings from above for initialization, and use torch.nn.init.trunc_normal_ to
   initialize the weights.
   To test your implementation, implement the test adapter at [adapters.run_embedding] . Then, run
   uv run pytest -k test_embedding.

关于这一章的疑问、理解与心得,都可以在这里交流。阅读无需登录;发表评论或回复时使用 GitHub 账号。

正在加载本章讨论…

欢迎交流概念与阅读疑问,请勿发布作业完整实现或题目答案。

输入中文、英文术语或题号,例如 RoPE、检查点、train_bpe。