微調配方參數審計與訓練超參數基準校準
Agent 輔助工程檢查
前置要求
第 64-66 天 LoRA 數學工程基礎與第 49-51 天預訓練訓練循環。
學習目標
系統審計微調學習率調度(帶線性預熱的餘弦衰減,峰值 2e-4)、秩 r=16、alpha=32、批大小及目標投影層,嚴格與主流開源標準配方對齊。
操作指引
學習來源:在本活動現有的閱讀與練習時段內,參考 Hugging Face LLM Course: Fine-tuning LLMs 的 Chapter 11.3: Training Configuration,用自己的話解釋一處與本地任務的聯繫。保留現有練習與驗收檢查;若外部資料無法存取,使用課程自寫的解釋。1. 查閱公開的配方(Alpaca、LoRA 論文、PEFT),寫下各自使用的值:
- 學習率:LoRA 取 1e-4 至 3e-4,約為常見全量微調學習率(1e-5 至 2e-5)的 10 倍,因為只更新很小的適配器。
- 秩與縮放:r=16,alpha=32,因此適配器輸出乘以 alpha/r = 2.0。
- 目標模組:注意力的全部投影(q_proj、k_proj、v_proj、o_proj),或全部線性層。
- 排程:在 3% 至 5% 的步數內線性預熱,然後餘弦衰減到峰值的 10%。
2. 用這些值加上 max_steps=1000、seq_len=1024 和 min_lr_ratio=0.1 寫出 config.json。
3. 實作 lr_at(step),並手算檢查三個點:預熱結束時(30 個預熱步中的第 29 步)為 2e-4,最後一步為 2e-5,預熱期間學習率上升。
4. 檢查序列格式:每個樣本對被打包到固定長度(512 或 1024 個詞元),並以 EOS 詞元結尾。
5. 用一個範例檢查損失遮罩:提示詞元的標籤為 -100,只有回答詞元和 EOS 計入損失。
時間安排(120 分鐘):閱讀 30 + 練習 60 + 檢查 30。 閱讀:Alpaca 的訓練配方,以及 Hu et al.(LoRA)第 7 節關於適配哪些權重矩陣、選用多大秩的討論。練習:第 2-5 步。檢查:重新計算 alpha/r 和預熱步數,並憑記憶解釋 LoRA 學習率為何高 10 倍。
自主實作與記錄
構造微調配置字典 config.json。斷言其顯式包含 rank=16, alpha=32, lr=2e-4, warmup_ratio=0.03 以及 loss_masking=True 且數值合規。
核對字典鍵值與 Hugging Face PEFT 規範一致。
import math
config = {
'r': 16,
'lora_alpha': 32,
'target_modules': ['q_proj', 'k_proj', 'v_proj', 'o_proj'],
'lr': 2e-4,
'warmup_ratio': 0.03,
'min_lr_ratio': 0.1, # cosine decays to 10% of the peak
'max_steps': 1000,
'seq_len': 1024,
'loss_masking': True # prompt tokens get label -100 and add nothing to the loss
}
assert config['r'] == 16 and config['lora_alpha'] == 32
assert config['lr'] == 2e-4 and config['warmup_ratio'] == 0.03
assert config['loss_masking'] is True
assert config['lora_alpha'] / config['r'] == 2.0 # the adapter output is scaled by 2
def lr_at(step, c=config):
warmup = round(c['warmup_ratio'] * c['max_steps']) # 30 steps
if step < warmup:
return c['lr'] * (step + 1) / warmup
progress = (step - warmup) / (c['max_steps'] - warmup)
floor = c['min_lr_ratio'] * c['lr']
return floor + 0.5 * (c['lr'] - floor) * (1 + math.cos(math.pi * progress))
assert abs(lr_at(29) - 2e-4) < 1e-12 # warmup ends at the peak
assert abs(lr_at(1000) - 2e-5) < 1e-12 # cosine ends at 10% of the peak
assert lr_at(0) < lr_at(10) < lr_at(29)
# Loss masking, worked on one example: 5 prompt tokens and 3 answer tokens plus EOS.
input_ids = [101, 7, 8, 9, 102, 55, 56, 57, 2]
labels = [-100] * 5 + input_ids[5:]
assert sum(l != -100 for l in labels) == 4 and labels[-1] == 2 # only the answer and EOS train
# Peak lr 2e-4 is about 10x a typical full fine-tuning lr (1e-5 to 2e-5) because only the adapter moves.
獨立構建符合行業最高標準且張量約束明確的 LoRA 微調超參數配方。
權威來源資源與權利證明
Hugging Face LLM Course: Fine-tuning LLMs
對應章節 / 時間戳: Chapter 11.3: Training Configuration
驗證版本與日期: Public edition checked 2026-11-01; moving pages may change
Sequenced templates, supervised fine-tuning and evaluation teaching with exercises/quizzes. LoRA method and memory claims are checked against the original paper, PEFT and the local parameter ledger, not accepted wholesale from Chapter 11.4.
Python, PyTorch, language-model training and the preceding chat-format lessons.
Use the original localized explanations, exercises and checks already present in this activity; no external account or purchase is required for that fallback.
對比候選資源與選型分析 (2)
Retained for initialization and the low-rank method, not a beginner teaching sequence.
Retained for actual API and implementation defaults; reference documentation is not a complete teaching course.
Stanford Alpaca: An Instruction-following LLaMA Model
對應章節 / 時間戳: Training recipe
驗證版本與日期: Stanford CRFM Release (Verified: 2026-10-30)
Original open recipe demonstrating lightweight instruction fine-tuning of open models, establishing prompt/response templates, batch scheduling, and learning rate ranges.
Supervised fine-tuning, instruction formatting, and LoRA fundamentals.
Complete instruction templates, JSONL formatting scripts, and learning rate schedules are self-contained in curriculum materials.
對比候選資源與選型分析 (2)
Multi-turn ShareGPT tuning recipe; Alpaca provides simpler, single-turn clarity ideal for foundational instruction tuning study.
Commercially permissive crowdsourced dataset; Alpaca established the academic instruction tuning standard.
LoRA: Low-Rank Adaptation of Large Language Models
對應章節 / 時間戳: Appendix D Hyperparameters Used in Experiments
驗證版本與日期: ICLR 2022 / arXiv:2106.09685v2 (Verified: 2026-10-30)
Primary literature introducing Low-Rank Adaptation, establishing parameter decomposition W = W0 + (alpha/r)*BA, initialization strategies, and zero inference latency merging.
Matrix factorization, rank, linear layers, and transformer attention.
Complete matrix derivations, tensor dimensions, and pure PyTorch LoRALinear modules are implemented directly in lesson code.
對比候選資源與選型分析 (2)
Introduces bottleneck adapter layers in series, which introduces unavoidable inference latency overhead; LoRA's parallel formulation merges with zero latency.
Prepends virtual prompt tokens; reduces available context length, unlike LoRA which preserves full sequence capacity.