最终规范化与权重绑定输出头(\mathbf{E}^\top):将规范化后的残差流向量投影为词表对数几率 \mathbf{Z} = \mathrm{Norm}(\mathbf{H}^{(L)})\mathbf{E}^\top \in \mathbb{R}^{B \times T \times V},复用 \mathbf{E} 可节省 V d 个参数(在 GPT-2 Small 中为 38.6\text{M})。
带 RoPE 与 GQA 的融合因果自注意力
因果注意力
融合 QKV 投影:将 \mathbf{X} 乘以单个矩阵 \mathbf{W}_{qkv} \in \mathbb{R}^{d \times (d + 2 H_{\text{kv}} d_h)},再拆分为 H 个查询头与 H_{\text{kv}} \le H 个键值头。
RoPE + 因果掩码(is_causal=True):按位置角度旋转查询与键,并将 s > t 掩蔽为 -\infty,使得 \partial \mathbf{z}_t / \partial \mathbf{x}_s = \mathbf{0}。
def init_weights(self):"""GPT-2's initialization of the linear layers: N(0, 0.02^2) weights and zero biases; W_o and W_2, which write to the stream, get std 0.02 / sqrt(2L).""" L =len(self.blks)for name, m inself.named_modules():ifisinstance(m, nn.Linear): std =0.02/ (2* L) **0.5if name.endswith( ('W_o', 'W_2')) else0.02 nn.init.normal_(m.weight, std=std)if m.bias isnotNone: nn.init.zeros_(m.bias)
自回归交叉熵目标
训练目标
给定输入窗口 \mathbf{x} = (x_1, \dots, x_T) 和移位目标 \mathbf{y} = (x_2, \dots, x_{T+1}),训练最小化全部 B \times T 个位置上的平均负对数似然:
X[0]: 'the European lobster ) a'
Y[0]: 'he European lobster ) an'
[[1 0 0 0 0]
[1 1 0 0 0]
[1 1 1 0 0]
[1 1 1 1 0]
[1 1 1 1 1]]
在 WikiText-103 上进行字节级语言建模
语料与初始化检验
我们在 WikiText-103 的 270\text{M} 原始 UTF-8 字节上训练一个 6 块字节级 GPT(V = 256, d = 256, H = 8, L = 6, T = 128,4.79\text{M} 参数):
data = d2l.WikiText103(batch_size=64, num_steps=128)print(f'{len(data.train) /1e6:.0f}M training bytes, 'f'{len(data.val) /1e6:.2f}M validation bytes, 'f'vocabulary of {len(data.vocab)}')
270M training bytes, 1.14M validation bytes, vocabulary of 256
model = gpt(len(data.vocab), max_len=128)loss = math.log(d2l.lm_perplexity(model, [next(data.val_dataloader())]))print(f'{d2l.num_params(model) /1e6:.2f}M parameters; loss before 'f'training {loss:.2f} nats per byte, log 256 = {math.log(256):.2f}')
4.79M parameters; loss before training 5.66 nats per byte, log 256 = 5.55
T=1.0, top_k=None: 'The history of the 2010 lead in Cecil . The shiwn trees
about his improvement appearances helped attack actual film songs , were
aportimely'
T=0.7, top_k=8: 'The history of the story to the ship wife . \n = = =
Control = = = \n The contrast of the final part of the time , and
interviewers , and the'
T=2.0, top_k=None: 'The history of the
lar��\u038d\u038d���Е�;v���ױ����岙��Ӄ�\x1c,ϐ \n
Trenreodoviti��Ě�\x08q���nve VS ÷tu KopaxodSq ;
�t3nĀohjnetoKcckakizonþon U�6'
加载预训练 OpenAI GPT-2 Small(124M)
检查点加载
将 GPT-2 的 2019 年配置(norm='layer'、act='gelu'、pos='learned'、bias=True)传入 d2l.GPT,即可精确实例化 GPT-2 Small 架构:
text = ("The Time Machine, by H. G. Wells. The Time Traveller was ""expounding a recondite matter to us.")x = torch.tensor(enc.encode(text), device=d2l.try_gpu())[None]with torch.inference_mode(): logits = gpt2(x)loss = F.cross_entropy(logits[0, :-1], x[0, 1:])print(f'per-token loss {loss.item():.2f}, 'f'perplexity {loss.exp().item():.0f}')
per-token loss 3.89, perplexity 49
GPT-2 Small 的贪婪与采样续写
检查点验证
Alan Turing theorized that computers would one day become the most powerful
machines on the planet.
The computer is a computer that
The secret of a good deep learning textbook is that it can be read by
anyone. The easiest way to learn a deep learning language is to read the
book, or the software. It's also the easiest way to learn a framework.