預訓練核心步進:前向、損失、反向傳播與梯度裁剪
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.