大模型原理与训练 / 系统课时
实现词元嵌入与位置表示
实现词元嵌入与位置表示
这一节把形状为 [B, T] 的 token id 变成 Transformer 可处理的 [B, T, C] 连续向量,同时加入可学习的位置表示。完成后会直接验证三类张量形状,并让超过最大上下文长度的输入明确报错。
学习目标
- 实现 token embedding 与可学习绝对位置 embedding 的相加
- 理解
[B, T]、[T, C]与[B, T, C]之间的形状关系 - 用边界检查验证最大上下文长度的含义
两种嵌入承担不同信息
词元嵌入回答“当前位置是什么 token”,位置嵌入回答“这个 token 出现在序列第几个位置”。设批量大小为 B、序列长度为 T、隐藏维度为 C,token id 输入形状是 [B, T],查 token 表后得到 [B, T, C];位置索引 0..T-1 查位置表后得到 [T, C]。
两者在相同隐藏维度上相加:
这一步不会改变批量和序列长度,只把离散 id 变成每个位置一个 C 维向量。即使两个位置出现同一个 token,它们也会因为位置向量不同而得到不同的最终表示。

实现并验证张量形状
下面实现一个最小输入嵌入模块。位置表示采用 GPT 常见的可学习绝对位置表;模块先检查输入是否是二维,再检查序列长度是否超过位置表能表示的最大上下文。
import torch
from torch import nn
class InputEmbedding(nn.Module):
def __init__(self, vocab_size: int, d_model: int, max_context: int):
super().__init__()
self.max_context = max_context
self.token_embedding = nn.Embedding(vocab_size, d_model)
self.position_embedding = nn.Embedding(max_context, d_model)
def forward(self, idx: torch.Tensor) -> torch.Tensor:
if idx.ndim != 2:
raise ValueError("idx must have shape [B, T]")
_, t = idx.shape
if t > self.max_context:
raise ValueError(
f"sequence length {t} exceeds max_context {self.max_context}"
)
# 词元向量按 token id 查表,位置向量按 0..T-1 查表。
positions = torch.arange(t, device=idx.device)
token_vectors = self.token_embedding(idx)
position_vectors = self.position_embedding(positions)
# [T, C] 扩成 [1, T, C],再与每个 batch 的词元向量相加。
return token_vectors + position_vectors.unsqueeze(0)
torch.manual_seed(0)
layer = InputEmbedding(vocab_size=16, d_model=8, max_context=6)
idx = torch.tensor(
[[1, 2, 3, 4], [4, 3, 2, 1]],
dtype=torch.long,
)
out = layer(idx)
print("input:", tuple(idx.shape))
print("token_embedding_weight:", tuple(layer.token_embedding.weight.shape))
print("position_embedding_weight:", tuple(layer.position_embedding.weight.shape))
print("output:", tuple(out.shape))
try:
layer(torch.zeros((1, 7), dtype=torch.long))
except ValueError as exc:
print("error:", exc)预期输出:
input: (2, 4)
token_embedding_weight: (16, 8)
position_embedding_weight: (6, 8)
output: (2, 4, 8)
error: sequence length 7 exceeds max_context 6输出验证了两件事:vocab_size=16 只决定 token 表有多少行,max_context=6 只决定位置表有多少行;两张表的列数都必须等于隐藏维度 d_model=8,才能逐元素相加。
最大上下文长度是位置表边界
当 T=4 时,只会访问位置 0..3;当 T=7 而 max_context=6 时,需要访问不存在的位置 6,因此示例主动抛出异常。自回归生成时,最简单的处理是只把最近 max_context 个 token 喂回模型,而不是让输入无限增长。
另一个常见错误是 token id 越界。nn.Embedding(vocab_size, d_model) 只接受 0 到 vocab_size - 1 的整数索引,因此这里的 vocab_size 必须和上一阶段保存的词表完全一致,输入 dtype 也应保持为 torch.long。
接到 Transformer 时保持什么不变
嵌入相加后的 [B, T, C] 会直接进入注意力层和前馈网络,Transformer 主体通常一直保留这三个轴的语义:批量、序列位置、隐藏特征。后续增加多头注意力时,只需再保证 C 能按头数合理拆分;输入嵌入模块本身无需知道每个注意力头如何工作。