预训练核心步进:前向、损失、反向传播与梯度裁剪
Agent 辅助工程分析
先修要求
第 49 日数据加载器与第 50 日 AdamW 优化器。
学习目标
执行经典的 5 步训练迭代,理解 set_to_none=True 的显存释放机制,施加全局 L2 范数梯度裁剪。
实验指南
学习来源:在本活动现有的阅读与练习时段内,参考 CS336 Assignment 1: Basics (Spring 2025 tagged release) 的 tests/adapters.py: run_gradient_clipping; tests/test_nn_utils.py: test_gradient_clipping,用自己的话解释一处与本地任务的联系。保留现有练习与验收检查;若外部资料无法访问,使用课程自写的解释。在每个预训练步进中:(1) optimizer.zero_grad(set_to_none=True) 释放梯度张量;(2) logits, loss = model(x, y) 计算前向传播与交叉熵损失;(3) loss.backward() 累加梯度;(4) torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0) 将全局梯度 L2 模长约束至不超过 1.0;(5) optimizer.step() 更新参数。分析梯度裁剪防止权重暴走的关键机理。
实战与预测记录
1. 给出执行一次完整训练迭代的 Python 代码。
2. 若未裁剪的全局梯度模长 ||g||_2 = 5.0 且 max_norm = 1.0,各个参数的梯度会被乘以何种缩放比例?
3. 为何 optimizer.zero_grad(set_to_none=True) 在工程性能上显著优于默认的 zero_grad()?
缩放系数为 min(1.0, max_norm / ||g||_2)。置空引用释放显存与写入 0 的访存开销差异。
1. 训练步进代码:
optimizer.zero_grad(set_to_none=True)
logits, loss = model(x, y)
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
optimizer.step()2. 缩放系数:1.0 / 5.0 = 0.2。所有参数的梯度均被乘以 0.2,将全局 L2 范数硬性限制在 1.0 以内。
3.
set_to_none=True 直接释放了梯度张量的显存指针,无需在已有缓冲区中逐个填充零,节省了显存读写带宽,并加速随后的 autograd 内存分配。
学习者能够编写规范的 5 步训练逻辑,准确计算梯度裁剪系数,并阐明 set_to_none=True 的显存优势。
权威来源与学术版权说明
CS336 Assignment 1: Basics (Spring 2025 tagged release)
对应章节/时间戳: tests/adapters.py: run_gradient_clipping; tests/test_nn_utils.py: test_gradient_clipping
核验版本与日期: spring2025 tag; README, tests and MIT LICENSE checked 2026-11-01
Lead assignment-driven source for pretraining component practice and tests. nanoGPT remains a compact historical code-reading companion, not the current recommended training curriculum.
Fluent Python, PyTorch, and linear algebra
Local self-contained pretraining scripts run on standard local CPUs or budget GPUs without Stanford cluster dependency.
候选来源对比与遴选分析 (2)
Simpler code layout, useful complementary reference for minimal PyTorch Transformer.
High-level API focus rather than building from raw tensor fundamentals.
nanoGPT: train.py pretraining loop
对应章节/时间戳: train.py: training loop (while True): forward under ctx, scaler.scale(loss).backward(), clip_grad_norm_(grad_clip), scaler.step(optimizer)
核验版本与日期: Git master commit 71c3905 (Verified: 2026-10-30)
Compact historical code reference for the named implementation functions; CS336 spring2025 provides the lead component exercises. Do not infer top-p, atomic persistence or cloud budget enforcement from nanoGPT.
Python, PyTorch, and Day 46-48 Transformer model architecture.
Runnable pretraining scripts and step-by-step tensor mechanics are fully self-contained in the curriculum lessons.
候选来源对比与遴选分析 (2)
Heavy abstraction layer wrapping distributed training; nanoGPT exposes raw PyTorch loops without framework overhead.
High-performance enterprise distributed framework; unsuitable for local educational first-principles comprehension.