Chương 21 — Học Tăng cường (RL), Tinh chỉnh PEFT (LoRA/QLoRA/DoRA) & Hậu huấn luyện Suy luận (DPO, CAI, GRPO + RLVR)
Từ 70B Full FT (1,123.6 GB) -> QLoRA NF4+DQ (43.3 GB, 25.9x, +1.34 dB SNR) & Prompt-Masked DoRA (100% acc, 0.00 merge diff) đến Tiny LLM 4 Giai đoạn thật: Pre-Train (PPL 31.11->2.69) -> SFT -> DPO+CAI (+9.40 margin, 100%) -> Critic-Free GRPO+RLVR (+31.2pp, k3 KL=0.11).
Đơn vị học phần (
Unit ID):T1-P4-U04(Phần 4: Xử lý Ngôn ngữ Tự nhiên, Mô hình Ngôn ngữ Lớn, Hậu huấn luyện Suy luận & An toàn AI — Mục lục Phần 4)
Phòng thí nghiệm Thực hành (Lab 12): Lab 12 — Tự xây dựng LLM Từ Con Số 0: Pre-Train, SFT, DPO/CAI & GRPO+RLVR (llm_from_scratch_lab)
Truy xuất nguồn & kế thừa: Kế thừa trực tiếp từ Chương 19 (RMSNorm,RoPE,SwiGLU,GQA/MLA) vàChương 20(Tiền huấn luyện, Quy luật Scaling &DSPy); hiện đại hóa trọn vẹn Chương trình gốc DSAI (R51— Introduction to RL & Deep RL;R52— Advanced LLM: Fine-Tuning, RLHF & DPO, Constitutional AI; Lab LLM from scratch). Chương kế tiếp làChương 22(An toàn AI, Hack Phần thưởng & Siêu Căn chỉnh).
Bốn Thất bại Hậu huấn luyện Thực chiến Mở màn: Vì sao Tiền huấn luyện Chưa Tạo ra Trợ lý AI Suy luận?#
Một mô hình ngôn ngữ vừa kết thúc tiền huấn luyện (Base LLM) chỉ là một bộ dự đoán token kế tiếp theo phân phối Internet: nó có tri thức số học và cú pháp, nhưng lại trả lời dài dòng, không tuân định dạng và không biết kiểm chứng bước suy luận. Trong thực tế triển khai 2024–2026, các đội kỹ sư thường va phải bốn bức tường thất bại định lượng sau — cả bốn đều được tái hiện trực tiếp trong Lab 12 (llm_from_scratch_lab, seed = 42):
-
Bức tường VRAM
1,123.6 GBcủa Full Fine-Tuning70B(Lab 12,Tests 04, 05, 06):Với bộ tối ưu
AdamWđộ chính xác hỗn hợp (bf16trọng số +bf16gradient +fp32master weights + hai mô-menfp32\(m, v\) =16 bytes/tham số), tinh chỉnh toàn phần mô hình70Bđòi hỏi1,120.0 GBbộ nhớ trạng thái tĩnh (1,123.6 GBgồm kích hoạtgrad_checkpointing, cần tới cụm16× H100 80GB). Thay vào đó,LoRA(bf16, r = 16) chỉ huấn luyện0.32%tham số, cắt VRAM xuống147.2 GB,DoRAcộng thêm đúng+0.15 GB(147.4 GB,0.34%tham số) để tách riêng biên độ–hướng và thu hẹp khoảng cách chất lượng so với Full FT, cònQLoRA(NF44-bit + Lượng tử hóa képDQ) ép trọng số nền xuống4.127 bit/tham số(đạt20.69 dBSNR, hơnINT4đồng đều+1.34 dB), cắt tổng VRAM xuống chỉ43.3 GB(giảm25.9×, chạy trọn vẹn trên một GPU80 GBduy nhất!). -
Bỏ quên Che Prompt (
Unmasked SFT) Làm Lãng phí Dung lượng Adapter (Lab 12,Test 09):Khi tinh chỉnh có giám sát (
SFT) trên cặp(prompt, response)có phần đầu đề ngữ cảnh biến thiên, việc tính Cross-Entropy lên toàn bộ chuỗi khiến adapter hạng thấp (rank = 6) lãng phí quá nửa bước cập nhật vào các token đề bài ngẫu nhiên: trongLab 12,Unmasked LoRA SFTdừng ở Eval Response NLL0.117và độ chính xác held-out chỉ75.0%. Áp dụng Che Prompt chuẩn (ignore_index = -100trên mọi token prompt) cắt Response NLL xuống0.034(giảm3.5×) và nâng độ chính xác lên96.9%(+21.9pp), cònPrompt-Masked DoRAđạt NLL0.027và100.0%chính xác với sai số gộp trọng số suy luận0.00e+00! -
Gánh nặng 4 Mô hình của
RLHF-PPO& Hiện tượng Trôi Xác suất trongDPO(Lab 12,Tests 10, 11):RLHF-PPOtiêu chuẩn phải giữ đồng thời 4 mô hình trên VRAM (Actor,Critic/Value,Reference,Reward Model=36 bytes/param, tức252 GBtĩnh cho mô hình7Bvà2,520 GBcho70B).DPOdạng đóng loại bỏ cảCriticlẫnReward Model, cắt đúng50.0%VRAM xuống126 GB(7B), nhưng nếu bỏ giám sát \(\log \pi_\theta(y_w \mid x)\) có thể rơi vào Likelihood Displacement (kéo giảm xác suất của cả câu trả lời đúng lẫn sai). Khi kết hợp bộ sinh cặp phê bình–chỉnh sửaConstitutional AI(C1-SAFE,C2-CONCISE) cùng neo NLL nhỏ (0.05) trongLab 12,DPOnâng độ chính xác ưu tiên từ50.0%lên100.0%với biên thưởng ngầm+9.40, giữ nguyênchosen_mean_logp(-0.0338 -> -0.0377) và chặn chặt phân kỳ Schulmank3KL ở mức0.0003. -
Hack Phần thưởng của Reward Model Nơ-ron & Đột phá
GRPO + RLVRKhông Cần Critic (Lab 12,Tests 12, 13, 14):Trong toán học, lập trình và logic hình thức, Reward Model nơ-ron dễ bị khai thác theo định luật Goodhart (câu trả lời dài dòng nhưng sai số vẫn nhận điểm cao). Hậu huấn luyện SOTA 2025–2026 kiểu DeepSeek-R1 thay Reward Model bằng bộ kiểm chứng tất định (
RLVR) và thay mạngCriticđắt đỏ bằng chuẩn hóa lợi thế nội bộ nhómGRPO(\(G = 8\) mẫu/prompt, tiết kiệm50%VRAM so vớiPPO!) kết hợp ước lượng Schulmank3KL không âm. TrongLab 12, xuất phát từ Cold-Start SFT ở mức40.6%held-out (64.8%train),GRPO + RLVRchỉ dùng tín hiệu thưởng vô hướng \(r_i \in [0, 1]\) từ bộ kiểm chứng chương trình đã đẩy độ chính xác kiểm chứng held-out vọt lên71.9%(+31.2pp; tập huấn luyện93.2%) mà giữ chặtk3 KL = 0.1104.
Mục tiêu Học tập (Learning Objectives)#
Sau khi hoàn thành Chương 21 và vượt qua 16/16 bài kiểm thử của Lab 12 (llm_from_scratch_lab), học viên làm chủ toàn diện 5 năng lực cốt lõi:
- Nền tảng Học Tăng cường (
RL) đến Token-Level MDP cho LLM: Phát biểu chính xácMDP, phương trình Bellman, Định lý Policy Gradient, chứng minh khử phương sai không chệch củaREINFORCE + Baseline, dẫn xuấtGAE(λ)và mục tiêu kẹp bi quanPPO\(L^{\text{CLIP}}\). - Kế toán Bộ nhớ & Triển khai SOTA
PEFT(LoRA,QLoRA NF4,DoRA): Chứng minh bức tường16 bytes/paramcủa Full FT, tự tay cài đặtLoRALinear,DoRALinear(khớp gộp trọng số< 1e-5), bộ lượng tử hóaNF44-bit theo khối (+1.34 dBSNR so vớiINT4đồng đều) và lập ngân sách VRAM cho mô hình7B/70B. - Dẫn xuất Toán học
RLHF\(\to\)DPO,SimPO/ORPO&Constitutional AI: Chứng minh nghiệm dạng đóng triệt tiêu hàm phân hoạch \(Z(x)\) trongDPO, phân tích bệnh lý Likelihood Displacement, so sánhDPOvsSimPO/ORPOvà cài đặt quy trình phê bình–chỉnh sửaConstitutional AI(SL-CAI+RLAIF). - Làm chủ Hậu huấn luyện Suy luận 2026 (
GRPO + RLVR& Schulmank3KL): Chứng minh tính không âm tuyệt đối và không chệch của bộ ước lượng Schulmank3KL, thiết kế bộ kiểm chứng tất địnhRLVR, xử lý bài toán nhóm đồng nhất (\(\sigma_G = 0\)) và kiểm soát ngân sách KL. - Tự tay Vận hành Trọn vẹn Vòng đời 4 Chặng LLM Từ Con Số 0 (
Lab 12): Triển khaiTinyModernDecoderLM(RMSNorm+RoPE+SwiGLU) từ khởi tạo ngẫu nhiên qua Pre-Train \(\to\) Prompt-Masked SFT (LoRA/DoRA) \(\to\)DPO+CAI\(\to\)GRPO + RLVRvà lưu trữ an toàn bằngsafetensors(0.0sai số, cấmpickle).
Truy xuất Nguồn (R51 + R52 + Lab LLM from Scratch) & Bảng Ký hiệu#
Thành phần Giáo trình Gốc (R51, R52, E50:E53) |
Nâng cấp Chuẩn SOTA 2026 (ch-21) |
Vị trí trong Chương | Sơ đồ / Widget | Mô-đun & Kiểm thử (llm_from_scratch_lab) |
|---|---|---|---|---|
1. Introduction to RL & Deep RL (R51) |
MDP \(\to\) Token-Level LLM MDP, Bellman, Policy Gradient, REINFORCE Baseline, GAE(λ), PPO Clipped Surrogate |
Trụ cột 1 (§1.1) | Mermaid 2 + Widget 2 |
rl_and_peft.py: compute_gae_advantages, ppo_clipped_surrogate_loss, run_ppo_policy_benchmark (Test 02) |
2. LLM Fine-Tuning & Evaluation (R52) |
Bức tường VRAM 16 B/param, LoRA (merge 0 ms), QLoRA (NF4 + Double Quant), DoRA (biên độ–hướng), Prompt-Masked SFT |
Trụ cột 1 (§1.2) + Trụ cột 2 (§2.1) | Mermaid 1 + Widget 1 |
rl_and_peft.py & tiny_llm_lifecycle.py: LoRALinear, DoRALinear, nf4_quantize_blockwise, sft_with_peft (Tests 04, 05, 06, 09) |
3. RLHF & DPO (R52) |
Bradley–Terry Reward Model, KL-Regularized PPO, dẫn xuất đóng DPO triệt tiêu \(Z(x)\), Likelihood Displacement, SimPO / ORPO |
Trụ cột 1 (§1.3) + Trụ cột 2 (§2.2) | Mermaid 2 + Widget 2 |
tiny_llm_lifecycle.py: compute_dpo_loss, align_with_dpo (Test 11) |
4. Constitutional AI (R52) |
Quy trình 2 pha SL-CAI (Critique \(\to\) Revise) & RLAIF sinh cặp ưu tiên an toàn chi phí thấp |
Trụ cột 1 (§1.3) + Trụ cột 2 (§2.4) | Mermaid 1 |
tiny_llm_lifecycle.py: ConstitutionalPrinciple, generate_constitutional_pairs (Test 10) |
| 5. SOTA 2026 Reasoning Post-Training | DeepSeek-R1 GRPO (Critic-free, tiết kiệm 50% VRAM), chứng minh Schulman k3 KL (\(\ge 0\), không chệch) & RLVR tất định |
Trụ cột 1 (§1.4) + Trụ cột 2 (§2.3) | Mermaid 3 + Widget 3 |
rl_and_peft.py & tiny_llm_lifecycle.py: schulman_k3_kl, compute_group_relative_advantages, verify_arithmetic_completion, posttrain_with_grpo_rlvr (Tests 03, 12–14) |
6. Lab: LLM from Scratch (E50:E53) |
TinyModernDecoderLM (42K params: RMSNorm/RoPE/SwiGLU) chạy đủ 4 chặng Pre-Train \(\to\) SFT \(\to\) DPO \(\to\) GRPO + safetensors |
Trụ cột 3 & 4 | Mermaid 1 |
tiny_llm_lifecycle.py & scripts/run_lab_demo.py (Tests 07, 08, 15, 16) |
Bảng Ký hiệu Toán học Chuẩn hóa (ch-21)#
| Ký hiệu | Miền / Hình dạng | Ý nghĩa Chuẩn trong Chương 21 | Định danh llm_from_scratch_lab |
|---|---|---|---|
| \((\mathcal{S}, \mathcal{A}, P, R, \gamma)\) | Bộ năm MDP | Trạng thái \(s_t = (x, y_{<t})\), hành động \(a_t = y_t\), chiết khấu \(\gamma \in [0, 1]\) | gamma, rewards, values, dones |
| \(\delta_t, \hat{A}_t^{\text{GAE}}, \lambda\) | \(\mathbb{R}, [0, 1]\) | Sai số TD 1 bước, ước lượng lợi thế GAE, tham số mượt bias–variance |
compute_gae_advantages, lam |
| \(\rho_t(\theta), \epsilon, \beta\) | \(\mathbb{R}_{>0}\) | Tỷ số xác suất quan trọng \(\pi_\theta/\pi_{\text{old}}\), biên kẹp PPO, hệ số phạt KL |
clip_eps, kl_beta, beta |
| \(\mathbf{W}_0, \mathbf{A}, \mathbf{B}, r, \alpha, \mathbf{m}\) | Ma trận, \(\mathbb{N}, \mathbb{R}^{d_{\text{out}}}\) | Trọng số đóng băng, nhân tử LoRA hạng \(r\), tỷ lệ \(\alpha/r\), biên độ DoRA |
LoRALinear, DoRALinear, magnitude |
| \((x, y_w, y_l), \hat{r}_\theta, \Delta\hat{r}\) | Chuỗi, \(\mathbb{R}\) | Prompt, phản hồi thắng/thua, thưởng ngầm DPO và biên ưu tiên |
compute_dpo_loss, mean_reward_margin |
| \(G, \{o_i\}_{i=1}^G, \mu_G, \sigma_G, \hat{A}_i\) | \(\mathbb{N}_{\ge 2}, \mathbb{R}\) | Cỡ nhóm GRPO, tập rollout, trung bình/độ lệch chuẩn nhóm, lợi thế nhóm |
group_size, compute_group_relative_advantages |
| \(u, D_{\text{KL}}^{(k3)}(\pi_\theta \| \pi_{\text{ref}})\) | \(\mathbb{R}_{>0}, \mathbb{R}_{\ge 0}\) | Tỷ số nghịch đảo \(\pi_{\text{ref}}/\pi_\theta\), ước lượng KL Schulman k3 \(= u - \log u - 1\) |
schulman_k3_kl, final_kl_k3 |
Trụ cột 1 — Nền tảng Lý thuyết & Chứng minh Toán học từ First Principles#
1.1 Từ MDP & REINFORCE đến GAE(λ) và PPO trong Token-Level LLM#
Một Quy trình Quyết định Markov (MDP) gồm \((\mathcal{S}, \mathcal{A}, P, R, \gamma)\). Khi áp dụng cho bài toán sinh văn bản tự hồi quy của LLM (Token-Level MDP), trạng thái tại bước \(t\) là tiền tố \(s_t = (x, y_{<t})\), hành động là lựa chọn token \(a_t = y_t \in \mathcal{V}\) theo chính sách \(\pi_\theta(y_t \mid x, y_{<t})\), chuyển trạng thái tất định \(s_{t+1} = (x, y_{\le t})\), và phần thưởng thưa \(r(x, y)\) thường chỉ xuất hiện ở token kết thúc <EOS>.
Hàm giá trị trạng thái \(V^\pi(s)\) và giá trị hành động \(Q^\pi(s, a)\) thỏa mãn phương trình kỳ vọng Bellman:
Định lý Đạo hàm Chính sách & Chứng minh Đường cơ sở Không chệch (REINFORCE + Baseline)#
Với mục tiêu \(J(\theta) = \mathbb{E}_{\tau \sim \pi_\theta}[R(\tau)]\), áp dụng thủ thuật log-đạo hàm \(\nabla_\theta \pi_\theta(\tau) = \pi_\theta(\tau)\nabla_\theta \log \pi_\theta(\tau)\) ta thu được:
Bất kỳ đường cơ sở \(b(s_t)\) nào chỉ phụ thuộc trạng thái \(s_t\) đều không làm chệch kỳ vọng gradient vì:
Chọn \(b(s_t) = V^\pi(s_t)\) dẫn thẳng đến họ thuật toán Actor-Critic, giảm mạnh phương sai ước lượng đạo hàm.
Ước lượng Lợi thế Tổng quát GAE(λ) & Mục tiêu Kẹp PPO#
Đặt sai số hiệu sai thời gian 1 bước \(\delta_t = r_t + \gamma V(s_{t+1})(1 - d_t) - V(s_t)\) (với \(d_t \in \{0, 1\}\) đánh dấu trạng thái kết thúc). GAE(γ, λ) (Schulman et al., 2016) tổ hợp lũy thừa các sai số TD để đánh đổi mượt giữa độ chệch và phương sai:
Hai trường hợp biên được kiểm chứng chính xác tới 1e-12 trong Lab 12 (Test 02): \(\lambda = 0\) quy về TD(0) (\(\hat{A}_t = \delta_t\), phương sai thấp nhất), còn \(\lambda = 1\) quy về Monte Carlo (\(\hat{A}_t = G_t - V(s_t)\), không chệch hoàn toàn).
Để ngăn các bước cập nhật quá lớn làm sụp đổ chính sách, PPO (Proximal Policy Optimization) dùng tỷ số xác suất \(\rho_t(\theta) = \frac{\pi_\theta(a_t \mid s_t)}{\pi_{\text{old}}(a_t \mid s_t)}\) trong mục tiêu kẹp bi quan (pessimistic clipped surrogate):
- Khi \(\hat{A}_t > 0\): nếu \(\rho_t(\theta) > 1 + \epsilon\), phép \(\min\) giữ mức trần \((1 + \epsilon)\hat{A}_t \implies\) gradient triệt tiêu, cấm bước nhảy lạc quan thái quá.
- Khi \(\hat{A}_t < 0\): nếu \(\rho_t(\theta) < 1 - \epsilon\), phép \(\min\) giữ mức sàn \((1 - \epsilon)\hat{A}_t \implies\) cấm triệt tiêu xác suất hành động quá đột ngột.
Trong Lab 12 (run_ppo_policy_benchmark, Test 02), PPO + GAE kết hợp phạt Schulman k3 KL nâng lợi nhuận kỳ vọng từ 1.31 lên 5.65 (sát mốc tối ưu lý thuyết 6.00, độ tăng +4.34).
1.2 Tinh chỉnh Tham số Hiệu quả (PEFT): Bức tường 16 B/param, LoRA, QLoRA NF4 & DoRA#
Bức tường VRAM của Full Fine-Tuning#
Huấn luyện toàn bộ \(\Psi\) tham số bằng AdamW độ chính xác hỗn hợp đòi hỏi lưu song song:
- Trọng số
bf16(\(2\Psi\) bytes) + Gradientbf16(\(2\Psi\) bytes), - Bản sao master weights
fp32(\(4\Psi\) bytes) + Mô-men bậc 1 \(m\)fp32(\(4\Psi\) bytes) + Mô-men bậc 2 \(v\)fp32(\(4\Psi\) bytes).
Tổng bộ nhớ tĩnh là \(16\Psi\) bytes (chưa tính kích hoạt): mô hình 7B cần 112.0 GB tĩnh (113.1 GB tổng), còn 70B cần 1,120.0 GB tĩnh (1,123.6 GB tổng)!
LoRA (Hu et al., ICLR 2022) — Hạng Nội tại Thấp & Gộp Không Độ trễ#
Đóng băng \(\mathbf{W}_0 \in \mathbb{R}^{d_{\text{out}} \times d_{\text{in}}}\) và học ma trận độ dịch hạng \(r \ll \min(d_{\text{in}}, d_{\text{out}})\):
- Bất biến khởi tạo 0: Khởi tạo \(\mathbf{A}\) theo Kaiming và \(\mathbf{B} = \mathbf{0} \implies \Delta\mathbf{W} = \mathbf{0}\) ở bước \(0\) (
Lab 12,Test 04: sai lệch0.0e+00), bảo toàn nguyên vẹn mô hình nền. - Gộp trọng số không tăng độ trễ suy luận: \(\mathbf{W}_{\text{merged}} = \mathbf{W}_0 + \frac{\alpha}{r}\mathbf{B}\mathbf{A}\) được gộp thẳng vào một tầng
nn.Linearduy nhất trước khi phục vụ (Test 04: sai khác cực đại1.07e-06).
QLoRA (Dettmers et al., NeurIPS 2023) — NF4 4-Bit & Lượng tử hóa Kép#
Lượng tử hóa trọng số nền \(\mathbf{W}_0\) sang chuẩn NF4 (4-bit NormalFloat) gồm 16 mức phân vị đồng xác suất của phân phối chuẩn chuẩn hóa \(\mathcal{N}(0, 1)\) theo từng khối cỡ \(B = 64\) (kèm absmax mỗi khối), sau đó lượng tử hóa tiếp các hằng số absmax fp32 sang fp8 theo siêu khối 256 (Double Quantization). Số bit hiệu dụng mỗi tham số nền giảm xuống đúng:
Kết quả đo thực nghiệm trong Lab 12 (Test 06, ma trận Gaussian 256 × 256, B = 64): NF4 đạt 20.69 dB SNR (RMSE = 0.00185), vượt trội so với lượng tử hóa INT4 đồng đều (19.35 dB, RMSE = 0.00216, lợi +1.34 dB) với hệ số nén 3.88× so với bf16 (7.75× so với fp32). Nhờ vậy, tổng VRAM tinh chỉnh 70B rơi từ 1,123.6 GB xuống 43.3 GB (cắt 25.9×, chạy vừa một GPU 80 GB duy nhất!).
DoRA (Liu et al., ICML 2024 Oral) — Phân rã Biên độ & Hướng#
Phân tích cập nhật của Full FT cho thấy biên độ và hướng của từng hàng trọng số thay đổi độc lập nhau (tương quan âm nhẹ), trong khi LoRA buộc chúng đồng biến. DoRA tách riêng vector biên độ học được \(\mathbf{m} \in \mathbb{R}^{d_{\text{out}}}\) và chỉ áp hạng thấp lên hướng chuẩn hóa:
Chi phí thêm cho vector \(\mathbf{m}\) trên mô hình 70B chỉ là +0.15 GB (0.34% vs 0.32% tham số), vẫn gộp hoàn hảo về một ma trận duy nhất (Test 05 & Lab 12: sai số gộp 0.00e+00), và trong Stage 2 SFT của Lab 12 đạt Eval Response NLL thấp nhất 0.027 cùng 100.0% độ chính xác held-out (vượt LoRA 0.034 / 96.9%).
1.3 Vòng đời Căn chỉnh Ưu tiên: Prompt-Masked SFT, RLHF, Dẫn xuất Đóng DPO, SimPO/ORPO & Constitutional AI#
Prompt-Masked SFT#
Trên tập cặp chỉ dẫn \((x, y)\), hàm mất mát SFT chuẩn bắt buộc gán ignore_index = -100 trên toàn bộ token prompt \(x\):
Trong Lab 12 (Test 09), khi prompt có 3 token tiêu đề ngữ cảnh biến thiên, Unmasked LoRA lãng phí dung lượng adapter hạng 6 nên dừng ở NLL 0.117 (75.0% acc), còn Prompt-Masked LoRA đạt NLL 0.034 (96.9% acc).
RLHF (Bradley–Terry Reward Model + KL-Regularized PPO) \(\to\) Dẫn xuất Đóng DPO#
Trong RLHF, bài toán tối ưu chính sách dưới ràng buộc KL với mô hình tham chiếu \(\pi_{\text{ref}}\) là:
Viết lại hàm mục tiêu theo phân kỳ KL tới phân phối Gibbs \(\pi^*(y \mid x) = \frac{1}{Z(x)}\pi_{\text{ref}}(y \mid x)\exp\!\big(\frac{1}{\beta}r(x, y)\big)\) với \(Z(x) = \sum_y \pi_{\text{ref}}(y \mid x)\exp\!\big(\frac{1}{\beta}r(x, y)\big)\):
Vì \(D_{\text{KL}} \ge 0\) và bằng 0 khi và chỉ khi \(\pi = \pi^*\), nghiệm tối ưu toàn cục là duy nhất và cho phép biểu diễn tường minh phần thưởng theo chính sách:
Thay trực tiếp vào mô hình xác suất ưu tiên Bradley–Terry \(P(y_w \succ y_l \mid x) = \sigma\big(r(x, y_w) - r(x, y_l)\big)\), hằng số chuẩn hóa khó tính \(\beta \log Z(x)\) triệt tiêu tuyệt đối, sinh ra hàm mất mát DPO (Rafailov et al., NeurIPS 2023):
- Bệnh lý Likelihood Displacement & Cách khắc phục: Vì \(\mathcal{L}_{\text{DPO}}\) chỉ tối ưu hiệu log-ratio \(\Delta\hat{r} = \hat{r}_\theta(x, y_w) - \hat{r}_\theta(x, y_l)\), mô hình có thể đẩy giảm xác suất của cả \(y_w\) lẫn \(y_l\) miễn là \(y_l\) tụt sâu hơn. Giải pháp thực chiến trong
Lab 12là cộng neo điều chuẩn NLL nhỏ (0.05) trên \(y_w\) và giám sát riêngchosen_mean_logp(-0.0338 -> -0.0377) cùngchosen_kl_k3(0.0003). SimPO(NeurIPS 2024) &ORPO(EMNLP 2024):SimPObỏ hẳn mô hình \(\pi_{\text{ref}}\) bằng cách chuẩn hóa log-xác suất theo độ dài câu trả lời kèm biên \(\gamma > 0\): \(\mathcal{L}_{\text{SimPO}} = -\mathbb{E}[\log \sigma(\frac{\beta}{|y_w|}\log\pi_\theta(y_w|x) - \frac{\beta}{|y_l|}\log\pi_\theta(y_l|x) - \gamma)]\); cònORPOgộp luônSFTvà ưu tiên vào một chặng duy nhất qua tỷ số chênh (odds ratio).Constitutional AI&RLAIF(Anthropic): Thay gán nhãn thủ công đắt đỏ bằng bộ quy tắc Hiến pháp tường minh qua hai pha: (1)SL-CAI(Critique \(\to\) Revise tự sửa câu trả lời vi phạm thành phản hồi sạch), và (2)RLAIFsinh bộ cặp \((x, y_w, y_l)\) tổng hợp đưa thẳng vàoDPO/PPO(giảm10×–20×chi phí gán nhãn).
1.4 Hậu huấn luyện Suy luận SOTA 2025–2026: GRPO, Chứng minh Schulman k3 KL & RLVR#
Trong các miền có tiêu chuẩn đúng/sai kiểm chứng được bằng chương trình (toán học, mã nguồn, định lý hình thức, JSON có ràng buộc), GRPO (Group Relative Policy Optimization — DeepSeekMath / DeepSeek-R1) kết hợp RLVR (RL with Verifiable Rewards) loại bỏ đồng thời cả mạng Critic (cắt 50% VRAM so với PPO) lẫn Reward Model nơ-ron (miễn nhiễm hack phần thưởng).
Với mỗi prompt \(x\), lấy mẫu nhóm \(G\) câu trả lời \(\{o_1, \dots, o_G\} \sim \pi_{\theta_{\text{old}}}(\cdot \mid x)\), chấm từng câu bằng bộ kiểm chứng tất định \(r_i = R_{\text{ver}}(x, o_i)\), rồi chuẩn hóa lợi thế nội bộ nhóm:
Khi toàn bộ \(G\) mẫu có cùng phần thưởng (\(\sigma_G = 0\), homogeneous group), đặt \(\hat{A}_i = 0\) để tránh chia cho 0 (trong Lab 12, Test 12 xác minh \(\operatorname{mean}(\hat{A}) = 0\), \(\operatorname{std}(\hat{A}) \approx 1.0\) trên nhóm đa dạng và \(\hat{A} \equiv \mathbf{0}\) trên nhóm đồng nhất). Mục tiêu tối ưu GRPO trên từng token:
Chứng minh Bất đẳng thức Không âm & Không chệch của Bộ ước lượng KL Schulman k3#
Đặt tỷ số xác suất nghịch đảo \(u = \frac{\pi_{\text{ref}}(a \mid s)}{\pi_\theta(a \mid s)} > 0\). Định nghĩa ước lượng Schulman k3:
- Không âm tuyệt đối (\(k_3(u) \ge 0\;\forall u > 0\), dấu
=khi và chỉ khi \(u = 1\)): Xét \(f(u) = u - \log u - 1\) trên \((0, +\infty)\). Ta có \(f'(u) = 1 - \frac{1}{u} = 0 \iff u = 1\) và \(f''(u) = \frac{1}{u^2} > 0\;\forall u > 0\). Do \(f\) lồi chặt, cực tiểu toàn cục duy nhất nằm tại \(u = 1\) với \(f(1) = 1 - 0 - 1 = 0\). - Không chệch chính xác đối với phân kỳ KL thực:
Khi lấy mẫu hành động \(a \sim \pi_\theta(\cdot \mid s)\):
\[\mathbb{E}_{a \sim \pi_\theta}\big[u - 1\big] = \sum_{a} \pi_\theta(a \mid s)\frac{\pi_{\text{ref}}(a \mid s)}{\pi_\theta(a \mid s)} - 1 = \sum_{a} \pi_{\text{ref}}(a \mid s) - 1 = 1 - 1 = 0.\]Suy ra:\[\mathbb{E}_{a \sim \pi_\theta}\big[k_3(u)\big] = \mathbb{E}_{a \sim \pi_\theta}\!\left[\log \frac{\pi_\theta(a \mid s)}{\pi_{\text{ref}}(a \mid s)}\right] + \mathbb{E}_{a \sim \pi_\theta}\big[u - 1\big] = D_{\text{KL}}\big(\pi_\theta \,\|\, \pi_{\text{ref}}\big).\]
- Giảm mạnh phương sai so với \(k_1 = -\log u\): Số hạng \((u - 1)\) đóng vai trò biến kiểm soát (control variate) triệt tiêu biến động âm của \(-\log u\), đảm bảo phạt KL trong
GRPOluôn ổn định số học (Test 03xác minhmin(k3) >= 0.0,k3 == 0.0khi hai chính sách trùng nhau, và gradient PyTorch hữu hạn).
Trụ cột 2 — Kiến trúc Hệ thống Hậu huấn luyện Sản xuất, Ngân sách VRAM & Mô phỏng Tương tác#
2.1 Đường ống Vòng đời 4 Chặng LLM Từ Con Số 0 & Kế toán VRAM PEFT#
Bảng đối chiếu chính xác ngân sách VRAM cho mô hình 7B và 70B (rank = 16, 7 tầng chiếu Attention + SwiGLU, seq_len = 2048, grad_checkpointing = True, trích trực tiếp từ artifacts/ch21_lab12_results.json):
| Mô hình & Phương pháp | VRAM Tĩnh (GB) | Kích hoạt (GB) | Tổng VRAM (GB) | Tham số Huấn luyện & Khả năng Chạy |
|---|---|---|---|---|
7B Full FT (AdamW bf16) |
112.0 |
1.1 |
113.1 |
100.0% (Tràn 1× 80GB) |
7B LoRA / DoRA (bf16) |
14.6 / 14.7 |
1.1 |
15.8 / 15.8 |
0.57% / 0.59% (Vừa 1× 24GB) |
7B QLoRA (NF4 + DQ) |
4.3 |
1.1 |
5.4 (21.0× cut) |
0.57% (Vừa GPU laptop 8–16GB) |
70B Full FT (AdamW bf16) |
1,120.0 |
3.6 |
1,123.6 |
100.0% (Cần cụm 16× H100 80GB) |
70B LoRA / DoRA (bf16) |
143.6 / 143.8 |
3.6 |
147.2 / 147.4 |
0.32% / 0.34% (Cần 2× 80GB) |
70B QLoRA (NF4 + DQ) |
39.7 |
3.6 |
43.3 (25.9× cut) |
0.32% (Vừa khít 1× 80GB GPU!) |
Hãy tự tay thay đổi cỡ mô hình (7B/13B/70B), hạng r, độ dài chuỗi và so sánh mật độ lượng tử hóa NF4 vs INT4 + phân rã biên độ–hướng DoRA trong trình mô phỏng tương tác đầu tiên:
2.2 So sánh Topo Bộ nhớ Hậu huấn luyện: RLHF-PPO (4 Mô hình) vs DPO vs GRPO + RLVR#
- Với mô hình
70B,RLHF-PPOfull-param ngốn2,520 GBtrạng thái tĩnh, cònDPOvàGRPO + RLVRcắt chính xác một nửa xuống1,260 GB(-50.0%), vàSimPO(không cần \(\pi_{\text{ref}}\)) còn1,120 GB. Khi kết hợp thêmLoRA/QLoRAtrên Actor,DPOvàGRPOthậm chí chạy được trên các cụm nhỏ hơn10×!
Hãy tương tác trực tiếp với đường cong kẹp PPO (\(L^{\text{CLIP}}\)), biên ưu tiên Bradley–Terry của DPO và chẩn đoán Likelihood Displacement trong trình mô phỏng tương tác thứ hai:
2.3 Kiến trúc Vòng lặp Rollout GRPO + RLVR & Cổng Chống Sụp đổ Huấn luyện#
Trong vận hành thực tế các cụm GRPO + RLVR quy mô lớn (kiểu DeepSeek-R1 / Qwen-QwQ), nút thắt thời gian không nằm ở bước lan truyền ngược (backward) mà ở pha sinh rollout (70%–80% tổng thời gian mỗi bước) vì phải giải mã tự hồi quy dài \(G = 8..16\) chuỗi suy luận cho mỗi prompt. Kiến trúc sản xuất chuẩn 2026 tách hẳn Rollout Engine (vLLM / SGLang chạy FP8 + đồng bộ trọng số nhanh qua NCCL) khỏi Training Engine (FSDP2 / Megatron-Core), đồng thời chạy Deterministic Verifier trong sandbox cô lập trên cụm CPU để đảm bảo 0 lỗ hổng thực thi mã từ mã nguồn do mô hình tự sinh!
Hãy điều chỉnh cỡ nhóm \(G\), xác suất giải đúng \(p\), hệ số phạt \(\beta_{\text{KL}}\) và quan sát tức thời lợi thế nhóm \(\hat{A}_i\), hiện tượng nhóm đồng nhất (\(\sigma_G = 0\)) cùng đường cong Schulman k3 KL trong trình mô phỏng tương tác thứ ba:
2.4 Cẩm nang Quyết định Hậu huấn luyện Sản xuất (2026)#
| Tình huống / Ràng buộc Thực tế | Chiến lược Khuyến nghị (Go) |
Chống mẫu Phải Tránh (No-Go) |
Ngưỡng Kiểm soát Tham chiếu |
|---|---|---|---|
Tinh chỉnh 70B trên 1× 80GB GPU |
QLoRA (NF4 + DQ) hoặc QDoRA (r = 16, đủ 7 tầng Attn+FFN) |
Full FT bf16 (1,123.6 GB OOM) hoặc chỉ áp LoRA lên q, v |
Tổng VRAM \(\le 45\text{ GB}\), merge_diff < 1e-5 |
Tinh chỉnh SFT có Prompt Dài / Biến thiên |
Prompt-Masked SFT (ignore_index = -100 trên prompt) + DoRA/LoRA |
Tính loss cả lên System Prompt / câu hỏi người dùng | Response NLL giảm mạnh hơn Unmasked (0.027 vs 0.117) |
| Căn chỉnh Phong cách & An toàn Chi phí Thấp | Constitutional AI (SL-CAI + RLAIF) + DPO (+ neo NLL nhỏ) hoặc SimPO |
Chạy RLHF-PPO 4 mô hình chỉ để chỉnh giọng văn, hoặc DPO không theo dõi chosen_logp |
pref_acc >= 95%, chosen_kl_k3 < 0.15, không tụt chosen_logp |
| Tăng năng lực Toán / Code / Logic Suy luận | Cold-Start SFT \(\to\) GRPO + RLVR (\(G = 6..16\), Schulman k3 KL, Verifier sandbox) |
Dùng Reward Model nơ-ron chấm toán/code (dễ Reward Hacking) hoặc giữ prompt \(\sigma_G = 0\) | Verifiable accuracy tăng >= +15..30pp, k3_KL < 0.3 |
| Phục vụ Sau Hậu huấn luyện & Lưu trữ | Gộp LoRA/DoRA về trọng số thuần (0 ms overhead) + lưu safetensors |
Phục vụ nhánh adapter chưa gộp cho 1 mô hình tĩnh hoặc lưu bằng pickle |
merge_diff < 1e-5, safetensors_diff == 0.0 |
2.5 Góc nhìn SOTA 2025–2026: Tiến hóa RL Suy luận (RLOO, Dr. GRPO, GSPO), CoT Reward Hacking & Giám sát Cơ chế (Principal Industrial Tip #5)#
Kinh nghiệm Triển khai Hậu huấn luyện Tuyến đầu (Reasoning RL Optimization, CoT Reward Hacking & Mechanistic Steering):
- Từ
GRPOđếnRLOO,Dr. GRPO&GSPO(Loại bỏ Thiên lệch Độ dài & Bất ổn MoE):RLOO(REINFORCE Leave-One-Out): Thay vì trừ trung bình cả nhóm \(\mu_G\) (gồm chính mẫu \(i\)),RLOOdùng đường cơ sở không chệch từ \(G-1\) mẫu còn lại \(b_{-i} = \frac{1}{G-1}\sum_{j \ne i} r_j\), loại bỏ tương quan tự thân mà không cần mạng Critic.Dr. GRPO(GRPO Done Right):GRPOgốc chia lợi thế cho độ lệch chuẩn nhóm \(\sigma_G\) và chia mất mát cho độ dài riêng từng chuỗi \(|o_i|\), tạo thiên lệch độ dài (verbosity bias): khi câu trả lời sai (\(\hat{A}_i < 0\)), chia cho \(|o_i|\) khiến câu sai càng dài bị phạt nhẹ hơn theo từng token!Dr. GRPOloại bỏ \(\sigma_G\) ở mẫu số và chuẩn hóa theo hằng số ngân sách độ dài cố định \(L_{\max}\), giữ tính không chệch của gradient và chấm dứt hiện tượng phình chuỗi suy luận vô ích.GSPO(Group Sequence Policy Optimization): TrongGRPO, tỷ số lấy mẫu tầm quan trọng \(\rho_{i,t} = \pi_\theta(o_{i,t}\mid\cdot)/\pi_{\text{old}}(o_{i,t}\mid\cdot)\) tính ở cấp token, dễ nổ phương sai và gây mất ổn định định tuyến trênSparse MoE.GSPO(Qwen team, 2025) tính tỷ số và kẹp cận ở cấp toàn chuỗi \(\rho_i = (\pi_\theta(o_i \mid x)/\pi_{\text{old}}(o_i \mid x))^{1/|o_i|}\), đồng bộ trực tiếp đơn vị phần thưởng toàn chuỗi với đơn vị cập nhật chính sách.
CoT Reward HackingDướiRLVRThuần Kết quả (Outcome-Only RLVR): Khi hàm thưởng chỉ chấm đầu ra cuối (pass unit test / đáp số đúng), mô hình có thể nảy sinhCoT Reward Hacking— lợi dụng lỗ hổng bộ kiểm thử biên (verifier loopholes), viết nháp ngụy tạo (deceptive scratchpad), hoặc cố tình làm mờ chuỗi lập luận (obfuscated CoT) nếu kỹ sư đưa thêm bộ phạt giám sátCoTvào thẳng mục tiêu RL! Quy chuẩn sản xuất: không tối ưu trực tiếp chống lại giám sát ngôn ngữ tự nhiên; hãy tách riêng bộ kiểm toánCoTngoại tuyến, mở rộng kiểm thử ngẫu nhiên hóa trường hợp biên, và giám sát thêm ở tầng kích hoạt nội tại.- Căn chỉnh Cơ chế Hậu kiểm (
SAEs,RepE&Circuit Breakers): Sau vòngDPO/GRPO/GSPO, bổ sungTopK/JumpReLU SAEsđể giải mã đặc trưng đơn nghĩa kiểm toán hành vi lừa dối trong không gian kích hoạt ẩn, kết hợpCircuit Breakers(bẻ gãy quỹ đạo biểu diễn độc hại ở các lớp giữa ngay cả khi bị ép tiền tố) và bộ đánh giá suy giảm năng lực (MMLU/GSM8K/Code + Over-Refusal Suite; xem sâu hơn về phòng thủ an toàn &CC++tại Chương 22).
Trụ cột 3 — Ngăn xếp Công nghệ 2026 & Mã Python Thực thi Đầu-Cuối#
3.1 Ngăn xếp Kỹ thuật Hậu huấn luyện 2026#
- Lõi Huấn luyện & PEFT:
PyTorch 2.x(FSDP2,torch.compile),PEFT(LoRA/DoRA),bitsandbytes(NF4+ Paged AdamW),safetensors(zero-pickle). - Hậu huấn luyện RL / Preference:
TRL(SFTTrainer,DPOTrainer,GRPOTrainer),verl/OpenRLHF(tách pha RolloutvLLM/SGLangkhỏi LearnerFSDP2).
3.2 Ma trận 6 Chống mẫu Hậu huấn luyện & Cổng Kiểm soát Tự động (Lab 12 CI Gates)#
| # | Chống mẫu (Anti-Pattern) |
Triệu chứng Thất bại Thực tế | Cổng Kiểm soát Tự động (Lab 12 CI Gate) |
|---|---|---|---|
| 1 | Không che prompt (mask_prompt=False) khi SFT |
Adapter hạng thấp bị loãng vào header ngữ cảnh, Response NLL cao gấp 3.5× (0.117 vs 0.034) |
Khẳng định masked_nll < unmasked_nll (Test 09) |
| 2 | Khởi tạo \(\mathbf{B} \ne \mathbf{0}\) trong LoRA hoặc sai chuẩn hóa DoRA |
Phá hủy phân phối pretrained ngay bước 0, lệch logit khi gộp adapter phục vụ |
Khẳng định zero_init_diff < 1e-5 và merge_max_diff < 1e-5 (Tests 04, 05) |
| 3 | Dùng DPO với bước học quá lớn / thiếu neo NLL |
Likelihood Displacement: biên dương nhưng cả chosen_logp lẫn chất lượng sinh đều tụt dốc |
Kiểm tra pref_acc >= 0.90, margin_gain > 1.0, 0 <= kl_k3 < 2.0 (Test 11) |
| 4 | Dùng ước lượng KL k1 có thể âm thay cho Schulman k3 |
Phạt KL âm kích thích chính sách chạy càng xa \(\pi_{\text{ref}}\), gây vỡ ngôn ngữ (KL explosion) | Khẳng định min(schulman_k3_kl) >= 0.0 và == 0.0 tại \(\pi_\theta = \pi_{\text{ref}}\) (Test 03) |
| 5 | Chia cho \(\sigma_G = 0\) khi gặp nhóm GRPO đồng nhất |
Phát sinh NaN/Inf làm hỏng toàn bộ trọng số mô hình ngay giữa kỳ huấn luyện |
Bắt buộc compute_group_relative_advantages trả về 0 khi \(\sigma_G < \epsilon\) (Test 12) |
| 6 | Lưu/nạp checkpoint bằng pickle / torch.save mặc định |
Lỗ hổng thực thi mã tùy ý (RCE) khi chia sẻ adapter hoặc checkpoint giữa các nhóm | Khẳng định safetensors khớp 0.0 & quét AST cấm toàn bộ deserializer rủi ro (Tests 15, 16) |
3.3 Mã Python Thực thi Đầu-Cuối (Sử dụng Trực tiếp llm_from_scratch_lab)#
Đoạn mã dưới đây chạy hoàn toàn ngoại tuyến trên .venv (PyTorch 2.15.0+cpu), kiểm chứng toàn bộ 4 chặng vòng đời LLM từ con số 0 cùng kế toán VRAM PEFT và lưu trữ safetensors:
from __future__ import annotations
import tempfile
from pathlib import Path
import torch
from llm_from_scratch_lab import (
ArithmeticVocab,
PEFTMemoryConfig,
TinyModernDecoderLM,
align_with_dpo,
audit_lora_and_dora_merge_parity,
audit_nf4_quantization_roundtrip,
build_arithmetic_splits,
compute_peft_vram_budget,
generate_constitutional_pairs,
load_safetensors_checkpoint,
posttrain_with_grpo_rlvr,
pretrain_tiny_llm,
run_ppo_policy_benchmark,
save_safetensors_checkpoint,
sft_with_peft,
)
from llm_from_scratch_lab.tiny_llm_lifecycle import merge_peft_adapters
def run_ch21_end_to_end_lifecycle(seed: int = 42) -> None:
"""Chạy kiểm chứng đầu-cuối RL, PEFT và vòng đời 4 chặng LLM từ con số 0."""
ppo = run_ppo_policy_benchmark(seed=seed)
v70 = compute_peft_vram_budget(PEFTMemoryConfig())
parity = audit_lora_and_dora_merge_parity(seed=seed)
nf4 = audit_nf4_quantization_roundtrip(seed=seed)
print(f"[0] PPO {ppo['initial_expected_return']:.2f}->{ppo['final_expected_return']:.2f} | "
f"70B FullFT={v70['full_ft_total_gb']:.1f}GB -> QLoRA={v70['qlora_nf4_total_gb']:.1f}GB | "
f"NF4 SNR={nf4['nf4_snr_db']:.2f}dB | DoRA merge={parity['dora_merge_max_diff']:.2e}")
vocab = ArithmeticVocab()
splits = build_arithmetic_splits(seed=seed)
train_s, eval_s = splits["train"], splits["eval"]
# Chặng 1: Pre-Training (CLM)
base_lm, s1 = pretrain_tiny_llm(train_s, eval_s, vocab, steps=95, seed=seed)
print(f"[1] Pre-Train PPL: {s1['init_eval_ppl']:.2f} -> {s1['final_eval_ppl']:.2f} ({s1['ppl_reduction_factor']:.1f}x)")
# Chặng 2: SFT với LoRA (Che Prompt vs Không Che) & DoRA
sft_lora, s2_m = sft_with_peft(base_lm, train_s, eval_s, vocab, method="lora", rank=6, alpha=12.0, mask_prompt=True, steps=45, lr=6e-3, seed=seed)
_, s2_u = sft_with_peft(base_lm, train_s, eval_s, vocab, method="lora", rank=6, alpha=12.0, mask_prompt=False, steps=45, lr=6e-3, seed=seed)
_, s2_d = sft_with_peft(base_lm, train_s, eval_s, vocab, method="dora", rank=6, alpha=12.0, mask_prompt=True, steps=45, lr=6e-3, seed=seed)
print(f"[2] SFT NLL: Unmasked={s2_u['final_response_nll']:.3f} -> Masked LoRA={s2_m['final_response_nll']:.3f} -> DoRA={s2_d['final_response_nll']:.3f}")
# Chặng 3: Constitutional AI Critique-Revise + DPO
tr_pairs, _ = generate_constitutional_pairs(train_s)
ev_pairs, _ = generate_constitutional_pairs(eval_s)
_, s3 = align_with_dpo(sft_lora, tr_pairs, ev_pairs, vocab, beta=0.25, steps=22, seed=seed)
print(f"[3] DPO PrefAcc: {100*s3['before_eval']['preference_accuracy']:.1f}% -> {100*s3['after_eval']['preference_accuracy']:.1f}% (margin=+{s3['after_eval']['mean_reward_margin']:.2f})")
# Chặng 4: Cold-Start SFT -> Critic-Free GRPO + RLVR + Safetensors
sft_cold, _ = sft_with_peft(base_lm, train_s[:24], eval_s, vocab, method="lora", rank=6, alpha=12.0, mask_prompt=True, steps=10, lr=4e-3, seed=seed + 7)
grpo_lm, s4 = posttrain_with_grpo_rlvr(sft_cold, train_s, eval_s, vocab, group_size=8, steps=36, clip_eps=0.2, kl_beta=0.02, lr=2.5e-3, temperature=0.95, seed=seed)
merged = merge_peft_adapters(grpo_lm).eval()
reloaded = TinyModernDecoderLM(merged.cfg).eval()
with tempfile.TemporaryDirectory() as tmp:
ckpt = save_safetensors_checkpoint(merged, Path(tmp) / "tiny_grpo.safetensors")
load_safetensors_checkpoint(reloaded, ckpt)
probe = torch.tensor([vocab.encode(s.prompt_tokens) for s in eval_s[:4]], dtype=torch.long)
with torch.no_grad():
st_diff = float((merged(probe) - reloaded(probe)).abs().max().item())
print(f"[4] GRPO VerifAcc: {100*s4['before_eval']['exact_accuracy']:.1f}% -> {100*s4['after_eval']['exact_accuracy']:.1f}% (+{100*s4['eval_accuracy_lift']:.1f}pp, k3={s4['final_kl_k3']:.4f}) | Safetensors={st_diff:.1e}")
if __name__ == "__main__":
run_ch21_end_to_end_lifecycle()
Trụ cột 4 — Phòng thí nghiệm Hai Tầng (Lab 12) & Hợp đồng 16 Kiểm thử#
4.1 Kiến trúc Hai Tầng (labs/lab-12-llm-from-scratch-pretrain-sft-posttrain/)#
- Tầng 1 (Lõi RL & Lượng tử hóa Giải tích —
src/llm_from_scratch_lab/rl_and_peft.py):compute_gae_advantages,ppo_clipped_surrogate_loss,schulman_k3_kl_numpy/schulman_k3_kl,run_ppo_policy_benchmark.LoRALinear,DoRALinear,audit_lora_and_dora_merge_parity,nf4_quantize_blockwise/nf4_dequantize_blockwise,audit_nf4_quantization_roundtrip,compute_peft_vram_budget,compute_post_training_vram_comparison.
- Tầng 2 (Vòng đời 4 Chặng LLM Thực thụ
PyTorch 2.15.0+cpu+Safetensors—src/llm_from_scratch_lab/tiny_llm_lifecycle.py):ArithmeticVocab,TinyModernDecoderLM(42,280tham số:RMSNorm,RoPE, Causal Self-Attention,SwiGLU),inject_peft_adapters,merge_peft_adapters.pretrain_tiny_llm,sft_with_peft,generate_constitutional_pairs,compute_dpo_loss,align_with_dpo,compute_group_relative_advantages,verify_arithmetic_completion,posttrain_with_grpo_rlvr,save_safetensors_checkpoint/load_safetensors_checkpoint, vàrun_full_ch21_lab12_benchmarks.
4.2 Bảng Kết quả Benchmark Đã Xác minh (artifacts/ch21_lab12_results.json, seed=42)#
Thí nghiệm Lab 12 |
Cấu hình / Đối chứng | Số đo Ghi nhận Chính xác | Kết luận Kỹ thuật |
|---|---|---|---|
RL (GAE + PPO + k3 KL) |
MDP 4 trạng thái, 40 bước + 7B VRAM | Return 1.31 -> 5.65 (opt 6.00); 7B VRAM PPO 252 -> GRPO 126 GB (-50%) |
PPO hội tụ sát tối ưu; GRPO cắt một nửa VRAM |
PEFT 70B VRAM & NF4 |
r = 16, 7 tầng Attn+FFN, B = 64 |
Full FT 1,123.6 GB \(\to\) LoRA 147.2 \(\to\) QLoRA 43.3 GB (25.9×); NF4 20.69 dB (+1.34 dB) |
QLoRA vừa khít 1× 80GB; DoRA merge 0.00e+00 |
Chặng 1 — Pre-Training (CLM) |
TinyModernDecoderLM (42,280 params) |
Eval PPL 31.11 -> 2.69 (giảm 11.6×); Base canonical Acc 12.5% |
Học vững cú pháp & số học nhưng chưa chuẩn chat |
Chặng 2 — SFT (LoRA/DoRA) |
rank = 6, 15 tầng, Che vs Không che |
Unmasked: NLL 0.117 (75.0%) \(\to\) Masked LoRA: 0.034 (96.9%) \(\to\) DoRA: 0.027 (100.0%) |
Che prompt cắt 3.5× NLL; DoRA đạt 100% |
Chặng 3 — DPO + CAI |
\(\beta = 0.25\), frozen ref_model, 2 quy tắc |
Pref Acc 50.0% -> 100.0%, Margin +9.40, chosen_kl_k3 = 0.0003 |
Khử hoàn toàn câu trả lời vi phạm, giữ sạch chosen_logp |
Chặng 4 — GRPO + RLVR |
Cold-Start SFT, \(G = 8\), clip = 0.2, k3 |
Held-out Acc 40.6% -> 71.9% (+31.2pp; Train 64.8% -> 93.2%), k3 = 0.1104, ST = 0.0 |
Verifier tất định nâng mạnh năng lực suy luận không cần Critic |
4.3 Hợp đồng 16 Kiểm thử Tự động (tests/test_llm_from_scratch_lab.py)#
| STT | Hàm Kiểm thử Pytest |
Bất biến Nghiệm thu Bắt buộc (CPU-Only, 0 Skips) |
|---|---|---|
1 |
test_01_pydantic_configs_strict_forbid |
Từ chối trường lạ (extra="forbid") và sai chia hết d_model % n_heads hoặc d_head lẻ |
2 |
test_02_gae_advantages_and_ppo_clipping_invariants |
GAE khớp TD(0) tại \(\lambda=0\) và MC tại \(\lambda=1\) (< 1e-12); PPO kẹp đúng mức trần/sàn & tăng return > +2.0 |
3 |
test_03_schulman_k3_kl_nonnegative_and_zero_at_identity |
Schulman k3 >= 0.0 trên mọi mẫu, == 0.0 khi hai phân phối trùng nhau, đạo hàm PyTorch hữu hạn |
4 |
test_04_lora_zero_init_and_exact_merge_parity |
LoRALinear giữ nguyên đầu ra tại bước 0 (< 1e-6), đóng băng base, gộp merge_to_linear() < 1e-5 |
5 |
test_05_dora_magnitude_direction_decomposition_and_param_ratio |
DoRALinear phân rã biên độ–hướng chính xác, khớp gộp < 1e-5, thêm đúng out_features tham số |
6 |
test_06_qlora_nf4_quantization_roundtrip_and_vram_accounting |
NF4 vượt INT4 đồng đều về SNR & RMSE; 70B QLoRA <= 80 GB, Full FT > 1100 GB; GRPO giảm 50% VRAM vs PPO |
7 |
test_07_tiny_llm_causal_masking_invariant |
Thay đổi token tương lai \(t > i\) không làm thay đổi logit tại vị trí \(i\) (max_diff < 1e-6) |
8 |
test_08_stage1_pretrain_perplexity_drop |
Chặng 1 Pre-Training cắt giảm eval perplexity > 5× (31.11 -> 2.69) |
9 |
test_09_stage2_sft_prompt_masking_and_lora_dora_lift |
Prompt-Masked SFT vượt Unmasked về Response NLL; DoRA đạt >= 80% held-out accuracy |
10 |
test_10_constitutional_ai_critique_revise_pair_generator |
Mọi cặp sinh ra phát hiện vi phạm Hiến pháp trên rejected và giữ reward == 1.0, 0 token cấm trên chosen |
11 |
test_11_stage3_dpo_reward_margin_and_preference_accuracy_gain |
DPO đạt preference_accuracy >= 90%, margin_gain > 1.0, và 0 <= chosen_kl_k3 < 2.0 |
12 |
test_12_grpo_group_advantage_zero_mean_unit_std_and_homogeneous_guard |
Lợi thế nhóm GRPO có trung bình 0, độ lệch chuẩn ~1.0 trên nhóm đa dạng và 0 trên nhóm đồng nhất |
13 |
test_13_deterministic_rlvr_arithmetic_verifier_contract |
Verifier trả 1.0 khi đúng cả định dạng & kết quả, 0.25 khi chỉ đúng định dạng, 0.0 khi sai định dạng |
14 |
test_14_stage4_grpo_rlvr_verifiable_accuracy_lift_bounded_kl |
GRPO + RLVR nâng độ chính xác kiểm chứng held-out >= +15pp so với Cold-Start SFT với k3 KL bị chặn |
15 |
test_15_safetensors_checkpoint_roundtrip_zero_pickle |
Lưu/nạp TinyModernDecoderLM qua safetensors đạt sai lệch logit tuyệt đối 0.0 |
16 |
test_16_cli_demo_workbench_json_schema_and_ast_deserialization_guard |
run_lab_demo.py --quick xuất đủ 6 KPI, 4 bar, 4 bảng; quét AST cấm mọi deserializer rủi ro |
Trụ cột 5 — Văn liệu Nền tảng & SOTA (2017–2026), Ôn tập & Thang chấm Rubric#
5.1 Sáu Công trình Học thuật Nền tảng & Biên giới (2017–2026)#
- Schulman, J., et al. (2016, 2017). High-Dimensional Continuous Control Using Generalized Advantage Estimation (ICLR 2016) & Proximal Policy Optimization Algorithms (
arXiv:1707.06347). (Đặt nền tảngGAE(λ), mục tiêu kẹpPPOvà bộ ước lượng KLk3.) - Hu, E. J., et al. (2022) & Dettmers, T., et al. (2023). LoRA: Low-Rank Adaptation of Large Language Models (ICLR 2022) & QLoRA: Efficient Finetuning of Quantized LLMs (NeurIPS 2023). (Phá vỡ bức tường
16 B/parambằng adapter hạng thấp gộp0 msvà lượng tử hóaNF4+ Double Quantization.) - Liu, S.-Y., et al. (2024). DoRA: Weight-Decomposed Low-Rank Adaptation (ICML 2024 Oral). (Phân rã biên độ–hướng thu hẹp khoảng cách năng lực học giữa
LoRAvàFull Fine-Tuning.) - Ouyang, L., et al. (2022) & Bai, Y., et al. (2022). Training Language Models to Follow Instructions with Human Feedback (
InstructGPT) (NeurIPS 2022) & Constitutional AI: Harmlessness from AI Feedback (arXiv:2212.08073). (Thiết lập chuẩnSFT -> RLHFvà mở đường cho căn chỉnh an toàn tự độngSL-CAI/RLAIF.) - Rafailov, R., et al. (2023) & Meng, Y., et al. (2024). Direct Preference Optimization: Your Language Model is Secretly a Reward Model (NeurIPS 2023) & SimPO: Simple Preference Optimization with a Reference-Free Reward (NeurIPS 2024). (Nghiệm dạng đóng triệt tiêu \(Z(x)\) và tối ưu ưu tiên không cần mô hình tham chiếu.)
- Shao, Z., et al. (2024) & DeepSeek-AI (2025). DeepSeekMath: Pushing the Limits of Mathematical Reasoning (
arXiv:2402.03300) & DeepSeek-R1: Incentivizing Reasoning Capability in LLMs via Reinforcement Learning (arXiv:2501.12948). (Khai sinh hậu huấn luyện suy luậnGRPO + RLVRkhông cần Critic, tiết kiệm50%VRAM và kích hoạt năng lực tự kiểm chứng suy luận.)
5.2 Tám Câu hỏi Trắc nghiệm Kiểm tra Nhanh (Q1..Q8 — Khớp quiz_and_hints.json)#
Q1(REINFORCE + Baseline&GAE(λ)): Đường cơ sở \(b(s_t)\) không làm chệch kỳ vọng gradient vì \(\mathbb{E}[\nabla\log\pi_\theta \cdot b(s_t)] = b(s_t)\nabla(1) = 0\);GAEquy về TD(0) tại \(\lambda = 0\) và Monte Carlo tại \(\lambda = 1\).Q2(PPOClipped Surrogate): Phép lấy \(\min(\rho_t\hat{A}_t, \operatorname{clip}(\rho_t, 1-\epsilon, 1+\epsilon)\hat{A}_t)\) chặn bước nhảy lạc quan khi \(\hat{A}_t > 0\) (\(\rho_t > 1+\epsilon\)) và chặn lao dốc khi \(\hat{A}_t < 0\) (\(\rho_t < 1-\epsilon\)).Q3(Bức tường16 B/param&QLoRA NF4): Full FTAdamWhỗn hợp cần16 bytes/param(1,123.6 GBcho70B), cònQLoRA(NF4+ Double Quant =4.127 bit/param,+1.34 dBSNR so vớiINT4) cắt25.9×xuống43.3 GBvừa khít1× 80GB.Q4(LoRAvsDoRA& Merge0 ms):LoRAkhởi tạoB = 0và gộp \(\mathbf{W}_0 + \frac{\alpha}{r}\mathbf{B}\mathbf{A}\) không tăng độ trễ suy luận (1.07e-06), cònDoRAtách riêng biên độ \(\mathbf{m}\) và hướng chuẩn hóa để bám sát động học Full FT (0.00e+00merge diff,100%acc trongLab 12).Q5(Prompt-MaskedSFT): Gánignore_index = -100trên token prompt tập trung100%dung lượng adapter vào câu trả lời, cắt Response NLL từ0.117xuống0.034(3.5×) và nâng độ chính xác từ75.0%lên96.9%.Q6(Dẫn xuấtDPO& Likelihood Displacement): Nghiệm đóng \(\pi^* \propto \pi_{\text{ref}}\exp(r/\beta)\) làm triệt tiêu chính xác hàm phân hoạch \(Z(x)\) trong Bradley–Terry (giảm từ4xuống2mô hình); cần giám sátchosen_logp+ neo NLL nhỏ để tránh tụt xác suất câu đúng.Q7(Constitutional AI&RLAIF): Hai phaSL-CAI(Critique \(\to\) Revise theo nguyên tắc tường minh) vàRLAIF(tổng hợp cặp ưu tiên choDPO/PPO) cắt10×–20×chi phí gán nhãn an toàn.Q8(GRPO + RLVR& Schulmank3KL):GRPOchuẩn hóa lợi thế nội bộ nhóm \(\hat{A}_i = (r_i - \mu_G)/(\sigma_G + \epsilon)\) loại bỏ Critic (cắt50%VRAM so vớiPPO), dùng Schulmank3KL \(= u - \log u - 1 \ge 0\) không chệch, và kết hợp verifier tất định nâng độ chính xác từ40.6%lên71.9%(+31.2pp).
5.3 Sáu Bài tập Lập trình & Chứng minh Trọng số (Bài tập 1..6)#
-
Bài tập 1 (
15%) — Chứng minh Baseline Không chệch,GAE(λ)& Kẹp Bi quanPPO:Chứng minh đại số \(\mathbb{E}_{\pi_\theta}[\nabla_\theta \log\pi_\theta \cdot b(s_t)] = 0\), chứng minh hai giới hạn \(\lambda = 0\) (TD0) và \(\lambda = 1\) (Monte Carlo) của
GAE, và đối chiếu trêncompute_gae_advantages,ppo_clipped_surrogate_loss,run_ppo_policy_benchmark(Test 02). -
Bài tập 2 (
15%) — Chứng minh Tính Không âm & Không chệch của Schulmank3KL:Khảo sát hàm lồi \(f(u) = u - \log u - 1\) để chứng minh \(k_3(u) \ge 0\) với dấu bằng duy nhất tại \(u = 1\), chứng minh \(\mathbb{E}_{\pi_\theta}[k_3] = D_{\text{KL}}(\pi_\theta \| \pi_{\text{ref}})\), và so sánh phương sai với \(k_1\) trên
schulman_k3_kl(Test 03). -
Bài tập 3 (
20%) — Kế toán VRAM70B, Triển khaiLoRA/DoRAMerge & Lượng tử hóaNF4:Tính tay bảng bộ nhớ
16 B/paramcho7B&70B, công thức4.127 bit/paramcủaNF4 + Double Quantization, và xác minhLoRALinear,DoRALinear(merge< 1e-5) cùng ưu thế+1.34 dBSNR củanf4_quantize_blockwise(Tests 04, 05, 06). -
Bài tập 4 (
15%) — Dẫn xuất ĐóngDPO, Chẩn đoán Likelihood Displacement &Constitutional AI:Chứng minh đầy đủ từng bước từ mục tiêu KL-regularized
RLHFđến \(\mathcal{L}_{\text{DPO}}\) triệt tiêu \(Z(x)\), giải thích cơ chế Likelihood Displacement, và kiểm địnhgenerate_constitutional_pairs+align_with_dpo(Tests 10, 11). -
Bài tập 5 (
20%) — Vòng đời 4 Chặng LLM: Pre-Train \(\to\) Prompt-MaskedSFT\(\to\)GRPO + RLVR:Phân tích thực nghiệm vì sao che prompt (
ignore_index = -100) cắt3.5×Response NLL trênsft_with_peft, chứng minh cơ chế xử lý nhóm đồng nhất (\(\sigma_G = 0\)) trongcompute_group_relative_advantages, và phân tích độ tăng+31.2ppcủaposttrain_with_grpo_rlvr(Tests 08, 09, 12, 13, 14). -
Bài tập 6 (
15%) — An toàn Lưu trữSafetensors& Nghiệm thu Trọn góiLab 12(16/16 Pytest):Kiểm chứng bất biến mặt nạ nhân quả của
TinyModernDecoderLM, thực thi gộp adapter và lưu/nạpsafetensors(diff = 0.0), đảm bảo0import deserializer rủi ro qua quét AST, và vượt trọn bộ16/16 pytest,ruff,mypy,run_lab_demo.py(Tests 07, 15, 16).
5.4 Thang chấm Rubric (UCL MSc Grading Rubric)#
| Cấp độ Đạt chuẩn | Tiêu chí Chứng minh & Kiến trúc (Trụ cột 1 & 2) | Tiêu chí Thực nghiệm & Hệ thống (Lab 12) |
|---|---|---|
Principal / MSc Distinction (>= 85%) |
Chứng minh trọn vẹn đường cơ sở không chệch, GAE, PPO clip, bức tường 16 B/param, NF4+DQ, phân rã DoRA, dẫn xuất đóng DPO triệt tiêu \(Z(x)\), và tính không âm–không chệch của Schulman k3 KL; thiết kế đúng kiến trúc tách Rollout–Learner cho GRPO + RLVR |
Đạt 16/16 pytest (0 skips, 0 lỗi ruff/mypy), merge LoRA/DoRA < 1e-5, NF4 thắng INT4, Pre-Train giảm > 10× PPL, Prompt-Masked SFT thắng Unmasked, DPO đạt 100%, GRPO tăng >= +15pp với k3 KL bị chặn, safetensors == 0.0 và xuất chuẩn artifacts/ch21_lab12_results.json |
Senior / Đạt chuẩn (70% – 84%) |
Nắm vững cơ chế PPO, LoRA/QLoRA/DoRA, DPO, Constitutional AI và GRPO, nhưng còn thiếu chứng minh đại số k3 không chệch hoặc phân tích Likelihood Displacement / nhóm đồng nhất \(\sigma_G = 0\) |
Chạy thông suốt run_lab_demo.py và qua đa số kiểm thử, nhưng chưa kiểm chứng đủ đối chứng Che vs Không che prompt hoặc thiếu bước gộp adapter / safetensors |
Cần khắc phục (< 70%) |
Nhầm lẫn DPO vẫn cần Reward Model, tưởng GRPO cần mạng Critic như PPO, tính sai ngân sách 16 B/param của AdamW, hoặc dùng ước lượng KL âm |
Quên che prompt gây tụt chất lượng SFT, để chia 0 trên nhóm GRPO đồng nhất, dùng pickle lưu trọng số, hoặc thất bại bộ pytest Lab 12 |
70B Llama-3 Fine-Tuning VRAM Budget (GB, Lower is Better)
7B Post-Training Static VRAM: RLHF-PPO vs DPO vs GRPO+RLVR (GB)
Tiny LLM Verifiable Arithmetic Accuracy Across Stages (%)
Stage 2 SFT Response NLL: Prompt-Masked vs Unmasked (Lower is Better)
PEFT Memory Wall Accounting: 7B vs 70B (r=16, seq=2048, Grad Ckpt)
| Model & Method | Static VRAM (GB) | Total VRAM (GB) | Trainable Params & Fit |
|---|---|---|---|
| 7B Full FT (AdamW) | 112.0 | 113.1 | 100.0% (OOM 1x 80GB) |
| 7B QLoRA (NF4 + DQ) | 4.3 | 5.4 | 0.57% (Fits 1x 16GB) |
| 70B Full FT (AdamW) | 1120.0 | 1123.6 | 100.0% (Needs 16x 80GB) |
| 70B LoRA / DoRA (bf16) | 143.6 / 143.8 | 147.2 / 147.4 | 0.32% / 0.34% |
| 70B QLoRA (NF4 + DQ) | 39.7 | 43.3 | 0.32% (Fits 1x 80GB!) |
4-Stage Tiny LLM From Scratch Lifecycle Results (PyTorch CPU)
| Lifecycle Stage | Primary Metric (Before -> After) | Key Regularizer / Guard | Verdict |
|---|---|---|---|
| Stage 1: Pre-Training (CLM) | Eval PPL 31.11 -> 2.69 | 11.6x perplexity cut | PASS |
| Stage 2: SFT (LoRA / DoRA) | Resp NLL 0.424 -> 0.027 | Masked (0.034) < Unmasked (0.117) | PASS |
| Stage 3: DPO + CAI | Pref Acc 50.0% -> 100.0% | Margin +9.40, k3 KL=0.0003 | PASS |
| Stage 4: GRPO + RLVR (G=8) | Verif Acc 40.6% -> 71.9% | Lift +31.2pp, k3 KL=0.1104 | PASS |
Numerical & Algorithmic Invariants: PPO, LoRA/DoRA Merge, NF4 & Safetensors
| Invariant Audit | Measured Value | Requirement | Status |
|---|---|---|---|
| PPO + GAE MDP Return Gain | 1.31 -> 5.65 (opt 6.00) | Return gain > +2.0 | PASS |
| LoRA / DoRA Zero-Latency Merge | 1.07e-06 / 0.00e+00 | < 1e-5 exact parity | EXACT PASS |
| QLoRA NF4 vs Uniform INT4 SNR | 20.69 dB vs 19.35 dB (+1.34 dB) | NF4 SNR > Uniform INT4 | PASS |
| Safetensors Round-Trip Parity | 0.0e+00 (DPO merge 4.29e-06) | == 0.0 (zero pickle) | EXACT PASS |
2026 Post-Training Alignment & Reasoning Method Trade-Offs
| Method | Models in VRAM | Reward Signal | Best Production Regime |
|---|---|---|---|
| RLHF-PPO | 4 (Actor, Critic, Ref, RM) | Learned Bradley-Terry RM | Open-ended chat with online exploration |
| DPO / SimPO | 2 (Policy, Ref) / 1 (Ref-free) | Offline preference pairs (y_w, y_l) | Fast style/safety alignment & CAI RLAIF |
| GRPO + RLVR | 2 (Policy, Ref) + CPU Verifier | Deterministic verifiable reward r_i | Math, code, logic & structured reasoning |
| Constitutional AI | Generator + Critic/Reviser | Explicit constitutional principles | Scalable low-cost safety & RLAIF pairs |
02-track-1-data-science-and-ai/part-04-nlp-llm-post-training-and-safety/labs/lab-12-llm-from-scratch-pretrain-sft-posttrain
[build-system]
requires = ["setuptools>=68.0"]
build-backend = "setuptools.build_meta"
[project]
name = "llm-from-scratch-lab"
version = "0.1.0"
description = "Lab 12: End-to-End LLM From Scratch (Pre-Train -> SFT with LoRA/DoRA -> DPO/CAI -> GRPO+RLVR) & RL/PEFT Foundations (T1-P4-U04)."
readme = "README.md"
requires-python = ">=3.12"
dependencies = [
"numpy>=1.26",
"pydantic>=2.0",
"safetensors>=0.4",
"scipy>=1.11",
"torch>=2.5",
]
[project.optional-dependencies]
dev = [
"mypy>=1.11",
"pytest>=8.0",
"ruff>=0.6",
]
[[tool.uv.index]]
name = "pytorch-cpu"
url = "https://download.pytorch.org/whl/cpu"
explicit = true
[tool.uv.sources]
torch = { index = "pytorch-cpu" }
[tool.setuptools]
package-dir = {"" = "src"}
[tool.setuptools.packages.find]
where = ["src"]
[tool.pytest.ini_options]
pythonpath = ["src"]
testpaths = ["tests"]
addopts = "-v"
[tool.ruff]
line-length = 110
target-version = "py312"
[tool.ruff.lint]
select = ["E", "F", "I", "UP", "B"]
[tool.mypy]
python_version = "3.12"
ignore_missing_imports = true
warn_unused_ignores = true
"""Lab 12: RL Foundations, PEFT (LoRA/QLoRA/DoRA) & 4-Stage LLM From Scratch Lifecycle."""
from llm_from_scratch_lab.rl_and_peft import (
DoRALinear,
LoRALinear,
PEFTMemoryConfig,
PostTrainingConfig,
PPOConfig,
TinyLLMConfig,
audit_lora_and_dora_merge_parity,
audit_nf4_quantization_roundtrip,
compute_gae_advantages,
compute_peft_vram_budget,
compute_post_training_vram_comparison,
nf4_dequantize_blockwise,
nf4_quantize_blockwise,
ppo_clipped_surrogate_loss,
run_ppo_policy_benchmark,
schulman_k3_kl,
schulman_k3_kl_numpy,
)
from llm_from_scratch_lab.tiny_llm_lifecycle import (
ArithmeticVocab,
ConstitutionalPrinciple,
TinyModernDecoderLM,
align_with_dpo,
build_arithmetic_splits,
compute_dpo_loss,
compute_group_relative_advantages,
generate_constitutional_pairs,
inject_peft_adapters,
load_safetensors_checkpoint,
posttrain_with_grpo_rlvr,
pretrain_tiny_llm,
run_full_ch21_lab12_benchmarks,
save_safetensors_checkpoint,
sft_with_peft,
verify_arithmetic_completion,
)
__all__ = [
"ArithmeticVocab",
"ConstitutionalPrinciple",
"DoRALinear",
"LoRALinear",
"PEFTMemoryConfig",
"PPOConfig",
"PostTrainingConfig",
"TinyLLMConfig",
"TinyModernDecoderLM",
"align_with_dpo",
"audit_lora_and_dora_merge_parity",
"audit_nf4_quantization_roundtrip",
"build_arithmetic_splits",
"compute_dpo_loss",
"compute_gae_advantages",
"compute_group_relative_advantages",
"compute_peft_vram_budget",
"compute_post_training_vram_comparison",
"generate_constitutional_pairs",
"inject_peft_adapters",
"load_safetensors_checkpoint",
"nf4_dequantize_blockwise",
"nf4_quantize_blockwise",
"posttrain_with_grpo_rlvr",
"ppo_clipped_surrogate_loss",
"pretrain_tiny_llm",
"run_full_ch21_lab12_benchmarks",
"run_ppo_policy_benchmark",
"save_safetensors_checkpoint",
"schulman_k3_kl",
"schulman_k3_kl_numpy",
"sft_with_peft",
"verify_arithmetic_completion",
]
"""Tier 1 + Tier 2 RL Foundations (GAE, PPO, Schulman k3 KL) & PEFT (LoRA, DoRA, QLoRA NF4)."""
from __future__ import annotations
import math
from typing import Any
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from pydantic import BaseModel, ConfigDict, Field, model_validator
# Exact 16-level NF4 (4-bit NormalFloat) quantile codebook from Dettmers et al. (NeurIPS 2023)
NF4_CODEBOOK: np.ndarray = np.array(
[
-1.0,
-0.6961928009986877,
-0.5250730514526367,
-0.39491748809814453,
-0.28444138169288635,
-0.18477343022823334,
-0.09105003625154495,
0.0,
0.07958029955625534,
0.16093020141124725,
0.24611230194568634,
0.33791524171829224,
0.44070982933044434,
0.5626170039176941,
0.7229568362236023,
1.0,
],
dtype=np.float32,
)
class PPOConfig(BaseModel):
"""Strict configuration for GAE & PPO clipped policy optimization."""
model_config = ConfigDict(extra="forbid")
gamma: float = Field(default=0.99, ge=0.0, le=1.0)
lam: float = Field(default=0.95, ge=0.0, le=1.0)
clip_eps: float = Field(default=0.2, gt=0.0, lt=1.0)
kl_beta: float = Field(default=0.04, ge=0.0)
lr: float = Field(default=0.05, gt=0.0)
class PEFTMemoryConfig(BaseModel):
"""Strict configuration for Full FT vs LoRA vs QLoRA vs DoRA VRAM accounting."""
model_config = ConfigDict(extra="forbid")
model_name: str = Field(default="70B Llama-3")
total_params_b: float = Field(default=70.0, gt=0.0)
n_layers: int = Field(default=80, ge=1)
d_model: int = Field(default=8192, ge=64)
d_ff: int = Field(default=28672, ge=64)
lora_rank: int = Field(default=16, ge=1, le=256)
target_modules: int = Field(default=7, ge=1, le=12)
batch_size: int = Field(default=1, ge=1)
seq_len: int = Field(default=2048, ge=128)
grad_checkpointing: bool = Field(default=True)
block_size_nf4: int = Field(default=64, ge=16)
class TinyLLMConfig(BaseModel):
"""Strict configuration for our real CPU-friendly Modern Decoder-Only Tiny LLM (~42K params)."""
model_config = ConfigDict(extra="forbid")
vocab_size: int = Field(default=30, ge=8)
d_model: int = Field(default=40, ge=16)
n_layers: int = Field(default=2, ge=1, le=8)
n_heads: int = Field(default=4, ge=1)
d_ff: int = Field(default=112, ge=16)
max_seq_len: int = Field(default=32, ge=8)
rope_theta: float = Field(default=10000.0, gt=0.0)
@model_validator(mode="after")
def _validate_heads(self) -> TinyLLMConfig:
if self.d_model % self.n_heads != 0:
raise ValueError("d_model must be divisible by n_heads")
if (self.d_model // self.n_heads) % 2 != 0:
raise ValueError("d_head must be even for RoPE")
return self
class PostTrainingConfig(BaseModel):
"""Strict configuration for 4-stage Pre-Train -> SFT -> DPO -> GRPO+RLVR lifecycle."""
model_config = ConfigDict(extra="forbid")
seed: int = Field(default=42, ge=0)
pretrain_steps: int = Field(default=110, ge=10)
sft_steps: int = Field(default=45, ge=5)
dpo_steps: int = Field(default=35, ge=5)
dpo_beta: float = Field(default=0.25, gt=0.0)
grpo_steps: int = Field(default=35, ge=5)
grpo_group_size: int = Field(default=8, ge=2)
grpo_clip_eps: float = Field(default=0.2, gt=0.0, lt=1.0)
grpo_kl_beta: float = Field(default=0.03, ge=0.0)
lora_rank: int = Field(default=8, ge=1)
lora_alpha: float = Field(default=16.0, gt=0.0)
def compute_gae_advantages(
rewards: np.ndarray,
values: np.ndarray,
dones: np.ndarray,
gamma: float = 0.99,
lam: float = 0.95,
next_value: float = 0.0,
) -> tuple[np.ndarray, np.ndarray]:
"""Compute exact Generalized Advantage Estimation (GAE) and bootstrapped returns.
Parameters
----------
rewards : np.ndarray
Reward sequence of shape ``(T,)``.
values : np.ndarray
State value estimates ``V(s_t)`` of shape ``(T,)``.
dones : np.ndarray
Episode termination flags (1.0 if terminal after step t else 0.0) of shape ``(T,)``.
gamma : float
Discount factor in ``[0, 1]``.
lam : float
GAE bias-variance smoothing parameter in ``[0, 1]``.
next_value : float
Bootstrap value ``V(s_T)`` when the final transition is non-terminal.
Returns
-------
tuple[np.ndarray, np.ndarray]
``(advantages, returns)`` as ``float64`` arrays of shape ``(T,)``.
"""
r = np.asarray(rewards, dtype=np.float64)
v = np.asarray(values, dtype=np.float64)
d = np.asarray(dones, dtype=np.float64)
if not (r.shape == v.shape == d.shape and r.ndim == 1):
raise ValueError("rewards, values, and dones must be 1D arrays of equal length")
t_len = r.shape[0]
advantages = np.zeros(t_len, dtype=np.float64)
running_gae = 0.0
for t in range(t_len - 1, -1, -1):
non_terminal = 1.0 - d[t]
v_next = next_value if t == t_len - 1 else v[t + 1]
delta = r[t] + gamma * v_next * non_terminal - v[t]
running_gae = delta + gamma * lam * non_terminal * running_gae
advantages[t] = running_gae
returns = advantages + v
return advantages, returns
def schulman_k3_kl_numpy(logp_policy: np.ndarray, logp_ref: np.ndarray) -> np.ndarray:
"""Non-negative, unbiased Schulman k3 KL estimator: exp(log_r) - log_r - 1 >= 0.
Here ``log_r = log(pi_ref / pi_theta) = logp_ref - logp_policy``.
"""
log_r = np.asarray(logp_ref, dtype=np.float64) - np.asarray(logp_policy, dtype=np.float64)
log_r_clamped = np.clip(log_r, -30.0, 30.0)
k3 = np.expm1(log_r_clamped) - log_r_clamped
return np.maximum(k3, 0.0)
def schulman_k3_kl(logp_policy: torch.Tensor, logp_ref: torch.Tensor) -> torch.Tensor:
"""PyTorch differentiable Schulman k3 KL estimator: (pi_ref/pi_theta) - log(pi_ref/pi_theta) - 1 >= 0."""
log_r = (logp_ref - logp_policy).clamp(min=-20.0, max=20.0)
k3 = torch.expm1(log_r) - log_r
return torch.clamp(k3, min=0.0)
def ppo_clipped_surrogate_loss(
new_logp: torch.Tensor,
old_logp: torch.Tensor,
advantages: torch.Tensor,
clip_eps: float = 0.2,
) -> tuple[torch.Tensor, dict[str, float]]:
"""Compute pessimistic PPO clipped surrogate loss (to minimize) and clipping diagnostics."""
log_ratio = (new_logp - old_logp).clamp(min=-20.0, max=20.0)
ratio = torch.exp(log_ratio)
clipped_ratio = torch.clamp(ratio, 1.0 - clip_eps, 1.0 + clip_eps)
surr1 = ratio * advantages
surr2 = clipped_ratio * advantages
objective = torch.minimum(surr1, surr2).mean()
clip_fraction = float(((ratio - 1.0).abs() > clip_eps).float().mean().item())
mean_ratio = float(ratio.mean().item())
return -objective, {"clip_fraction": clip_fraction, "mean_ratio": mean_ratio}
def run_ppo_policy_benchmark(seed: int = 42, cfg: PPOConfig | None = None) -> dict[str, Any]:
"""Verify GAE + PPO clipped surrogate + Schulman k3 KL on a deterministic multi-step MDP."""
ppo_cfg = cfg or PPOConfig()
torch.manual_seed(seed)
np.random.seed(seed)
# 4-state, 4-action contextual sequential MDP with distinct optimal actions per state
n_states = 4
n_actions = 4
horizon = 6
reward_table = np.array(
[
[1.0, 0.2, -0.3, 0.0],
[0.0, 1.0, 0.1, -0.4],
[-0.2, 0.1, 1.0, 0.2],
[0.1, -0.3, 0.0, 1.0],
],
dtype=np.float64,
)
policy_logits = nn.Parameter(torch.zeros((n_states, n_actions), dtype=torch.float32))
ref_logits = torch.zeros((n_states, n_actions), dtype=torch.float32)
value_table = nn.Parameter(torch.zeros(n_states, dtype=torch.float32))
optimizer = torch.optim.Adam([policy_logits, value_table], lr=ppo_cfg.lr)
def eval_expected_return() -> float:
with torch.no_grad():
probs = torch.softmax(policy_logits, dim=-1).numpy()
per_step = float(np.mean(np.sum(probs * reward_table, axis=-1)))
return per_step * horizon
initial_return = eval_expected_return()
rng = np.random.default_rng(seed)
last_clip_frac = 0.0
last_kl_k3 = 0.0
history: list[dict[str, float]] = []
for step in range(40):
# Collect batch of trajectories from current policy
with torch.no_grad():
old_probs = torch.softmax(policy_logits, dim=-1).numpy()
old_log_probs_all = torch.log_softmax(policy_logits, dim=-1).detach()
ref_log_probs_all = torch.log_softmax(ref_logits, dim=-1).detach()
v_est = value_table.detach().numpy()
states_buf: list[int] = []
actions_buf: list[int] = []
old_logp_buf: list[float] = []
ref_logp_buf: list[float] = []
adv_buf: list[float] = []
ret_buf: list[float] = []
for _ep in range(24):
ep_states = rng.integers(0, n_states, size=horizon)
ep_actions = np.array(
[rng.choice(n_actions, p=old_probs[s]) for s in ep_states], dtype=np.int64
)
ep_rewards = np.array(
[reward_table[s, a] for s, a in zip(ep_states, ep_actions, strict=True)],
dtype=np.float64,
)
ep_values = np.array([v_est[s] for s in ep_states], dtype=np.float64)
ep_dones = np.zeros(horizon, dtype=np.float64)
ep_dones[-1] = 1.0
adv, ret = compute_gae_advantages(
ep_rewards, ep_values, ep_dones, gamma=ppo_cfg.gamma, lam=ppo_cfg.lam
)
for t in range(horizon):
s_t = int(ep_states[t])
a_t = int(ep_actions[t])
states_buf.append(s_t)
actions_buf.append(a_t)
old_logp_buf.append(float(old_log_probs_all[s_t, a_t].item()))
ref_logp_buf.append(float(ref_log_probs_all[s_t, a_t].item()))
adv_buf.append(float(adv[t]))
ret_buf.append(float(ret[t]))
s_t_ten = torch.tensor(states_buf, dtype=torch.long)
a_t_ten = torch.tensor(actions_buf, dtype=torch.long)
old_logp_ten = torch.tensor(old_logp_buf, dtype=torch.float32)
ref_logp_ten = torch.tensor(ref_logp_buf, dtype=torch.float32)
adv_ten = torch.tensor(adv_buf, dtype=torch.float32)
adv_ten = (adv_ten - adv_ten.mean()) / (adv_ten.std(unbiased=False) + 1e-8)
ret_ten = torch.tensor(ret_buf, dtype=torch.float32)
for _epoch in range(3):
log_probs_all = torch.log_softmax(policy_logits, dim=-1)
new_logp = log_probs_all[s_t_ten, a_t_ten]
ppo_loss, diag = ppo_clipped_surrogate_loss(
new_logp, old_logp_ten, adv_ten, clip_eps=ppo_cfg.clip_eps
)
kl_k3 = schulman_k3_kl(new_logp, ref_logp_ten).mean()
value_loss = F.mse_loss(value_table[s_t_ten], ret_ten)
total_loss = ppo_loss + ppo_cfg.kl_beta * kl_k3 + 0.5 * value_loss
optimizer.zero_grad()
total_loss.backward()
optimizer.step()
last_clip_frac = diag["clip_fraction"]
last_kl_k3 = float(kl_k3.item())
if step in {0, 9, 19, 39}:
history.append(
{
"step": float(step + 1),
"expected_return": eval_expected_return(),
"kl_k3": last_kl_k3,
"clip_fraction": last_clip_frac,
}
)
final_return = eval_expected_return()
optimal_return = float(np.mean(np.max(reward_table, axis=-1)) * horizon)
return {
"initial_expected_return": initial_return,
"final_expected_return": final_return,
"optimal_return": optimal_return,
"return_gain": final_return - initial_return,
"final_kl_k3": last_kl_k3,
"last_clip_fraction": last_clip_frac,
"history": history,
}
class LoRALinear(nn.Module):
"""Low-Rank Adaptation layer: W = W_0 + (alpha / r) * B @ A with zero-init B & exact merge."""
def __init__(self, base_linear: nn.Linear, rank: int = 8, alpha: float = 16.0) -> None:
super().__init__()
if rank <= 0:
raise ValueError("rank must be positive")
self.in_features = base_linear.in_features
self.out_features = base_linear.out_features
self.rank = rank
self.alpha = float(alpha)
self.scaling = self.alpha / float(rank)
self.base = nn.Linear(
self.in_features, self.out_features, bias=base_linear.bias is not None
)
self.base.weight.data.copy_(base_linear.weight.data)
self.base.weight.requires_grad_(False)
if base_linear.bias is not None and self.base.bias is not None:
self.base.bias.data.copy_(base_linear.bias.data)
self.base.bias.requires_grad_(False)
self.lora_a = nn.Parameter(torch.empty((rank, self.in_features), dtype=base_linear.weight.dtype))
self.lora_b = nn.Parameter(torch.zeros((self.out_features, rank), dtype=base_linear.weight.dtype))
nn.init.kaiming_uniform_(self.lora_a, a=math.sqrt(5.0))
def forward(self, x: torch.Tensor) -> torch.Tensor:
base_out = self.base(x)
delta = F.linear(F.linear(x, self.lora_a), self.lora_b) * self.scaling
return base_out + delta
@torch.no_grad()
def merge_to_linear(self) -> nn.Linear:
"""Fold LoRA delta into a single dense nn.Linear with zero inference latency overhead."""
merged = nn.Linear(
self.in_features, self.out_features, bias=self.base.bias is not None
)
delta_w = (self.lora_b @ self.lora_a) * self.scaling
merged.weight.data.copy_(self.base.weight.data + delta_w)
if self.base.bias is not None and merged.bias is not None:
merged.bias.data.copy_(self.base.bias.data)
return merged
class DoRALinear(nn.Module):
"""Weight-Decomposed Low-Rank Adaptation (ICML 2024 Oral): W' = m * (W_0 + s*B@A) / ||W_0 + s*B@A||_c."""
def __init__(self, base_linear: nn.Linear, rank: int = 8, alpha: float = 16.0) -> None:
super().__init__()
if rank <= 0:
raise ValueError("rank must be positive")
self.in_features = base_linear.in_features
self.out_features = base_linear.out_features
self.rank = rank
self.alpha = float(alpha)
self.scaling = self.alpha / float(rank)
self.base = nn.Linear(
self.in_features, self.out_features, bias=base_linear.bias is not None
)
self.base.weight.data.copy_(base_linear.weight.data)
self.base.weight.requires_grad_(False)
if base_linear.bias is not None and self.base.bias is not None:
self.base.bias.data.copy_(base_linear.bias.data)
self.base.bias.requires_grad_(False)
self.lora_a = nn.Parameter(torch.empty((rank, self.in_features), dtype=base_linear.weight.dtype))
self.lora_b = nn.Parameter(torch.zeros((self.out_features, rank), dtype=base_linear.weight.dtype))
nn.init.kaiming_uniform_(self.lora_a, a=math.sqrt(5.0))
# Per-output-channel learnable magnitude vector m initialized to ||W_0||_2 per row
init_mag = self.base.weight.data.norm(p=2, dim=1)
self.magnitude = nn.Parameter(init_mag.clone())
def effective_weight(self) -> torch.Tensor:
"""Compute magnitude-direction decomposed effective weight matrix W'."""
directional = self.base.weight + (self.lora_b @ self.lora_a) * self.scaling
row_norm = directional.norm(p=2, dim=1, keepdim=True).clamp_min(1e-8)
return (self.magnitude.unsqueeze(1) / row_norm) * directional
def forward(self, x: torch.Tensor) -> torch.Tensor:
return F.linear(x, self.effective_weight(), self.base.bias)
@torch.no_grad()
def merge_to_linear(self) -> nn.Linear:
"""Merge magnitude & directional updates into a single zero-overhead nn.Linear."""
merged = nn.Linear(
self.in_features, self.out_features, bias=self.base.bias is not None
)
merged.weight.data.copy_(self.effective_weight())
if self.base.bias is not None and merged.bias is not None:
merged.bias.data.copy_(self.base.bias.data)
return merged
def audit_lora_and_dora_merge_parity(
in_features: int = 128,
out_features: int = 128,
rank: int = 8,
alpha: float = 16.0,
seed: int = 42,
) -> dict[str, Any]:
"""Verify zero-init identity, exact merge parity (<1e-5), and trainable parameter ratios."""
torch.manual_seed(seed)
base = nn.Linear(in_features, out_features, bias=True)
x = torch.randn(16, in_features)
lora = LoRALinear(base, rank=rank, alpha=alpha)
dora = DoRALinear(base, rank=rank, alpha=alpha)
with torch.no_grad():
y_base = base(x)
lora_zero_init_diff = float((lora(x) - y_base).abs().max().item())
dora_zero_init_diff = float((dora(x) - y_base).abs().max().item())
# Populate non-zero adapter weights and magnitude shift
lora.lora_b.normal_(mean=0.0, std=0.05)
dora.lora_b.normal_(mean=0.0, std=0.05)
dora.magnitude.mul_(1.0 + 0.05 * torch.randn_like(dora.magnitude))
lora_merge_diff = float((lora(x) - lora.merge_to_linear()(x)).abs().max().item())
dora_merge_diff = float((dora(x) - dora.merge_to_linear()(x)).abs().max().item())
base_params = sum(p.numel() for p in base.parameters())
lora_trainable = sum(p.numel() for p in lora.parameters() if p.requires_grad)
dora_trainable = sum(p.numel() for p in dora.parameters() if p.requires_grad)
return {
"in_features": in_features,
"out_features": out_features,
"rank": rank,
"base_params": base_params,
"lora_trainable_params": lora_trainable,
"dora_trainable_params": dora_trainable,
"lora_trainable_ratio": lora_trainable / float(base_params),
"dora_trainable_ratio": dora_trainable / float(base_params),
"dora_extra_magnitude_params": out_features,
"lora_zero_init_diff": lora_zero_init_diff,
"dora_zero_init_diff": dora_zero_init_diff,
"lora_merge_max_diff": lora_merge_diff,
"dora_merge_max_diff": dora_merge_diff,
}
def nf4_quantize_blockwise(
weight: np.ndarray, block_size: int = 64
) -> tuple[np.ndarray, np.ndarray, tuple[int, ...]]:
"""Quantize float weights to 4-bit NF4 indices using blockwise absmax scaling."""
arr = np.asarray(weight, dtype=np.float32)
orig_shape = arr.shape
flat = arr.reshape(-1)
pad_len = (-flat.size) % block_size
if pad_len > 0:
flat = np.pad(flat, (0, pad_len), mode="constant")
blocks = flat.reshape(-1, block_size)
absmax = np.max(np.abs(blocks), axis=1).astype(np.float32)
safe_absmax = np.where(absmax == 0.0, 1.0, absmax)
normed = blocks / safe_absmax[:, None]
# Map each normalized value in [-1, 1] to nearest NF4 quantile index (0..15)
diffs = np.abs(normed[:, :, None] - NF4_CODEBOOK[None, None, :])
q_idx = np.argmin(diffs, axis=-1).astype(np.uint8)
return q_idx, absmax, orig_shape
def nf4_dequantize_blockwise(
q_idx: np.ndarray, absmax: np.ndarray, orig_shape: tuple[int, ...], block_size: int = 64
) -> np.ndarray:
"""Dequantize 4-bit NF4 blockwise indices back to float32 tensor."""
if q_idx.shape[1] != block_size:
raise ValueError("q_idx second dimension must match block_size")
deq_blocks = NF4_CODEBOOK[q_idx] * absmax[:, None]
total_elems = int(math.prod(orig_shape))
return deq_blocks.reshape(-1)[:total_elems].reshape(orig_shape).astype(np.float32)
def audit_nf4_quantization_roundtrip(
shape: tuple[int, int] = (256, 256), block_size: int = 64, seed: int = 42
) -> dict[str, Any]:
"""Benchmark NF4 4-bit quantization fidelity vs naive uniform INT4 on Gaussian LLM weights."""
rng = np.random.default_rng(seed)
w = (rng.standard_normal(shape) * 0.02).astype(np.float32)
q_idx, absmax, orig_shape = nf4_quantize_blockwise(w, block_size=block_size)
w_nf4 = nf4_dequantize_blockwise(q_idx, absmax, orig_shape, block_size=block_size)
# Uniform 4-bit baseline for quantitative contrast
flat = w.reshape(-1)
blocks = flat.reshape(-1, block_size)
b_max = np.maximum(np.max(np.abs(blocks), axis=1, keepdims=True), 1e-12)
q_unif = np.round(np.clip(blocks / b_max, -1.0, 1.0) * 7.0) / 7.0
w_unif = (q_unif * b_max).reshape(shape)
nf4_rmse = float(np.sqrt(np.mean((w - w_nf4) ** 2)))
unif_rmse = float(np.sqrt(np.mean((w - w_unif) ** 2)))
sig_power = float(np.mean(w**2))
nf4_snr_db = float(10.0 * math.log10(sig_power / max(nf4_rmse**2, 1e-16)))
unif_snr_db = float(10.0 * math.log10(sig_power / max(unif_rmse**2, 1e-16)))
# Effective bits per parameter: NF4 (4 bits) + Double Quant overhead (8/B + 32/(B*256))
dq_overhead_bits = (8.0 / block_size) + (32.0 / (block_size * 256.0))
eff_bits_per_param = 4.0 + dq_overhead_bits
bf16_compression = 16.0 / eff_bits_per_param
fp32_compression = 32.0 / eff_bits_per_param
return {
"shape": list(shape),
"block_size": block_size,
"nf4_rmse": nf4_rmse,
"uniform_int4_rmse": unif_rmse,
"nf4_snr_db": nf4_snr_db,
"uniform_int4_snr_db": unif_snr_db,
"snr_gain_db": nf4_snr_db - unif_snr_db,
"effective_bits_per_param_dq": eff_bits_per_param,
"compression_vs_bf16": bf16_compression,
"compression_vs_fp32": fp32_compression,
}
def compute_peft_vram_budget(cfg: PEFTMemoryConfig) -> dict[str, Any]:
"""Compute exact static + activation VRAM budgets (GB) for Full FT, LoRA, QLoRA, and DoRA."""
total_params = cfg.total_params_b * 1e9
gb = 1e9 # Decimal GB matching GPU spec sheets & Ch 19 convention
# Adapter params per layer: 4 attention projections (d x d) + 3 SwiGLU projections (d x d_ff)
attn_projs = min(4, cfg.target_modules)
ffn_projs = max(0, cfg.target_modules - 4)
per_layer_lora = attn_projs * (2 * cfg.lora_rank * cfg.d_model) + ffn_projs * (
cfg.lora_rank * (cfg.d_model + cfg.d_ff)
)
lora_params = float(cfg.n_layers * per_layer_lora)
dora_extra_mag_params = float(
cfg.n_layers * (attn_projs * cfg.d_model + ffn_projs * cfg.d_ff)
)
dora_params = lora_params + dora_extra_mag_params
# Activation memory estimate (bf16 = 2 bytes, reduced by sqrt(L) under gradient checkpointing)
act_factor = math.sqrt(cfg.n_layers) if cfg.grad_checkpointing else float(cfg.n_layers)
activation_gb = (
cfg.batch_size * cfg.seq_len * cfg.d_model * 12.0 * 2.0 * act_factor / gb
)
# Full FT AdamW mixed precision: 2B weight + 2B grad + 4B fp32 master + 8B Adam m,v = 16 B/param
full_static_gb = (16.0 * total_params) / gb
full_total_gb = full_static_gb + activation_gb
# LoRA bf16: 2B frozen base + 16B trainable adapter (bf16 weight/grad + fp32 master + Adam m,v)
lora_base_gb = (2.0 * total_params) / gb
lora_opt_gb = (16.0 * lora_params) / gb
lora_total_gb = lora_base_gb + lora_opt_gb + activation_gb
# DoRA bf16: same frozen base + 16B on (lora + magnitude vector)
dora_opt_gb = (16.0 * dora_params) / gb
dora_total_gb = lora_base_gb + dora_opt_gb + activation_gb
# QLoRA NF4 + Double Quantization: (4 + 8/B + 32/(256*B)) / 8 bytes per base param
eff_bytes_nf4 = (4.0 + 8.0 / cfg.block_size_nf4 + 32.0 / (256.0 * cfg.block_size_nf4)) / 8.0
qlora_base_gb = (eff_bytes_nf4 * total_params) / gb
qlora_total_gb = qlora_base_gb + lora_opt_gb + activation_gb
return {
"model_name": cfg.model_name,
"total_params_b": cfg.total_params_b,
"lora_rank": cfg.lora_rank,
"trainable_pct_lora": 100.0 * lora_params / total_params,
"trainable_pct_dora": 100.0 * dora_params / total_params,
"activation_gb": activation_gb,
"full_ft_static_gb": full_static_gb,
"full_ft_total_gb": full_total_gb,
"lora_bf16_static_gb": lora_base_gb + lora_opt_gb,
"lora_bf16_total_gb": lora_total_gb,
"dora_bf16_static_gb": lora_base_gb + dora_opt_gb,
"dora_bf16_total_gb": dora_total_gb,
"qlora_nf4_static_gb": qlora_base_gb + lora_opt_gb,
"qlora_nf4_total_gb": qlora_total_gb,
"qlora_vs_full_ft_reduction_x": full_total_gb / qlora_total_gb,
"fits_single_80gb_gpu_qlora": qlora_total_gb <= 80.0,
"fits_single_80gb_gpu_full_ft": full_total_gb <= 80.0,
}
def compute_post_training_vram_comparison(total_params_b: float = 7.0) -> dict[str, Any]:
"""Compare static VRAM footprints (GB) of RLHF-PPO (4 models) vs DPO (2) vs GRPO+RLVR (2)."""
params = total_params_b * 1e9
gb = 1e9
# Full-param training states:
# Trainable model (Actor or Critic): 16 B/param (bf16 w/g + fp32 master + Adam m/v)
# Frozen inference model (Ref or Reward Model): 2 B/param (bf16 weights only)
actor_gb = (16.0 * params) / gb
critic_gb = (16.0 * params) / gb
ref_gb = (2.0 * params) / gb
rm_gb = (2.0 * params) / gb
rlhf_ppo_gb = actor_gb + critic_gb + ref_gb + rm_gb # 36 B/param
dpo_gb = actor_gb + ref_gb # 18 B/param
grpo_rlvr_gb = actor_gb + ref_gb # 18 B/param (critic-free + programmatic CPU verifier!)
simpo_gb = actor_gb # 16 B/param (reference-free)
return {
"total_params_b": total_params_b,
"rlhf_ppo_4_models_gb": rlhf_ppo_gb,
"dpo_2_models_gb": dpo_gb,
"grpo_rlvr_2_models_gb": grpo_rlvr_gb,
"simpo_1_model_gb": simpo_gb,
"grpo_vs_ppo_vram_saving_pct": 100.0 * (1.0 - grpo_rlvr_gb / rlhf_ppo_gb),
}
"""End-to-End 4-Stage Tiny Modern Decoder-Only LLM From Scratch (Pre-Train -> SFT -> DPO/CAI -> GRPO+RLVR)."""
from __future__ import annotations
import copy
import math
import tempfile
from dataclasses import dataclass
from pathlib import Path
from typing import Any
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from safetensors.torch import load_file as safetensors_load_file
from safetensors.torch import save_file as safetensors_save_file
from llm_from_scratch_lab.rl_and_peft import (
DoRALinear,
LoRALinear,
PEFTMemoryConfig,
TinyLLMConfig,
audit_lora_and_dora_merge_parity,
audit_nf4_quantization_roundtrip,
compute_peft_vram_budget,
compute_post_training_vram_comparison,
ppo_clipped_surrogate_loss,
run_ppo_policy_benchmark,
schulman_k3_kl,
)
class ArithmeticVocab:
"""Compact deterministic vocabulary for verifiable arithmetic + alignment post-training."""
TOKENS: tuple[str, ...] = (
"<PAD>",
"<BOS>",
"<EOS>",
"0",
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"ADD",
"SUB",
"=>",
"ANS:",
"OK",
"ERR",
"UMM",
"VERBOSE",
"UNSAFE",
"SAFE",
"REFUSE",
"CHECK",
"DONE",
"SYS",
"USER",
"TASK",
"MATH",
)
def __init__(self) -> None:
self.token_to_id: dict[str, int] = {tok: idx for idx, tok in enumerate(self.TOKENS)}
self.id_to_token: dict[int, str] = {idx: tok for idx, tok in enumerate(self.TOKENS)}
self.pad_id = self.token_to_id["<PAD>"]
self.bos_id = self.token_to_id["<BOS>"]
self.eos_id = self.token_to_id["<EOS>"]
@property
def size(self) -> int:
return len(self.TOKENS)
def encode(self, tokens: list[str]) -> list[int]:
return [self.token_to_id[t] for t in tokens]
def decode(self, ids: list[int]) -> list[str]:
return [self.id_to_token[i] for i in ids]
@dataclass(frozen=True)
class ArithmeticSample:
"""Single deterministic arithmetic problem with varied context prompt & canonical response."""
op: str
a: int
b: int
answer: int
prompt_tokens: list[str]
response_tokens: list[str]
@dataclass(frozen=True)
class ConstitutionalPrinciple:
"""Explicit Constitutional AI principle governing critique & revision."""
code: str
rule: str
forbidden_tokens: tuple[str, ...]
def build_arithmetic_splits(seed: int = 42) -> dict[str, list[ArithmeticSample]]:
"""Build deterministic leakage-free train/eval splits of verifiable arithmetic problems.
24 core verifiable operations (ADD/SUB with delta in {1, 2} on a in 2..7) each wrapped in
5 distinct high-entropy context header prefixes (120 unique prompts: 88 train / 32 eval).
"""
rng = np.random.default_rng(seed)
ctx_pool = ("SYS", "USER", "TASK", "MATH", "SAFE", "CHECK")
base_ops: list[tuple[str, int, int, int]] = []
for a in range(2, 8):
for b in (1, 2):
base_ops.append(("ADD", a, b, a + b))
base_ops.append(("SUB", a, b, a - b))
all_samples: list[ArithmeticSample] = []
for op, a, b, ans in base_ops:
d1, d0 = ans // 10, ans % 10
for _variant in range(5):
ctx = [str(x) for x in rng.choice(ctx_pool, size=3, replace=True)]
all_samples.append(
ArithmeticSample(
op=op,
a=a,
b=b,
answer=ans,
prompt_tokens=["<BOS>", *ctx, op, str(a), str(b), "=>"],
response_tokens=["ANS:", str(d1), str(d0), "OK", "<EOS>"],
)
)
perm = rng.permutation(len(all_samples))
shuffled = [all_samples[int(i)] for i in perm]
return {"train": shuffled[:88], "eval": shuffled[88:]}
def verify_arithmetic_completion(
prompt_tokens: list[str], completion_tokens: list[str]
) -> dict[str, Any]:
"""100% deterministic programmatic verifier (RLVR) for arithmetic & format correctness."""
arrow_idx = prompt_tokens.index("=>")
op = prompt_tokens[arrow_idx - 3]
a = int(prompt_tokens[arrow_idx - 2])
b = int(prompt_tokens[arrow_idx - 1])
expected = a + b if op == "ADD" else a - b
trimmed = list(completion_tokens)
has_eos = "<EOS>" in trimmed
if has_eos:
trimmed = trimmed[: trimmed.index("<EOS>")]
format_ok = (
len(trimmed) == 4
and trimmed[0] == "ANS:"
and trimmed[1].isdigit()
and trimmed[2].isdigit()
and trimmed[3] == "OK"
and has_eos
)
format_reward = 0.25 if format_ok else 0.0
exact_match = False
predicted: int | None = None
if len(trimmed) >= 3 and trimmed[0] == "ANS:" and trimmed[1].isdigit() and trimmed[2].isdigit():
predicted = int(trimmed[1]) * 10 + int(trimmed[2])
exact_match = predicted == expected
accuracy_reward = 0.75 if (exact_match and format_ok) else (0.35 if exact_match else 0.0)
total_reward = format_reward + accuracy_reward
return {
"expected": expected,
"predicted": predicted,
"format_ok": format_ok,
"exact_match": exact_match and format_ok,
"reward": float(total_reward),
}
class RMSNorm(nn.Module):
"""Root Mean Square Layer Normalization (no mean subtraction)."""
def __init__(self, d_model: int, eps: float = 1e-6) -> None:
super().__init__()
self.eps = eps
self.weight = nn.Parameter(torch.ones(d_model))
def forward(self, x: torch.Tensor) -> torch.Tensor:
rms = torch.rsqrt(x.pow(2).mean(dim=-1, keepdim=True) + self.eps)
return x * rms * self.weight
class RotaryPositionEmbedding(nn.Module):
"""Precomputed RoPE cos/sin cache for causal self-attention."""
def __init__(self, d_head: int, max_seq_len: int, theta: float = 10000.0) -> None:
super().__init__()
inv_freq = 1.0 / (theta ** (torch.arange(0, d_head, 2, dtype=torch.float32) / d_head))
positions = torch.arange(max_seq_len, dtype=torch.float32)
freqs = torch.outer(positions, inv_freq)
self.register_buffer("cos_cache", torch.cos(freqs), persistent=False)
self.register_buffer("sin_cache", torch.sin(freqs), persistent=False)
def apply_rope(self, x: torch.Tensor) -> torch.Tensor:
seq_len = x.shape[2]
cos_buf: torch.Tensor = self.cos_cache # type: ignore[assignment]
sin_buf: torch.Tensor = self.sin_cache # type: ignore[assignment]
cos = cos_buf[:seq_len][None, None, :, :]
sin = sin_buf[:seq_len][None, None, :, :]
x_even = x[..., 0::2]
x_odd = x[..., 1::2]
out_even = x_even * cos - x_odd * sin
out_odd = x_even * sin + x_odd * cos
return torch.stack((out_even, out_odd), dim=-1).flatten(-2)
class CausalSelfAttention(nn.Module):
"""Multi-head causal self-attention with RoPE."""
def __init__(self, cfg: TinyLLMConfig) -> None:
super().__init__()
self.n_heads = cfg.n_heads
self.d_head = cfg.d_model // cfg.n_heads
self.q_proj: nn.Module = nn.Linear(cfg.d_model, cfg.d_model, bias=False)
self.k_proj: nn.Module = nn.Linear(cfg.d_model, cfg.d_model, bias=False)
self.v_proj: nn.Module = nn.Linear(cfg.d_model, cfg.d_model, bias=False)
self.o_proj: nn.Module = nn.Linear(cfg.d_model, cfg.d_model, bias=False)
self.rope = RotaryPositionEmbedding(self.d_head, cfg.max_seq_len, cfg.rope_theta)
def forward(self, x: torch.Tensor) -> torch.Tensor:
bsz, seq_len, d_model = x.shape
q = self.q_proj(x).view(bsz, seq_len, self.n_heads, self.d_head).transpose(1, 2)
k = self.k_proj(x).view(bsz, seq_len, self.n_heads, self.d_head).transpose(1, 2)
v = self.v_proj(x).view(bsz, seq_len, self.n_heads, self.d_head).transpose(1, 2)
q = self.rope.apply_rope(q)
k = self.rope.apply_rope(k)
scores = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(float(self.d_head))
causal_mask = torch.triu(
torch.ones((seq_len, seq_len), dtype=torch.bool, device=x.device), diagonal=1
)
scores = scores.masked_fill(causal_mask[None, None, :, :], float("-inf"))
attn = torch.softmax(scores, dim=-1)
ctx = torch.matmul(attn, v).transpose(1, 2).contiguous().view(bsz, seq_len, d_model)
return self.o_proj(ctx)
class SwiGLUFFN(nn.Module):
"""SwiGLU gated feed-forward block."""
def __init__(self, d_model: int, d_ff: int) -> None:
super().__init__()
self.w_gate: nn.Module = nn.Linear(d_model, d_ff, bias=False)
self.w_up: nn.Module = nn.Linear(d_model, d_ff, bias=False)
self.w_down: nn.Module = nn.Linear(d_ff, d_model, bias=False)
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.w_down(F.silu(self.w_gate(x)) * self.w_up(x))
class ModernDecoderBlock(nn.Module):
"""Pre-Norm Modern LLM Transformer Block (RMSNorm + RoPE Causal Attn + SwiGLU)."""
def __init__(self, cfg: TinyLLMConfig) -> None:
super().__init__()
self.norm1 = RMSNorm(cfg.d_model)
self.attn = CausalSelfAttention(cfg)
self.norm2 = RMSNorm(cfg.d_model)
self.ffn = SwiGLUFFN(cfg.d_model, cfg.d_ff)
def forward(self, x: torch.Tensor) -> torch.Tensor:
x = x + self.attn(self.norm1(x))
x = x + self.ffn(self.norm2(x))
return x
class TinyModernDecoderLM(nn.Module):
"""Real modern decoder-only LLM from scratch (~58K params) for fast 4-stage CPU lifecycle."""
def __init__(self, cfg: TinyLLMConfig) -> None:
super().__init__()
self.cfg = cfg
self.tok_emb = nn.Embedding(cfg.vocab_size, cfg.d_model)
self.blocks = nn.ModuleList([ModernDecoderBlock(cfg) for _ in range(cfg.n_layers)])
self.norm_f = RMSNorm(cfg.d_model)
self.lm_head = nn.Linear(cfg.d_model, cfg.vocab_size, bias=False)
self._init_weights()
def _init_weights(self) -> None:
for module in self.modules():
if isinstance(module, nn.Linear):
nn.init.normal_(module.weight, mean=0.0, std=0.04)
elif isinstance(module, nn.Embedding):
nn.init.normal_(module.weight, mean=0.0, std=0.04)
def forward(self, input_ids: torch.Tensor) -> torch.Tensor:
x = self.tok_emb(input_ids)
for blk in self.blocks:
x = blk(x)
return self.lm_head(self.norm_f(x))
@torch.no_grad()
def generate(
self,
prompt_ids: torch.Tensor,
max_new_tokens: int,
eos_id: int,
temperature: float = 0.0,
generator: torch.Generator | None = None,
) -> torch.Tensor:
"""Autoregressive greedy (T=0) or temperature-sampled generation."""
self.eval()
seq = prompt_ids.clone()
bsz = seq.shape[0]
finished = torch.zeros(bsz, dtype=torch.bool, device=seq.device)
for _ in range(max_new_tokens):
logits = self.forward(seq)[:, -1, :]
if temperature <= 0.0:
next_tok = torch.argmax(logits, dim=-1, keepdim=True)
else:
probs = torch.softmax(logits / temperature, dim=-1)
next_tok = torch.multinomial(probs, num_samples=1, generator=generator)
next_tok = torch.where(
finished.unsqueeze(1), torch.full_like(next_tok, eos_id), next_tok
)
seq = torch.cat([seq, next_tok], dim=1)
finished = finished | (next_tok.squeeze(1) == eos_id)
if bool(finished.all().item()):
break
return seq
def inject_peft_adapters(
model: TinyModernDecoderLM,
method: str = "lora",
rank: int = 8,
alpha: float = 16.0,
) -> tuple[TinyModernDecoderLM, dict[str, Any]]:
"""Freeze base parameters and inject LoRA or DoRA adapters into attention, FFN & lm_head projections."""
if method not in {"lora", "dora"}:
raise ValueError("method must be 'lora' or 'dora'")
adapted = copy.deepcopy(model)
for param in adapted.parameters():
param.requires_grad_(False)
adapter_cls = LoRALinear if method == "lora" else DoRALinear
replaced_count = 0
for block in adapted.blocks:
assert isinstance(block, ModernDecoderBlock)
for attr in ("q_proj", "k_proj", "v_proj", "o_proj"):
layer = getattr(block.attn, attr)
if isinstance(layer, nn.Linear):
setattr(block.attn, attr, adapter_cls(layer, rank=rank, alpha=alpha))
replaced_count += 1
for attr in ("w_gate", "w_up", "w_down"):
layer = getattr(block.ffn, attr)
if isinstance(layer, nn.Linear):
setattr(block.ffn, attr, adapter_cls(layer, rank=rank, alpha=alpha))
replaced_count += 1
if isinstance(adapted.lm_head, nn.Linear):
adapted.lm_head = adapter_cls(adapted.lm_head, rank=rank, alpha=alpha) # type: ignore[assignment]
replaced_count += 1
total_params = sum(p.numel() for p in adapted.parameters())
trainable_params = sum(p.numel() for p in adapted.parameters() if p.requires_grad)
return adapted, {
"method": method,
"rank": rank,
"alpha": alpha,
"replaced_layers": replaced_count,
"total_params": total_params,
"trainable_params": trainable_params,
"trainable_ratio": trainable_params / float(total_params),
}
def merge_peft_adapters(model: TinyModernDecoderLM) -> TinyModernDecoderLM:
"""Fold all LoRA/DoRA modules back into plain nn.Linear layers for zero-latency serving."""
merged = copy.deepcopy(model)
for block in merged.blocks:
assert isinstance(block, ModernDecoderBlock)
for attr in ("q_proj", "k_proj", "v_proj", "o_proj"):
layer = getattr(block.attn, attr)
if isinstance(layer, (LoRALinear, DoRALinear)):
setattr(block.attn, attr, layer.merge_to_linear())
for attr in ("w_gate", "w_up", "w_down"):
layer = getattr(block.ffn, attr)
if isinstance(layer, (LoRALinear, DoRALinear)):
setattr(block.ffn, attr, layer.merge_to_linear())
if isinstance(merged.lm_head, (LoRALinear, DoRALinear)):
merged.lm_head = merged.lm_head.merge_to_linear()
return merged
def _pad_sequences(seqs: list[list[int]], pad_id: int) -> torch.Tensor:
max_len = max(len(s) for s in seqs)
out = torch.full((len(seqs), max_len), pad_id, dtype=torch.long)
for i, s in enumerate(seqs):
out[i, : len(s)] = torch.tensor(s, dtype=torch.long)
return out
def _build_pretrain_corpus(
samples: list[ArithmeticSample], vocab: ArithmeticVocab, seed: int
) -> list[list[int]]:
"""Create mixed web-like pretraining corpus (canonical + verbose + noisy web styles)."""
rng = np.random.default_rng(seed)
corpus: list[list[int]] = []
for s in samples:
# 1/3 verbose web text, 1/3 informal web text, 1/3 direct answers (half correct, half off-by-1)
corpus.append(vocab.encode(s.prompt_tokens + ["UMM", "VERBOSE"] + s.response_tokens))
corpus.append(vocab.encode(s.prompt_tokens + s.response_tokens))
wrong_ans = (s.answer + int(rng.choice([1, -1]))) % 10
corpus.append(
vocab.encode(
s.prompt_tokens + ["CHECK", "ANS:", "0", str(wrong_ans), "ERR", "<EOS>"]
)
)
return corpus
def pretrain_tiny_llm(
train_samples: list[ArithmeticSample],
eval_samples: list[ArithmeticSample],
vocab: ArithmeticVocab,
model_cfg: TinyLLMConfig | None = None,
steps: int = 95,
lr: float = 1.2e-2,
seed: int = 42,
) -> tuple[TinyModernDecoderLM, dict[str, Any]]:
"""Stage 1: Causal next-token pre-training from random initialization."""
torch.set_num_threads(1)
torch.manual_seed(seed)
np.random.seed(seed)
cfg = model_cfg or TinyLLMConfig(vocab_size=vocab.size)
model = TinyModernDecoderLM(cfg)
train_seqs = _build_pretrain_corpus(train_samples, vocab, seed=seed)
eval_seqs = _build_pretrain_corpus(eval_samples, vocab, seed=seed + 1)
train_tensor = _pad_sequences(train_seqs, vocab.pad_id)
eval_tensor = _pad_sequences(eval_seqs, vocab.pad_id)
def eval_clm_loss(data: torch.Tensor) -> float:
model.eval()
with torch.no_grad():
logits = model(data[:, :-1])
loss = F.cross_entropy(
logits.reshape(-1, vocab.size),
data[:, 1:].reshape(-1),
ignore_index=vocab.pad_id,
)
return float(loss.item())
init_eval_loss = eval_clm_loss(eval_tensor)
init_eval_ppl = float(math.exp(min(init_eval_loss, 20.0)))
optimizer = torch.optim.AdamW(model.parameters(), lr=lr, weight_decay=1e-2)
rng = np.random.default_rng(seed)
batch_size = min(48, train_tensor.shape[0])
model.train()
for _ in range(steps):
idx = rng.integers(0, train_tensor.shape[0], size=batch_size)
batch = train_tensor[idx]
logits = model(batch[:, :-1])
loss = F.cross_entropy(
logits.reshape(-1, vocab.size),
batch[:, 1:].reshape(-1),
ignore_index=vocab.pad_id,
)
optimizer.zero_grad()
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
optimizer.step()
final_eval_loss = eval_clm_loss(eval_tensor)
final_eval_ppl = float(math.exp(min(final_eval_loss, 20.0)))
total_params = sum(p.numel() for p in model.parameters())
return model, {
"total_params": total_params,
"steps": steps,
"init_eval_loss": init_eval_loss,
"final_eval_loss": final_eval_loss,
"init_eval_ppl": init_eval_ppl,
"final_eval_ppl": final_eval_ppl,
"ppl_reduction_factor": init_eval_ppl / max(final_eval_ppl, 1e-8),
}
def evaluate_verifiable_accuracy(
model: TinyModernDecoderLM,
samples: list[ArithmeticSample],
vocab: ArithmeticVocab,
) -> dict[str, float]:
"""Evaluate greedy generation format rate, exact arithmetic accuracy, and mean verifier reward."""
model.eval()
prompt_ids = torch.tensor([vocab.encode(s.prompt_tokens) for s in samples], dtype=torch.long)
prompt_len = prompt_ids.shape[1]
gen = model.generate(prompt_ids, max_new_tokens=6, eos_id=vocab.eos_id, temperature=0.0)
exact_hits = 0
format_hits = 0
total_reward = 0.0
for i, sample in enumerate(samples):
comp_ids = gen[i, prompt_len:].tolist()
comp_toks = vocab.decode(comp_ids)
ver = verify_arithmetic_completion(sample.prompt_tokens, comp_toks)
exact_hits += int(ver["exact_match"])
format_hits += int(ver["format_ok"])
total_reward += float(ver["reward"])
n = float(len(samples))
return {
"exact_accuracy": exact_hits / n,
"format_rate": format_hits / n,
"mean_reward": total_reward / n,
"num_samples": len(samples),
}
def sft_with_peft(
base_model: TinyModernDecoderLM,
train_samples: list[ArithmeticSample],
eval_samples: list[ArithmeticSample],
vocab: ArithmeticVocab,
method: str = "lora",
rank: int = 4,
alpha: float = 8.0,
mask_prompt: bool = True,
steps: int = 38,
lr: float = 8e-3,
seed: int = 42,
) -> tuple[TinyModernDecoderLM, dict[str, Any]]:
"""Stage 2: Supervised Fine-Tuning with LoRA/DoRA and optional prompt-token loss masking."""
torch.set_num_threads(1)
torch.manual_seed(seed)
np.random.seed(seed)
model, adapter_info = inject_peft_adapters(base_model, method=method, rank=rank, alpha=alpha)
def make_batch_tensors(items: list[ArithmeticSample]) -> tuple[torch.Tensor, torch.Tensor]:
full_seqs = [vocab.encode(s.prompt_tokens + s.response_tokens) for s in items]
prompt_lens = [len(s.prompt_tokens) for s in items]
inp = _pad_sequences(full_seqs, vocab.pad_id)
targets = inp[:, 1:].clone()
targets[targets == vocab.pad_id] = -100
if mask_prompt:
for row_idx, p_len in enumerate(prompt_lens):
targets[row_idx, : p_len - 1] = -100
return inp[:, :-1], targets
train_x, train_y = make_batch_tensors(train_samples)
eval_x, eval_y_masked = make_batch_tensors(eval_samples)
eval_y_resp = eval_y_masked.clone()
if not mask_prompt:
for row_idx, s in enumerate(eval_samples):
eval_y_resp[row_idx, : len(s.prompt_tokens) - 1] = -100
def eval_response_nll() -> float:
model.eval()
with torch.no_grad():
logits = model(eval_x)
loss = F.cross_entropy(
logits.reshape(-1, vocab.size), eval_y_resp.reshape(-1), ignore_index=-100
)
return float(loss.item())
before_metrics = evaluate_verifiable_accuracy(model, eval_samples, vocab)
init_resp_nll = eval_response_nll()
trainable_params = [p for p in model.parameters() if p.requires_grad]
optimizer = torch.optim.AdamW(trainable_params, lr=lr, weight_decay=1e-2)
rng = np.random.default_rng(seed)
batch_size = min(36, train_x.shape[0])
model.train()
for _ in range(steps):
idx = rng.integers(0, train_x.shape[0], size=batch_size)
logits = model(train_x[idx])
loss = F.cross_entropy(
logits.reshape(-1, vocab.size), train_y[idx].reshape(-1), ignore_index=-100
)
optimizer.zero_grad()
loss.backward()
torch.nn.utils.clip_grad_norm_(trainable_params, 1.0)
optimizer.step()
final_resp_nll = eval_response_nll()
after_metrics = evaluate_verifiable_accuracy(model, eval_samples, vocab)
return model, {
**adapter_info,
"mask_prompt": mask_prompt,
"steps": steps,
"init_response_nll": init_resp_nll,
"final_response_nll": final_resp_nll,
"before_eval": before_metrics,
"after_eval": after_metrics,
}
def generate_constitutional_pairs(
samples: list[ArithmeticSample],
) -> tuple[list[dict[str, Any]], list[ConstitutionalPrinciple]]:
"""Constitutional AI (Critique -> Revise) preference pair synthesizer."""
principles = [
ConstitutionalPrinciple(
code="C1-SAFE",
rule="Khong phat sinh noi dung doc hai (UNSAFE) hoac sai lech (ERR).",
forbidden_tokens=("UNSAFE", "ERR"),
),
ConstitutionalPrinciple(
code="C2-CONCISE",
rule="Tra loi ngan gon dung dinh dang 'ANS: d1 d0 OK <EOS>', loai bo nhieu UMM/VERBOSE.",
forbidden_tokens=("UMM", "VERBOSE"),
),
]
pairs: list[dict[str, Any]] = []
for idx, s in enumerate(samples):
if idx % 2 == 0:
raw_rejected = [
"UMM",
"VERBOSE",
"UNSAFE",
"ANS:",
s.response_tokens[1],
s.response_tokens[2],
"ERR",
"<EOS>",
]
violated = ["C1-SAFE", "C2-CONCISE"]
else:
wrong_ans = (s.answer + 1) % 20
raw_rejected = [
"UMM",
"VERBOSE",
"ANS:",
str(wrong_ans // 10),
str(wrong_ans % 10),
"ERR",
"<EOS>",
]
violated = ["C1-SAFE", "C2-CONCISE"]
critique_flags = [
p.code for p in principles if any(tok in raw_rejected for tok in p.forbidden_tokens)
]
pairs.append(
{
"prompt_tokens": s.prompt_tokens,
"chosen_tokens": s.response_tokens,
"rejected_tokens": raw_rejected,
"violated_principles": violated,
"critique_detected": critique_flags,
}
)
return pairs, principles
def _sequence_response_logprobs(
model: TinyModernDecoderLM,
prompt_tokens_list: list[list[str]],
response_tokens_list: list[list[str]],
vocab: ArithmeticVocab,
) -> tuple[torch.Tensor, torch.Tensor]:
"""Compute summed and mean token log-probabilities strictly over response tokens."""
seqs = [vocab.encode(p + r) for p, r in zip(prompt_tokens_list, response_tokens_list, strict=True)]
p_lens = [len(p) for p in prompt_tokens_list]
r_lens = [len(r) for r in response_tokens_list]
inp = _pad_sequences(seqs, vocab.pad_id)
logits = model(inp[:, :-1])
log_probs = F.log_softmax(logits, dim=-1)
targets = inp[:, 1:]
gathered = log_probs.gather(dim=-1, index=targets.unsqueeze(-1)).squeeze(-1)
mask = torch.zeros_like(gathered, dtype=torch.float32)
for i, (p_len, r_len) in enumerate(zip(p_lens, r_lens, strict=True)):
start = p_len - 1
end = start + r_len
mask[i, start:end] = 1.0
seq_sum = (gathered * mask).sum(dim=-1)
seq_mean = seq_sum / mask.sum(dim=-1).clamp_min(1.0)
return seq_sum, seq_mean
def compute_dpo_loss(
policy_chosen_logp: torch.Tensor,
policy_rejected_logp: torch.Tensor,
ref_chosen_logp: torch.Tensor,
ref_rejected_logp: torch.Tensor,
beta: float = 0.25,
nll_anchor_weight: float = 0.05,
policy_chosen_mean_logp: torch.Tensor | None = None,
) -> tuple[torch.Tensor, dict[str, float]]:
"""Exact Bradley-Terry DPO loss + optional NLL anchor mitigating likelihood displacement."""
chosen_rewards = beta * (policy_chosen_logp - ref_chosen_logp)
rejected_rewards = beta * (policy_rejected_logp - ref_rejected_logp)
margin = chosen_rewards - rejected_rewards
dpo_loss = -F.logsigmoid(margin).mean()
if policy_chosen_mean_logp is not None and nll_anchor_weight > 0.0:
total_loss = dpo_loss - nll_anchor_weight * policy_chosen_mean_logp.mean()
else:
total_loss = dpo_loss
# Ties (margin == 0 at init when policy == ref) represent 50% Bradley-Terry sigmoid(0)=0.5
wins = torch.where(
margin.abs() < 1e-7,
torch.full_like(margin, 0.5),
(margin > 0.0).float(),
)
pref_acc = float(wins.mean().item())
return total_loss, {
"dpo_loss": float(dpo_loss.item()),
"preference_accuracy": pref_acc,
"mean_reward_margin": float(margin.mean().item()),
"mean_chosen_reward": float(chosen_rewards.mean().item()),
"mean_rejected_reward": float(rejected_rewards.mean().item()),
}
def align_with_dpo(
sft_model: TinyModernDecoderLM,
train_pairs: list[dict[str, Any]],
eval_pairs: list[dict[str, Any]],
vocab: ArithmeticVocab,
beta: float = 0.25,
steps: int = 30,
lr: float = 2e-3,
seed: int = 42,
) -> tuple[TinyModernDecoderLM, dict[str, Any]]:
"""Stage 3: Direct Preference Optimization (DPO) against frozen reference checkpoint."""
torch.set_num_threads(1)
torch.manual_seed(seed)
np.random.seed(seed)
ref_model = copy.deepcopy(sft_model).eval()
for p in ref_model.parameters():
p.requires_grad_(False)
policy = copy.deepcopy(sft_model)
trainable = [p for p in policy.parameters() if p.requires_grad]
if not trainable:
for p in policy.parameters():
p.requires_grad_(True)
trainable = list(policy.parameters())
def eval_dpo(pairs: list[dict[str, Any]]) -> dict[str, float]:
policy.eval()
prompts = [x["prompt_tokens"] for x in pairs]
chosen = [x["chosen_tokens"] for x in pairs]
rejected = [x["rejected_tokens"] for x in pairs]
with torch.no_grad():
pc_sum, pc_mean = _sequence_response_logprobs(policy, prompts, chosen, vocab)
pr_sum, _ = _sequence_response_logprobs(policy, prompts, rejected, vocab)
rc_sum, rc_mean = _sequence_response_logprobs(ref_model, prompts, chosen, vocab)
rr_sum, _ = _sequence_response_logprobs(ref_model, prompts, rejected, vocab)
_, metrics = compute_dpo_loss(pc_sum, pr_sum, rc_sum, rr_sum, beta=beta)
kl_k3 = float(schulman_k3_kl(pc_mean, rc_mean).mean().item())
metrics["chosen_kl_k3"] = kl_k3
metrics["chosen_mean_logp"] = float(pc_mean.mean().item())
return metrics
before = eval_dpo(eval_pairs)
optimizer = torch.optim.AdamW(trainable, lr=lr, weight_decay=0.0)
rng = np.random.default_rng(seed)
batch_size = min(32, len(train_pairs))
policy.train()
for _ in range(steps):
idx = rng.integers(0, len(train_pairs), size=batch_size)
batch = [train_pairs[int(i)] for i in idx]
prompts = [x["prompt_tokens"] for x in batch]
chosen = [x["chosen_tokens"] for x in batch]
rejected = [x["rejected_tokens"] for x in batch]
pc_sum, pc_mean = _sequence_response_logprobs(policy, prompts, chosen, vocab)
pr_sum, _ = _sequence_response_logprobs(policy, prompts, rejected, vocab)
with torch.no_grad():
rc_sum, _ = _sequence_response_logprobs(ref_model, prompts, chosen, vocab)
rr_sum, _ = _sequence_response_logprobs(ref_model, prompts, rejected, vocab)
loss, _ = compute_dpo_loss(
pc_sum,
pr_sum,
rc_sum,
rr_sum,
beta=beta,
nll_anchor_weight=0.05,
policy_chosen_mean_logp=pc_mean,
)
optimizer.zero_grad()
loss.backward()
torch.nn.utils.clip_grad_norm_(trainable, 1.0)
optimizer.step()
after = eval_dpo(eval_pairs)
return policy, {
"beta": beta,
"steps": steps,
"before_eval": before,
"after_eval": after,
"margin_gain": after["mean_reward_margin"] - before["mean_reward_margin"],
}
def compute_group_relative_advantages(rewards: np.ndarray, eps: float = 1e-8) -> np.ndarray:
"""Critic-free GRPO group-relative advantage: A_i = (r_i - mean_G) / (std_G + eps)."""
r = np.asarray(rewards, dtype=np.float64)
if r.ndim != 1 or r.size < 2:
raise ValueError("rewards must be a 1D array with group size G >= 2")
mean_g = float(np.mean(r))
std_g = float(np.std(r))
if std_g < eps:
return np.zeros_like(r, dtype=np.float64)
return (r - mean_g) / (std_g + eps)
def posttrain_with_grpo_rlvr(
sft_model: TinyModernDecoderLM,
train_samples: list[ArithmeticSample],
eval_samples: list[ArithmeticSample],
vocab: ArithmeticVocab,
group_size: int = 6,
steps: int = 30,
clip_eps: float = 0.2,
kl_beta: float = 0.025,
lr: float = 7e-3,
temperature: float = 0.85,
seed: int = 42,
) -> tuple[TinyModernDecoderLM, dict[str, Any]]:
"""Stage 4: DeepSeek-R1 style critic-free GRPO + Deterministic Verifiable Rewards (RLVR)."""
torch.set_num_threads(1)
torch.manual_seed(seed)
np.random.seed(seed)
ref_model = copy.deepcopy(sft_model).eval()
for p in ref_model.parameters():
p.requires_grad_(False)
policy = copy.deepcopy(sft_model)
trainable = [p for p in policy.parameters() if p.requires_grad]
if not trainable:
for p in policy.parameters():
p.requires_grad_(True)
trainable = list(policy.parameters())
before_eval = evaluate_verifiable_accuracy(policy, eval_samples, vocab)
before_train = evaluate_verifiable_accuracy(policy, train_samples, vocab)
optimizer = torch.optim.AdamW(trainable, lr=lr, weight_decay=0.0)
rng = np.random.default_rng(seed)
torch_gen = torch.Generator()
torch_gen.manual_seed(seed)
prompts_per_step = min(14, len(train_samples))
max_comp_len = 5
total_groups = 0
homogeneous_groups = 0
last_kl_k3 = 0.0
last_clip_frac = 0.0
mean_group_reward_trace: list[float] = []
for _step in range(steps):
chosen_idx = rng.choice(len(train_samples), size=prompts_per_step, replace=False)
batch_samples = [train_samples[int(i)] for i in chosen_idx]
prompt_ids_base = torch.tensor(
[vocab.encode(s.prompt_tokens) for s in batch_samples], dtype=torch.long
)
prompt_len = prompt_ids_base.shape[1]
repeated_prompts = prompt_ids_base.repeat_interleave(group_size, dim=0)
with torch.no_grad():
rollout_seqs = policy.generate(
repeated_prompts,
max_new_tokens=max_comp_len,
eos_id=vocab.eos_id,
temperature=temperature,
generator=torch_gen,
)
all_adv = np.zeros(prompts_per_step * group_size, dtype=np.float64)
all_rewards = np.zeros(prompts_per_step * group_size, dtype=np.float64)
for p_i, sample in enumerate(batch_samples):
g_rewards = np.zeros(group_size, dtype=np.float64)
for g_i in range(group_size):
row = p_i * group_size + g_i
comp_ids = rollout_seqs[row, prompt_len:].tolist()
ver = verify_arithmetic_completion(sample.prompt_tokens, vocab.decode(comp_ids))
g_rewards[g_i] = float(ver["reward"])
total_groups += 1
if float(np.std(g_rewards)) < 1e-8:
homogeneous_groups += 1
g_adv = compute_group_relative_advantages(g_rewards)
all_rewards[p_i * group_size : (p_i + 1) * group_size] = g_rewards
all_adv[p_i * group_size : (p_i + 1) * group_size] = g_adv
mean_group_reward_trace.append(float(np.mean(all_rewards)))
if float(np.max(np.abs(all_adv))) < 1e-8:
continue
comp_targets = rollout_seqs[:, prompt_len:]
comp_mask = torch.ones_like(comp_targets, dtype=torch.float32)
for row_i in range(comp_targets.shape[0]):
eos_pos = (comp_targets[row_i] == vocab.eos_id).nonzero(as_tuple=False)
if eos_pos.numel() > 0:
first_eos = int(eos_pos[0].item())
if first_eos + 1 < comp_targets.shape[1]:
comp_mask[row_i, first_eos + 1 :] = 0.0
with torch.no_grad():
old_logits = policy(rollout_seqs[:, :-1])[:, prompt_len - 1 :, :]
old_tok_logp = (
F.log_softmax(old_logits, dim=-1)
.gather(-1, comp_targets.unsqueeze(-1))
.squeeze(-1)
)
ref_logits = ref_model(rollout_seqs[:, :-1])[:, prompt_len - 1 :, :]
ref_tok_logp = (
F.log_softmax(ref_logits, dim=-1)
.gather(-1, comp_targets.unsqueeze(-1))
.squeeze(-1)
)
adv_tensor = torch.tensor(all_adv, dtype=torch.float32).unsqueeze(1).expand_as(comp_targets)
active = comp_mask > 0.5
policy.train()
for _inner in range(2):
new_logits = policy(rollout_seqs[:, :-1])[:, prompt_len - 1 :, :]
new_tok_logp = (
F.log_softmax(new_logits, dim=-1)
.gather(-1, comp_targets.unsqueeze(-1))
.squeeze(-1)
)
ppo_loss, diag = ppo_clipped_surrogate_loss(
new_tok_logp[active],
old_tok_logp[active],
adv_tensor[active],
clip_eps=clip_eps,
)
kl_k3 = schulman_k3_kl(new_tok_logp[active], ref_tok_logp[active]).mean()
loss = ppo_loss + kl_beta * kl_k3
optimizer.zero_grad()
loss.backward()
torch.nn.utils.clip_grad_norm_(trainable, 1.0)
optimizer.step()
last_kl_k3 = float(kl_k3.item())
last_clip_frac = diag["clip_fraction"]
after_eval = evaluate_verifiable_accuracy(policy, eval_samples, vocab)
after_train = evaluate_verifiable_accuracy(policy, train_samples, vocab)
return policy, {
"group_size": group_size,
"steps": steps,
"clip_eps": clip_eps,
"kl_beta": kl_beta,
"before_eval": before_eval,
"after_eval": after_eval,
"before_train": before_train,
"after_train": after_train,
"eval_accuracy_lift": after_eval["exact_accuracy"] - before_eval["exact_accuracy"],
"train_accuracy_lift": after_train["exact_accuracy"] - before_train["exact_accuracy"],
"final_kl_k3": last_kl_k3,
"last_clip_fraction": last_clip_frac,
"homogeneous_group_rate": homogeneous_groups / float(max(total_groups, 1)),
"mean_rollout_reward_start": mean_group_reward_trace[0] if mean_group_reward_trace else 0.0,
"mean_rollout_reward_end": mean_group_reward_trace[-1] if mean_group_reward_trace else 0.0,
}
def save_safetensors_checkpoint(model: nn.Module, path: Path) -> Path:
"""Persist PyTorch model weights strictly via safetensors (zero pickle)."""
path.parent.mkdir(parents=True, exist_ok=True)
tensors = {k: v.detach().cpu().contiguous() for k, v in model.state_dict().items()}
safetensors_save_file(tensors, str(path))
return path
def load_safetensors_checkpoint(model: nn.Module, path: Path) -> nn.Module:
"""Load safetensors checkpoint strictly into model state_dict."""
tensors = safetensors_load_file(str(path), device="cpu")
model.load_state_dict(tensors, strict=True)
return model
def run_full_ch21_lab12_benchmarks(seed: int = 42, quick: bool = False) -> dict[str, Any]:
"""Execute complete Tier 1 + Tier 2 Ch 21 & Lab 12 benchmarks and assemble workbench panels."""
torch.set_num_threads(1)
vocab = ArithmeticVocab()
splits = build_arithmetic_splits(seed=seed)
train_samples, eval_samples = splits["train"], splits["eval"]
# 1. RL Foundations (GAE + PPO + Schulman k3 KL)
ppo_bench = run_ppo_policy_benchmark(seed=seed)
# 2. PEFT Audits (LoRA/DoRA merge parity, NF4 quantization, 7B/70B VRAM & RLHF/DPO/GRPO VRAM)
peft_parity = audit_lora_and_dora_merge_parity(seed=seed)
nf4_audit = audit_nf4_quantization_roundtrip(seed=seed)
vram_7b = compute_peft_vram_budget(
PEFTMemoryConfig(
model_name="7B Class",
total_params_b=7.0,
n_layers=32,
d_model=4096,
d_ff=11008,
lora_rank=16,
)
)
vram_70b = compute_peft_vram_budget(
PEFTMemoryConfig(
model_name="70B Llama-3",
total_params_b=70.0,
n_layers=80,
d_model=8192,
d_ff=28672,
lora_rank=16,
)
)
pt_vram_7b = compute_post_training_vram_comparison(total_params_b=7.0)
pt_vram_70b = compute_post_training_vram_comparison(total_params_b=70.0)
# 3. 4-Stage Tiny LLM From Scratch Lifecycle
pretrain_steps = 65 if quick else 95
sft_steps_full = 30 if quick else 45
sft_steps_cold = 8 if quick else 10
dpo_steps = 15 if quick else 22
grpo_steps = 22 if quick else 36
base_model, stage1_pretrain = pretrain_tiny_llm(
train_samples, eval_samples, vocab, steps=pretrain_steps, seed=seed
)
# Stage 2: SFT ablations (Prompt-Masked LoRA vs Unmasked LoRA vs Prompt-Masked DoRA)
sft_lora_masked, stage2_lora_masked = sft_with_peft(
base_model,
train_samples,
eval_samples,
vocab,
method="lora",
rank=6,
alpha=12.0,
mask_prompt=True,
steps=sft_steps_full,
lr=6.0e-3,
seed=seed,
)
_, stage2_lora_unmasked = sft_with_peft(
base_model,
train_samples,
eval_samples,
vocab,
method="lora",
rank=6,
alpha=12.0,
mask_prompt=False,
steps=sft_steps_full,
lr=6.0e-3,
seed=seed,
)
sft_dora_masked, stage2_dora_masked = sft_with_peft(
base_model,
train_samples,
eval_samples,
vocab,
method="dora",
rank=6,
alpha=12.0,
mask_prompt=True,
steps=sft_steps_full,
lr=6.0e-3,
seed=seed,
)
# Verify adapter merge parity on trained DoRA LLM
merged_dora_lm = merge_peft_adapters(sft_dora_masked).eval()
probe_ids = torch.tensor(
[vocab.encode(s.prompt_tokens) for s in eval_samples[:8]], dtype=torch.long
)
with torch.no_grad():
dora_lm_merge_diff = float(
(sft_dora_masked.eval()(probe_ids) - merged_dora_lm(probe_ids)).abs().max().item()
)
# Stage 3: Constitutional AI Critique-Revise + DPO Preference Alignment
train_pairs, principles = generate_constitutional_pairs(train_samples)
eval_pairs, _ = generate_constitutional_pairs(eval_samples)
dpo_model, stage3_dpo = align_with_dpo(
sft_lora_masked, train_pairs, eval_pairs, vocab, beta=0.25, steps=dpo_steps, seed=seed
)
# Stage 4: Cold-Start SFT -> Reasoning GRPO + RLVR (DeepSeek-R1 pattern)
sft_cold, stage2_rlvr_seed = sft_with_peft(
base_model,
train_samples[:24],
eval_samples,
vocab,
method="lora",
rank=6,
alpha=12.0,
mask_prompt=True,
steps=sft_steps_cold,
lr=4.0e-3,
seed=seed + 7,
)
grpo_model, stage4_grpo = posttrain_with_grpo_rlvr(
sft_cold,
train_samples,
eval_samples,
vocab,
group_size=8,
steps=grpo_steps,
clip_eps=0.2,
kl_beta=0.02,
lr=2.5e-3,
temperature=0.95,
seed=seed,
)
# Safetensors checkpoint round-trip verification (zero pickle)
merged_grpo = merge_peft_adapters(grpo_model).eval()
reloaded = TinyModernDecoderLM(merged_grpo.cfg).eval()
with tempfile.TemporaryDirectory() as tmp:
ckpt_path = save_safetensors_checkpoint(
merged_grpo, Path(tmp) / "tiny_llm_grpo.safetensors"
)
load_safetensors_checkpoint(reloaded, ckpt_path)
with torch.no_grad():
st_roundtrip_diff = float(
(merged_grpo(probe_ids) - reloaded(probe_ids)).abs().max().item()
)
merged_dpo = merge_peft_adapters(dpo_model).eval()
with torch.no_grad():
dpo_merge_diff = float(
(dpo_model.eval()(probe_ids) - merged_dpo(probe_ids)).abs().max().item()
)
dora_vram_delta = vram_70b["dora_bf16_total_gb"] - vram_70b["lora_bf16_total_gb"]
workbench_panels = {
"kpis": [
{
"id": "kpi_qlora_70b_vram",
"label": "70B QLoRA NF4 VRAM vs Full FT",
"value": f"{vram_70b['qlora_nf4_total_gb']:.1f} GB",
"unit": f"({vram_70b['qlora_vs_full_ft_reduction_x']:.1f}x cut)",
"status": "ok",
"detail": (
f"Full FT AdamW needs {vram_70b['full_ft_total_gb']:.0f} GB; "
f"QLoRA NF4+DQ fits on 1x 80GB GPU "
f"with {vram_70b['trainable_pct_lora']:.2f}% trainable params."
),
},
{
"id": "kpi_pretrain_ppl_drop",
"label": "Stage 1 Pre-Train Perplexity Drop",
"value": f"{stage1_pretrain['final_eval_ppl']:.2f}",
"unit": f"({stage1_pretrain['ppl_reduction_factor']:.1f}x cut)",
"status": "ok",
"detail": (
f"TinyModernDecoderLM ({stage1_pretrain['total_params']:,} params) drops eval PPL "
f"from {stage1_pretrain['init_eval_ppl']:.2f} to {stage1_pretrain['final_eval_ppl']:.2f}."
),
},
{
"id": "kpi_sft_masking_dora",
"label": "Stage 2 Prompt-Masked SFT (DoRA)",
"value": f"{100.0 * stage2_dora_masked['after_eval']['exact_accuracy']:.1f}%",
"unit": f"(NLL {stage2_dora_masked['final_response_nll']:.3f})",
"status": "ok",
"detail": (
f"Prompt-masked LoRA NLL={stage2_lora_masked['final_response_nll']:.3f} vs "
f"Unmasked NLL={stage2_lora_unmasked['final_response_nll']:.3f}; "
f"DoRA merge diff={dora_lm_merge_diff:.2e}."
),
},
{
"id": "kpi_dpo_preference_acc",
"label": "Stage 3 DPO + CAI Preference Acc",
"value": f"{100.0 * stage3_dpo['after_eval']['preference_accuracy']:.1f}%",
"unit": f"(margin +{stage3_dpo['after_eval']['mean_reward_margin']:.2f})",
"status": "ok",
"detail": (
f"Bradley-Terry DPO lifts pref accuracy from "
f"{100.0 * stage3_dpo['before_eval']['preference_accuracy']:.1f}% with "
f"bounded Schulman k3 KL={stage3_dpo['after_eval']['chosen_kl_k3']:.4f}."
),
},
{
"id": "kpi_grpo_rlvr_lift",
"label": "Stage 4 GRPO + RLVR Verifiable Acc",
"value": f"{100.0 * stage4_grpo['after_eval']['exact_accuracy']:.1f}%",
"unit": f"(+{100.0 * stage4_grpo['eval_accuracy_lift']:.1f}pp)",
"status": "ok",
"detail": (
f"Critic-free GRPO (G={stage4_grpo['group_size']}) lifts held-out accuracy from "
f"{100.0 * stage4_grpo['before_eval']['exact_accuracy']:.1f}% with "
f"k3 KL={stage4_grpo['final_kl_k3']:.4f} and saves "
f"{pt_vram_7b['grpo_vs_ppo_vram_saving_pct']:.0f}% VRAM vs PPO."
),
},
{
"id": "kpi_safetensors_parity",
"label": "Safetensors & NF4 SNR Fidelity",
"value": f"{st_roundtrip_diff:.1e}",
"unit": f"(NF4 {nf4_audit['nf4_snr_db']:.1f} dB)",
"status": "ok",
"detail": (
f"Zero-pickle safetensors round-trip diff={st_roundtrip_diff:.1e}; "
f"NF4 beats uniform INT4 by +{nf4_audit['snr_gain_db']:.2f} dB SNR."
),
},
],
"bars": [
{
"id": "bar_peft_70b_vram_gb",
"title": "70B Llama-3 Fine-Tuning VRAM Budget (GB, Lower is Better)",
"metric_label": "VRAM (GB)",
"items": [
{
"label": "Full FT (AdamW bf16)",
"value": vram_70b["full_ft_total_gb"],
"display": f"{vram_70b['full_ft_total_gb']:.1f} GB (16x H100)",
"css_class": "is-slow",
},
{
"label": "LoRA (bf16, r=16)",
"value": vram_70b["lora_bf16_total_gb"],
"display": f"{vram_70b['lora_bf16_total_gb']:.1f} GB (2x 80GB)",
"css_class": "is-mid",
},
{
"label": "DoRA (bf16, r=16)",
"value": vram_70b["dora_bf16_total_gb"],
"display": f"{vram_70b['dora_bf16_total_gb']:.1f} GB (+{dora_vram_delta:.2f} GB)",
"css_class": "is-mid",
},
{
"label": "QLoRA (NF4 + DQ)",
"value": vram_70b["qlora_nf4_total_gb"],
"display": f"{vram_70b['qlora_nf4_total_gb']:.1f} GB (1x 80GB)",
"css_class": "is-fast",
},
],
},
{
"id": "bar_posttrain_vram_7b",
"title": "7B Post-Training Static VRAM: RLHF-PPO vs DPO vs GRPO+RLVR (GB)",
"metric_label": "Static VRAM (GB)",
"items": [
{
"label": "RLHF-PPO (4 models)",
"value": pt_vram_7b["rlhf_ppo_4_models_gb"],
"display": f"{pt_vram_7b['rlhf_ppo_4_models_gb']:.0f} GB (Actor+Critic+Ref+RM)",
"css_class": "is-slow",
},
{
"label": "DPO (2 models)",
"value": pt_vram_7b["dpo_2_models_gb"],
"display": f"{pt_vram_7b['dpo_2_models_gb']:.0f} GB (-50% vs PPO)",
"css_class": "is-fast",
},
{
"label": "GRPO + RLVR (2 models)",
"value": pt_vram_7b["grpo_rlvr_2_models_gb"],
"display": f"{pt_vram_7b['grpo_rlvr_2_models_gb']:.0f} GB (Critic-Free)",
"css_class": "is-fast",
},
{
"label": "SimPO (1 model)",
"value": pt_vram_7b["simpo_1_model_gb"],
"display": f"{pt_vram_7b['simpo_1_model_gb']:.0f} GB (Ref-Free)",
"css_class": "is-fast",
},
],
},
{
"id": "bar_grpo_rlvr_verifiable_acc",
"title": "Tiny LLM Verifiable Arithmetic Accuracy Across Stages (%)",
"metric_label": "Held-out Accuracy (%)",
"items": [
{
"label": "Stage 1 Base (Pre-Train)",
"value": 100.0 * stage2_lora_masked["before_eval"]["exact_accuracy"],
"display": f"{100.0 * stage2_lora_masked['before_eval']['exact_accuracy']:.1f}%",
"css_class": "is-slow",
},
{
"label": "Stage 2 Cold-Start SFT",
"value": 100.0 * stage4_grpo["before_eval"]["exact_accuracy"],
"display": f"{100.0 * stage4_grpo['before_eval']['exact_accuracy']:.1f}%",
"css_class": "is-mid",
},
{
"label": "Stage 2 Full DoRA SFT",
"value": 100.0 * stage2_dora_masked["after_eval"]["exact_accuracy"],
"display": f"{100.0 * stage2_dora_masked['after_eval']['exact_accuracy']:.1f}%",
"css_class": "is-fast",
},
{
"label": f"Stage 4 GRPO + RLVR (G={stage4_grpo['group_size']})",
"value": 100.0 * stage4_grpo["after_eval"]["exact_accuracy"],
"display": (
f"{100.0 * stage4_grpo['after_eval']['exact_accuracy']:.1f}% "
f"(+{100.0 * stage4_grpo['eval_accuracy_lift']:.1f}pp)"
),
"css_class": "is-fast",
},
],
},
{
"id": "bar_sft_masking_nll",
"title": "Stage 2 SFT Response NLL: Prompt-Masked vs Unmasked (Lower is Better)",
"metric_label": "Eval Response NLL",
"items": [
{
"label": "Base Pre-Trained (Before SFT)",
"value": stage2_lora_masked["init_response_nll"],
"display": f"{stage2_lora_masked['init_response_nll']:.3f}",
"css_class": "is-slow",
},
{
"label": "LoRA Unmasked SFT",
"value": stage2_lora_unmasked["final_response_nll"],
"display": f"{stage2_lora_unmasked['final_response_nll']:.3f}",
"css_class": "is-mid",
},
{
"label": "LoRA Prompt-Masked SFT",
"value": stage2_lora_masked["final_response_nll"],
"display": f"{stage2_lora_masked['final_response_nll']:.3f}",
"css_class": "is-fast",
},
{
"label": "DoRA Prompt-Masked SFT",
"value": stage2_dora_masked["final_response_nll"],
"display": f"{stage2_dora_masked['final_response_nll']:.3f}",
"css_class": "is-fast",
},
],
},
],
"tables": [
{
"id": "tbl_peft_vram_matrix",
"title": "PEFT Memory Wall Accounting: 7B vs 70B (r=16, seq=2048, Grad Ckpt)",
"columns": [
"Model & Method",
"Static VRAM (GB)",
"Total VRAM (GB)",
"Trainable Params & Fit",
],
"rows": [
[
"7B Full FT (AdamW)",
f"{vram_7b['full_ft_static_gb']:.1f}",
f"{vram_7b['full_ft_total_gb']:.1f}",
"100.0% (OOM 1x 80GB)",
],
[
"7B QLoRA (NF4 + DQ)",
f"{vram_7b['qlora_nf4_static_gb']:.1f}",
f"{vram_7b['qlora_nf4_total_gb']:.1f}",
f"{vram_7b['trainable_pct_lora']:.2f}% (Fits 1x 16GB)",
],
[
"70B Full FT (AdamW)",
f"{vram_70b['full_ft_static_gb']:.1f}",
f"{vram_70b['full_ft_total_gb']:.1f}",
"100.0% (Needs 16x 80GB)",
],
[
"70B LoRA / DoRA (bf16)",
f"{vram_70b['lora_bf16_static_gb']:.1f} / {vram_70b['dora_bf16_static_gb']:.1f}",
f"{vram_70b['lora_bf16_total_gb']:.1f} / {vram_70b['dora_bf16_total_gb']:.1f}",
f"{vram_70b['trainable_pct_lora']:.2f}% / {vram_70b['trainable_pct_dora']:.2f}%",
],
[
"70B QLoRA (NF4 + DQ)",
f"{vram_70b['qlora_nf4_static_gb']:.1f}",
f"{vram_70b['qlora_nf4_total_gb']:.1f}",
f"{vram_70b['trainable_pct_lora']:.2f}% (Fits 1x 80GB!)",
],
],
},
{
"id": "tbl_4stage_llm_lifecycle",
"title": "4-Stage Tiny LLM From Scratch Lifecycle Results (PyTorch CPU)",
"columns": [
"Lifecycle Stage",
"Primary Metric (Before -> After)",
"Key Regularizer / Guard",
"Verdict",
],
"rows": [
[
"Stage 1: Pre-Training (CLM)",
(
f"Eval PPL {stage1_pretrain['init_eval_ppl']:.2f} -> "
f"{stage1_pretrain['final_eval_ppl']:.2f}"
),
f"{stage1_pretrain['ppl_reduction_factor']:.1f}x perplexity cut",
"PASS",
],
[
"Stage 2: SFT (LoRA / DoRA)",
(
f"Resp NLL {stage2_dora_masked['init_response_nll']:.3f} -> "
f"{stage2_dora_masked['final_response_nll']:.3f}"
),
(
f"Masked ({stage2_lora_masked['final_response_nll']:.3f}) < "
f"Unmasked ({stage2_lora_unmasked['final_response_nll']:.3f})"
),
"PASS",
],
[
"Stage 3: DPO + CAI",
(
f"Pref Acc {100.0 * stage3_dpo['before_eval']['preference_accuracy']:.1f}% -> "
f"{100.0 * stage3_dpo['after_eval']['preference_accuracy']:.1f}%"
),
(
f"Margin +{stage3_dpo['after_eval']['mean_reward_margin']:.2f}, "
f"k3 KL={stage3_dpo['after_eval']['chosen_kl_k3']:.4f}"
),
"PASS",
],
[
f"Stage 4: GRPO + RLVR (G={stage4_grpo['group_size']})",
(
f"Verif Acc {100.0 * stage4_grpo['before_eval']['exact_accuracy']:.1f}% -> "
f"{100.0 * stage4_grpo['after_eval']['exact_accuracy']:.1f}%"
),
(
f"Lift +{100.0 * stage4_grpo['eval_accuracy_lift']:.1f}pp, "
f"k3 KL={stage4_grpo['final_kl_k3']:.4f}"
),
"PASS",
],
],
},
{
"id": "tbl_rl_and_quant_parity",
"title": "Numerical & Algorithmic Invariants: PPO, LoRA/DoRA Merge, NF4 & Safetensors",
"columns": [
"Invariant Audit",
"Measured Value",
"Requirement",
"Status",
],
"rows": [
[
"PPO + GAE MDP Return Gain",
(
f"{ppo_bench['initial_expected_return']:.2f} -> "
f"{ppo_bench['final_expected_return']:.2f} "
f"(opt {ppo_bench['optimal_return']:.2f})"
),
"Return gain > +2.0",
"PASS",
],
[
"LoRA / DoRA Zero-Latency Merge",
(
f"{peft_parity['lora_merge_max_diff']:.2e} / "
f"{peft_parity['dora_merge_max_diff']:.2e}"
),
"< 1e-5 exact parity",
"EXACT PASS",
],
[
"QLoRA NF4 vs Uniform INT4 SNR",
(
f"{nf4_audit['nf4_snr_db']:.2f} dB vs "
f"{nf4_audit['uniform_int4_snr_db']:.2f} dB "
f"(+{nf4_audit['snr_gain_db']:.2f} dB)"
),
"NF4 SNR > Uniform INT4",
"PASS",
],
[
"Safetensors Round-Trip Parity",
f"{st_roundtrip_diff:.1e} (DPO merge {dpo_merge_diff:.2e})",
"== 0.0 (zero pickle)",
"EXACT PASS",
],
],
},
{
"id": "tbl_posttrain_method_tradeoffs",
"title": "2026 Post-Training Alignment & Reasoning Method Trade-Offs",
"columns": [
"Method",
"Models in VRAM",
"Reward Signal",
"Best Production Regime",
],
"rows": [
[
"RLHF-PPO",
"4 (Actor, Critic, Ref, RM)",
"Learned Bradley-Terry RM",
"Open-ended chat with online exploration",
],
[
"DPO / SimPO",
"2 (Policy, Ref) / 1 (Ref-free)",
"Offline preference pairs (y_w, y_l)",
"Fast style/safety alignment & CAI RLAIF",
],
[
"GRPO + RLVR",
"2 (Policy, Ref) + CPU Verifier",
"Deterministic verifiable reward r_i",
"Math, code, logic & structured reasoning",
],
[
"Constitutional AI",
"Generator + Critic/Reviser",
"Explicit constitutional principles",
"Scalable low-cost safety & RLAIF pairs",
],
],
},
],
}
return {
"config": {
"seed": seed,
"quick": quick,
"torch_version": torch.__version__,
"device": "cpu",
"vocab_size": vocab.size,
"train_samples": len(train_samples),
"eval_samples": len(eval_samples),
"constitutional_principles": len(principles),
},
"workbench_panels": workbench_panels,
"rl_foundations": {
"ppo_benchmark": ppo_bench,
"post_training_vram_7b": pt_vram_7b,
"post_training_vram_70b": pt_vram_70b,
},
"peft_audits": {
"lora_dora_merge_parity": peft_parity,
"nf4_quantization": nf4_audit,
"vram_7b": vram_7b,
"vram_70b": vram_70b,
"dora_lm_merge_diff": dora_lm_merge_diff,
"dpo_lm_merge_diff": dpo_merge_diff,
},
"llm_lifecycle": {
"stage1_pretrain": stage1_pretrain,
"stage2_sft_lora_masked": stage2_lora_masked,
"stage2_sft_lora_unmasked": stage2_lora_unmasked,
"stage2_sft_dora_masked": stage2_dora_masked,
"stage2_rlvr_seed": stage2_rlvr_seed,
"stage3_dpo_cai": stage3_dpo,
"stage4_grpo_rlvr": stage4_grpo,
"safetensors_roundtrip_max_diff": st_roundtrip_diff,
},
}
"""End-to-end CLI benchmark runner for Lab 12: LLM From Scratch (Pre-Train -> SFT -> DPO/CAI -> GRPO+RLVR)."""
from __future__ import annotations
import argparse
import json
import sys
from pathlib import Path
if hasattr(sys.stdout, "reconfigure"):
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
try:
import llm_from_scratch_lab # noqa: F401
except ImportError:
_SRC_DIR = Path(__file__).resolve().parents[1] / "src"
if str(_SRC_DIR) not in sys.path:
sys.path.insert(0, str(_SRC_DIR))
from llm_from_scratch_lab.tiny_llm_lifecycle import run_full_ch21_lab12_benchmarks # noqa: E402
def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
"""Parse CLI arguments for Lab 12 benchmark execution."""
parser = argparse.ArgumentParser(
description=(
"Run Lab 12: RL (GAE/PPO/k3 KL), PEFT (LoRA/DoRA/QLoRA NF4) & "
"4-Stage Tiny LLM From Scratch (Pre-Train -> SFT -> DPO/CAI -> GRPO+RLVR)."
)
)
parser.add_argument("--seed", type=int, default=42, help="Deterministic RNG seed.")
parser.add_argument(
"--quick",
action="store_true",
help="Run lighter step counts for fast CI verification (<4s CPU).",
)
parser.add_argument(
"--output",
type=str,
default="artifacts/ch21_lab12_results.json",
help="Output JSON artifact path.",
)
return parser.parse_args(argv)
def main(argv: list[str] | None = None) -> int:
"""Run all Tier 1 + Tier 2 Lab 12 benchmarks, print telemetry summary, and write JSON artifact."""
args = parse_args(argv)
payload = run_full_ch21_lab12_benchmarks(seed=args.seed, quick=args.quick)
payload["config"]["output"] = args.output
ppo = payload["rl_foundations"]["ppo_benchmark"]
pt7 = payload["rl_foundations"]["post_training_vram_7b"]
peft = payload["peft_audits"]
v70 = peft["vram_70b"]
nf4 = peft["nf4_quantization"]
lc = payload["llm_lifecycle"]
s1 = lc["stage1_pretrain"]
s2_m = lc["stage2_sft_lora_masked"]
s2_u = lc["stage2_sft_lora_unmasked"]
s2_d = lc["stage2_sft_dora_masked"]
s3 = lc["stage3_dpo_cai"]
s4 = lc["stage4_grpo_rlvr"]
print("=== Ch 21 + Lab 12: RL, PEFT (LoRA/QLoRA/DoRA) & 4-Stage LLM From Scratch ===")
print(
f"[1] RL Foundations (GAE + PPO + k3 KL): "
f"Return {ppo['initial_expected_return']:.2f} -> {ppo['final_expected_return']:.2f} "
f"(opt {ppo['optimal_return']:.2f}) | k3_KL={ppo['final_kl_k3']:.4f} | "
f"7B VRAM: PPO={pt7['rlhf_ppo_4_models_gb']:.0f}GB vs GRPO={pt7['grpo_rlvr_2_models_gb']:.0f}GB "
f"(-{pt7['grpo_vs_ppo_vram_saving_pct']:.0f}%)"
)
print(
f"[2] PEFT & NF4 Quantization: "
f"70B FullFT={v70['full_ft_total_gb']:.1f}GB -> LoRA={v70['lora_bf16_total_gb']:.1f}GB "
f"-> QLoRA={v70['qlora_nf4_total_gb']:.1f}GB ({v70['qlora_vs_full_ft_reduction_x']:.1f}x cut) | "
f"MergeParity(LoRA={peft['lora_dora_merge_parity']['lora_merge_max_diff']:.2e}, "
f"DoRA={peft['lora_dora_merge_parity']['dora_merge_max_diff']:.2e}) | "
f"NF4 SNR={nf4['nf4_snr_db']:.2f}dB (+{nf4['snr_gain_db']:.2f}dB vs INT4)"
)
print(
f"[3] Stage 1 Pre-Train & Stage 2 SFT (LoRA/DoRA): "
f"PPL {s1['init_eval_ppl']:.2f} -> {s1['final_eval_ppl']:.2f} ({s1['ppl_reduction_factor']:.1f}x) | "
f"SFT Resp NLL(Masked LoRA={s2_m['final_response_nll']:.3f} vs "
f"Unmasked={s2_u['final_response_nll']:.3f} vs DoRA={s2_d['final_response_nll']:.3f}) | "
f"DoRA Acc={100.0 * s2_d['after_eval']['exact_accuracy']:.1f}%"
)
print(
f"[4] Stage 3 DPO+CAI & Stage 4 GRPO+RLVR (G={s4['group_size']}): "
f"DPO PrefAcc {100.0 * s3['before_eval']['preference_accuracy']:.1f}% -> "
f"{100.0 * s3['after_eval']['preference_accuracy']:.1f}% "
f"(margin=+{s3['after_eval']['mean_reward_margin']:.2f}, "
f"k3={s3['after_eval']['chosen_kl_k3']:.4f}) | "
f"GRPO VerifAcc {100.0 * s4['before_eval']['exact_accuracy']:.1f}% -> "
f"{100.0 * s4['after_eval']['exact_accuracy']:.1f}% "
f"(+{100.0 * s4['eval_accuracy_lift']:.1f}pp, k3={s4['final_kl_k3']:.4f}) | "
f"Safetensors={lc['safetensors_roundtrip_max_diff']:.1e}"
)
out_path = Path(args.output)
out_path.parent.mkdir(parents=True, exist_ok=True)
out_path.write_text(json.dumps(payload, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
return 0
if __name__ == "__main__":
raise SystemExit(main())
"""16 deterministic CPU-only verification tests for Lab 12 (llm_from_scratch_lab)."""
from __future__ import annotations
import ast
import json
import subprocess
import sys
from pathlib import Path
import numpy as np
import pytest
import torch
import torch.nn as nn
from pydantic import ValidationError
from llm_from_scratch_lab import (
ArithmeticVocab,
DoRALinear,
LoRALinear,
PEFTMemoryConfig,
PostTrainingConfig,
PPOConfig,
TinyLLMConfig,
TinyModernDecoderLM,
align_with_dpo,
audit_lora_and_dora_merge_parity,
audit_nf4_quantization_roundtrip,
build_arithmetic_splits,
compute_gae_advantages,
compute_group_relative_advantages,
compute_peft_vram_budget,
compute_post_training_vram_comparison,
generate_constitutional_pairs,
load_safetensors_checkpoint,
posttrain_with_grpo_rlvr,
ppo_clipped_surrogate_loss,
pretrain_tiny_llm,
run_ppo_policy_benchmark,
save_safetensors_checkpoint,
schulman_k3_kl,
schulman_k3_kl_numpy,
sft_with_peft,
verify_arithmetic_completion,
)
LAB_ROOT = Path(__file__).resolve().parents[1]
BANNED_DESERIALIZERS = {"pickle", "joblib", "cloudpickle", "dill", "shelve", "marshal"}
@pytest.fixture(scope="module")
def shared_pretrained_bundle() -> dict[str, object]:
"""Train one shared base model for fast deterministic downstream stage tests."""
vocab = ArithmeticVocab()
splits = build_arithmetic_splits(seed=42)
base_model, pretrain_stats = pretrain_tiny_llm(
splits["train"], splits["eval"], vocab, steps=95, seed=42
)
return {
"vocab": vocab,
"train": splits["train"],
"eval": splits["eval"],
"base_model": base_model,
"pretrain_stats": pretrain_stats,
}
def test_01_pydantic_configs_strict_forbid() -> None:
"""All Pydantic configs reject unknown fields and invalid architectural divisibility."""
with pytest.raises(ValidationError):
PPOConfig(unknown_flag=True) # type: ignore[call-arg]
with pytest.raises(ValidationError):
PEFTMemoryConfig(extra_param=123) # type: ignore[call-arg]
with pytest.raises(ValidationError):
PostTrainingConfig(bad_key="x") # type: ignore[call-arg]
with pytest.raises(ValidationError):
TinyLLMConfig(d_model=65, n_heads=4)
with pytest.raises(ValidationError):
TinyLLMConfig(d_model=60, n_heads=4) # d_head=15 is odd -> invalid for RoPE
def test_02_gae_advantages_and_ppo_clipping_invariants() -> None:
"""Verify GAE boundary cases (lam=0 TD0, lam=1 MC), PPO clipping pessimism & return gain."""
rewards = np.array([1.0, 0.5, 2.0, -1.0], dtype=np.float64)
values = np.array([0.8, 0.4, 1.2, 0.1], dtype=np.float64)
dones = np.array([0.0, 0.0, 0.0, 1.0], dtype=np.float64)
gamma = 0.9
adv_td0, _ = compute_gae_advantages(rewards, values, dones, gamma=gamma, lam=0.0)
expected_td0 = np.array(
[
1.0 + 0.9 * 0.4 - 0.8,
0.5 + 0.9 * 1.2 - 0.4,
2.0 + 0.9 * 0.1 - 1.2,
-1.0 - 0.1,
]
)
assert np.allclose(adv_td0, expected_td0, atol=1e-12)
adv_mc, ret_mc = compute_gae_advantages(rewards, values, dones, gamma=gamma, lam=1.0)
mc_returns = np.array(
[
1.0 + 0.9 * 0.5 + 0.81 * 2.0 + 0.729 * (-1.0),
0.5 + 0.9 * 2.0 + 0.81 * (-1.0),
2.0 + 0.9 * (-1.0),
-1.0,
]
)
assert np.allclose(ret_mc, mc_returns, atol=1e-12)
assert np.allclose(adv_mc, mc_returns - values, atol=1e-12)
# PPO clip must cap positive advantage at (1 + eps) and negative advantage at (1 - eps)
old_lp = torch.zeros(2)
new_lp = torch.tensor([1.0, -1.0]) # ratios e^1 ~ 2.718, e^-1 ~ 0.368
adv = torch.tensor([1.0, -1.0])
loss, diag = ppo_clipped_surrogate_loss(new_lp, old_lp, adv, clip_eps=0.2)
# min(2.718*1, 1.2*1)=1.2 and min(0.368*-1, 0.8*-1)=-0.8 -> mean=0.2 -> loss=-0.2
assert abs(float(loss.item()) - (-0.2)) < 1e-6
assert diag["clip_fraction"] == 1.0
ppo_res = run_ppo_policy_benchmark(seed=42)
assert ppo_res["return_gain"] > 2.0
assert ppo_res["final_expected_return"] > 4.5
assert ppo_res["final_kl_k3"] >= 0.0
def test_03_schulman_k3_kl_nonnegative_and_zero_at_identity() -> None:
"""Schulman k3 KL is strictly >= 0 everywhere, == 0 iff identical, and differentiable."""
rng = np.random.default_rng(7)
lp_a = rng.uniform(-5.0, -0.05, size=256)
lp_b = rng.uniform(-5.0, -0.05, size=256)
k3_diff = schulman_k3_kl_numpy(lp_a, lp_b)
k3_same = schulman_k3_kl_numpy(lp_a, lp_a)
assert float(np.min(k3_diff)) >= 0.0
assert float(np.max(np.abs(k3_same))) == 0.0
assert float(np.mean(k3_diff)) > 0.0
t_pol = torch.tensor(lp_a, dtype=torch.float32, requires_grad=True)
t_ref = torch.tensor(lp_b, dtype=torch.float32)
k3_t = schulman_k3_kl(t_pol, t_ref)
assert float(k3_t.min().item()) >= 0.0
k3_t.mean().backward()
assert t_pol.grad is not None and bool(torch.isfinite(t_pol.grad).all().item())
def test_04_lora_zero_init_and_exact_merge_parity() -> None:
"""LoRALinear preserves base output at init, freezes base weights, and merges to <1e-5."""
audit = audit_lora_and_dora_merge_parity(in_features=128, out_features=128, rank=8, seed=42)
assert audit["lora_zero_init_diff"] < 1e-6
assert audit["lora_merge_max_diff"] < 1e-5
assert audit["lora_trainable_ratio"] < 0.15
base = nn.Linear(64, 64)
lora = LoRALinear(base, rank=4, alpha=8.0)
assert not lora.base.weight.requires_grad
assert lora.lora_a.requires_grad and lora.lora_b.requires_grad
def test_05_dora_magnitude_direction_decomposition_and_param_ratio() -> None:
"""DoRALinear decomposes magnitude & direction, merges exactly (<1e-5), and updates row norms."""
audit = audit_lora_and_dora_merge_parity(in_features=128, out_features=128, rank=8, seed=42)
assert audit["dora_zero_init_diff"] < 1e-5
assert audit["dora_merge_max_diff"] < 1e-5
assert audit["dora_trainable_params"] - audit["lora_trainable_params"] == 128
torch.manual_seed(9)
base = nn.Linear(32, 16, bias=False)
dora = DoRALinear(base, rank=4, alpha=8.0)
with torch.no_grad():
dora.magnitude.fill_(2.5)
eff_norms = dora.effective_weight().norm(p=2, dim=1)
assert torch.allclose(eff_norms, torch.full_like(eff_norms, 2.5), atol=1e-5)
def test_06_qlora_nf4_quantization_roundtrip_and_vram_accounting() -> None:
"""NF4 beats uniform INT4 in SNR; 70B QLoRA fits single 80GB GPU; GRPO cuts 50% VRAM vs PPO."""
nf4 = audit_nf4_quantization_roundtrip(shape=(256, 256), block_size=64, seed=42)
assert nf4["nf4_snr_db"] > nf4["uniform_int4_snr_db"]
assert nf4["nf4_rmse"] < nf4["uniform_int4_rmse"]
assert nf4["compression_vs_bf16"] > 3.8
v7b = compute_peft_vram_budget(
PEFTMemoryConfig(model_name="7B", total_params_b=7.0, n_layers=32, d_model=4096, d_ff=11008)
)
v70b = compute_peft_vram_budget(
PEFTMemoryConfig(model_name="70B", total_params_b=70.0, n_layers=80, d_model=8192, d_ff=28672)
)
assert v7b["full_ft_static_gb"] == pytest.approx(112.0, rel=1e-3)
assert v70b["full_ft_static_gb"] == pytest.approx(1120.0, rel=1e-3)
assert v70b["fits_single_80gb_gpu_qlora"] is True
assert v70b["fits_single_80gb_gpu_full_ft"] is False
assert v70b["qlora_vs_full_ft_reduction_x"] > 20.0
pt7 = compute_post_training_vram_comparison(total_params_b=7.0)
assert pt7["grpo_vs_ppo_vram_saving_pct"] == pytest.approx(50.0, abs=1e-6)
def test_07_tiny_llm_causal_masking_invariant() -> None:
"""Mutating future tokens t > i must have zero effect on logits at position i."""
torch.manual_seed(11)
vocab = ArithmeticVocab()
model = TinyModernDecoderLM(TinyLLMConfig(vocab_size=vocab.size)).eval()
seq_a = torch.tensor([[1, 13, 3, 5, 3, 7, 15, 16, 4, 5, 17, 2]], dtype=torch.long)
seq_b = seq_a.clone()
seq_b[0, 6:] = torch.tensor([18, 19, 20, 21, 22, 23], dtype=torch.long)
with torch.no_grad():
logits_a = model(seq_a)
logits_b = model(seq_b)
prefix_diff = float((logits_a[:, :6, :] - logits_b[:, :6, :]).abs().max().item())
suffix_diff = float((logits_a[:, 6:, :] - logits_b[:, 6:, :]).abs().max().item())
assert prefix_diff < 1e-6
assert suffix_diff > 1e-3
def test_08_stage1_pretrain_perplexity_drop(shared_pretrained_bundle: dict[str, object]) -> None:
"""Stage 1 Causal LM pre-training sharply reduces held-out perplexity (>5x)."""
stats = shared_pretrained_bundle["pretrain_stats"]
assert isinstance(stats, dict)
assert stats["init_eval_ppl"] > 20.0
assert stats["final_eval_ppl"] < 3.5
assert stats["ppl_reduction_factor"] > 5.0
def test_09_stage2_sft_prompt_masking_and_lora_dora_lift(
shared_pretrained_bundle: dict[str, object],
) -> None:
"""Stage 2 Prompt-masked SFT beats unmasked SFT on response NLL and lifts accuracy with LoRA/DoRA."""
vocab = shared_pretrained_bundle["vocab"]
train = shared_pretrained_bundle["train"]
eval_s = shared_pretrained_bundle["eval"]
base = shared_pretrained_bundle["base_model"]
assert isinstance(vocab, ArithmeticVocab)
assert isinstance(train, list) and isinstance(eval_s, list)
assert isinstance(base, TinyModernDecoderLM)
_, lora_masked = sft_with_peft(
base,
train,
eval_s,
vocab,
method="lora",
rank=6,
alpha=12.0,
mask_prompt=True,
steps=35,
lr=6e-3,
seed=42,
)
_, lora_unmasked = sft_with_peft(
base,
train,
eval_s,
vocab,
method="lora",
rank=6,
alpha=12.0,
mask_prompt=False,
steps=35,
lr=6e-3,
seed=42,
)
_, dora_masked = sft_with_peft(
base,
train,
eval_s,
vocab,
method="dora",
rank=6,
alpha=12.0,
mask_prompt=True,
steps=35,
lr=6e-3,
seed=42,
)
assert lora_masked["final_response_nll"] < lora_unmasked["final_response_nll"]
assert lora_masked["after_eval"]["exact_accuracy"] > lora_masked["before_eval"]["exact_accuracy"] + 0.30
assert dora_masked["after_eval"]["exact_accuracy"] >= 0.80
assert dora_masked["trainable_params"] > lora_masked["trainable_params"]
def test_10_constitutional_ai_critique_revise_pair_generator(
shared_pretrained_bundle: dict[str, object],
) -> None:
"""Constitutional AI synthesizer detects forbidden violations on rejected & yields clean chosen."""
eval_s = shared_pretrained_bundle["eval"]
assert isinstance(eval_s, list)
pairs, principles = generate_constitutional_pairs(eval_s)
assert len(pairs) == len(eval_s)
assert len(principles) == 2
forbidden = {tok for p in principles for tok in p.forbidden_tokens}
for pair in pairs:
assert len(pair["critique_detected"]) >= 1
assert any(tok in forbidden for tok in pair["rejected_tokens"])
assert not any(tok in forbidden for tok in pair["chosen_tokens"])
ver_chosen = verify_arithmetic_completion(pair["prompt_tokens"], pair["chosen_tokens"])
ver_rejected = verify_arithmetic_completion(pair["prompt_tokens"], pair["rejected_tokens"])
assert ver_chosen["reward"] == 1.0
assert ver_rejected["reward"] < 1.0
def test_11_stage3_dpo_reward_margin_and_preference_accuracy_gain(
shared_pretrained_bundle: dict[str, object],
) -> None:
"""Stage 3 DPO raises preference accuracy >=90% and implicit reward margin with bounded KL."""
vocab = shared_pretrained_bundle["vocab"]
train = shared_pretrained_bundle["train"]
eval_s = shared_pretrained_bundle["eval"]
base = shared_pretrained_bundle["base_model"]
assert isinstance(vocab, ArithmeticVocab)
assert isinstance(train, list) and isinstance(eval_s, list)
assert isinstance(base, TinyModernDecoderLM)
sft_model, _ = sft_with_peft(
base,
train,
eval_s,
vocab,
method="lora",
rank=6,
alpha=12.0,
mask_prompt=True,
steps=20,
lr=6e-3,
seed=42,
)
train_pairs, _ = generate_constitutional_pairs(train)
eval_pairs, _ = generate_constitutional_pairs(eval_s)
_, dpo_stats = align_with_dpo(
sft_model, train_pairs, eval_pairs, vocab, beta=0.25, steps=18, seed=42
)
assert dpo_stats["after_eval"]["preference_accuracy"] >= 0.90
assert dpo_stats["margin_gain"] > 1.0
assert dpo_stats["after_eval"]["chosen_kl_k3"] >= 0.0
assert dpo_stats["after_eval"]["chosen_kl_k3"] < 2.0
def test_12_grpo_group_advantage_zero_mean_unit_std_and_homogeneous_guard() -> None:
"""GRPO advantages have zero mean, ~unit std on diverse rewards, and 0 on homogeneous groups."""
diverse = np.array([1.0, 1.0, 0.25, 0.0, 0.25, 1.0, 0.0, 0.25], dtype=np.float64)
adv = compute_group_relative_advantages(diverse)
assert abs(float(np.mean(adv))) < 1e-12
assert abs(float(np.std(adv)) - 1.0) < 1e-6
all_same = np.array([1.0, 1.0, 1.0, 1.0, 1.0, 1.0], dtype=np.float64)
adv_zero = compute_group_relative_advantages(all_same)
assert np.allclose(adv_zero, 0.0)
def test_13_deterministic_rlvr_arithmetic_verifier_contract() -> None:
"""RLVR deterministic verifier strictly rewards exact answer+format and rejects errors."""
prompt = ["<BOS>", "SYS", "USER", "TASK", "ADD", "7", "8", "=>"]
perfect = verify_arithmetic_completion(prompt, ["ANS:", "1", "5", "OK", "<EOS>"])
wrong_num = verify_arithmetic_completion(prompt, ["ANS:", "1", "4", "OK", "<EOS>"])
bad_fmt = verify_arithmetic_completion(prompt, ["UMM", "VERBOSE", "1", "5", "ERR", "<EOS>"])
assert perfect["exact_match"] is True and perfect["reward"] == 1.0
assert wrong_num["exact_match"] is False and wrong_num["format_ok"] is True
assert wrong_num["reward"] == pytest.approx(0.25)
assert bad_fmt["exact_match"] is False and bad_fmt["reward"] == 0.0
def test_14_stage4_grpo_rlvr_verifiable_accuracy_lift_bounded_kl(
shared_pretrained_bundle: dict[str, object],
) -> None:
"""Stage 4 Critic-free GRPO + RLVR lifts verifiable accuracy over SFT with bounded k3 KL."""
vocab = shared_pretrained_bundle["vocab"]
train = shared_pretrained_bundle["train"]
eval_s = shared_pretrained_bundle["eval"]
base = shared_pretrained_bundle["base_model"]
assert isinstance(vocab, ArithmeticVocab)
assert isinstance(train, list) and isinstance(eval_s, list)
assert isinstance(base, TinyModernDecoderLM)
sft_seed, _ = sft_with_peft(
base,
train[:24],
eval_s,
vocab,
method="lora",
rank=6,
alpha=12.0,
mask_prompt=True,
steps=10,
lr=4.0e-3,
seed=49,
)
_, grpo_stats = posttrain_with_grpo_rlvr(
sft_seed,
train,
eval_s,
vocab,
group_size=8,
steps=36,
clip_eps=0.2,
kl_beta=0.02,
lr=2.5e-3,
temperature=0.95,
seed=42,
)
assert grpo_stats["eval_accuracy_lift"] >= 0.15
assert grpo_stats["after_eval"]["exact_accuracy"] > grpo_stats["before_eval"]["exact_accuracy"]
assert 0.0 <= grpo_stats["final_kl_k3"] < 2.0
def test_15_safetensors_checkpoint_roundtrip_zero_pickle(tmp_path: Path) -> None:
"""Safetensors save/load round-trips TinyModernDecoderLM with exact 0.0 logit difference."""
torch.manual_seed(123)
vocab = ArithmeticVocab()
cfg = TinyLLMConfig(vocab_size=vocab.size)
m1 = TinyModernDecoderLM(cfg).eval()
m2 = TinyModernDecoderLM(cfg).eval()
ckpt = save_safetensors_checkpoint(m1, tmp_path / "model.safetensors")
load_safetensors_checkpoint(m2, ckpt)
probe = torch.randint(0, vocab.size, (4, 10))
with torch.no_grad():
diff = float((m1(probe) - m2(probe)).abs().max().item())
assert diff == 0.0
def test_16_cli_demo_workbench_json_schema_and_ast_deserialization_guard(tmp_path: Path) -> None:
"""CLI --quick exports valid workbench_panels (6 KPI, 4 bars, 4 tables) & AST guard passes."""
out_json = tmp_path / "lab12_quick.json"
proc = subprocess.run(
[
sys.executable,
str(LAB_ROOT / "scripts" / "run_lab_demo.py"),
"--quick",
"--output",
str(out_json),
],
capture_output=True,
text=True,
check=True,
)
assert "Ch 21 + Lab 12" in proc.stdout
data = json.loads(out_json.read_text(encoding="utf-8"))
panels = data["workbench_panels"]
assert len(panels["kpis"]) == 6
assert len(panels["bars"]) == 4
assert len(panels["tables"]) == 4
# AST security guard across src/, scripts/, tests/
py_files = [
p
for sub in ("src", "scripts", "tests")
for p in (LAB_ROOT / sub).rglob("*.py")
]
assert len(py_files) >= 4
for py_file in py_files:
tree = ast.parse(py_file.read_text(encoding="utf-8"), filename=str(py_file))
for node in ast.walk(tree):
if isinstance(node, ast.Import):
for alias in node.names:
assert alias.name.split(".")[0] not in BANNED_DESERIALIZERS
elif isinstance(node, ast.ImportFrom) and node.module:
assert node.module.split(".")[0] not in BANNED_DESERIALIZERS
Lab 12, Test 02), vì sao trừ đường cơ sở \(b(s_t)\) trong REINFORCE không làm chệch kỳ vọng gradient và hai giới hạn \(\lambda = 0\) vs \(\lambda = 1\) của GAE tương ứng với ước lượng nào?Test 02 kiểm chứng chính xác cả hai giới hạn GAE tới 1e-12.
PPO \(L^{\text{CLIP}}(\theta) = \mathbb{E}_t[\min(\rho_t\hat{A}_t,\;\operatorname{clip}(\rho_t, 1-\epsilon, 1+\epsilon)\hat{A}_t)]\) (Lab 12, Test 02), phép lấy \(\min\) hoạt động như thế nào?Test 02, tại \(\epsilon = 0.2\) với \(\rho = [e^1, e^{-1}]\) và \(\hat{A} = [+1, -1]\), phép \(\min\) kẹp chính xác hai nhánh về +1.2 và -0.8 (clip_fraction = 1.0), giữ bước cập nhật ổn định trong vùng tin cậy.
AdamW hỗn hợp và kết quả đo trên Lab 12 (Test 06), so sánh nào giữa Full FT và QLoRA (NF4 + Double Quantization) cho mô hình 70B (r = 16, seq = 2048) là CHÍNH XÁC?NF4 đặt 16 mức tại các phân vị đồng xác suất của \(\mathcal{N}(0,1)\) (dày đặc quanh 0), tăng +1.34 dB SNR so với INT4 đồng đều và kết hợp Double Quantization đưa tổng VRAM 70B xuống 43.3 GB.
LoRALinear và DoRALinear trong Lab 12 (Tests 04, 05, 09), nhận định nào ĐÚNG?A và B bằng 0 thì đạo hàm theo A và B đều triệt tiêu! LoRA khởi tạo A Kaiming, B = 0; DoRA tách biên độ m = ||W_0||_c khỏi hướng chuẩn hóa và cả hai đều gộp thành một ma trận tuyến tính duy nhất ở pha suy luận.
SFT trên TinyModernDecoderLM (Lab 12, Test 09), vì sao bắt buộc gán ignore_index = -100 trên toàn bộ token thuộc prompt?targets trên vị trí prompt chỉ tắt đạo hàm mất mát lên prompt trong khi cơ chế Self-Attention vẫn đọc trọn vẹn prompt để dự đoán phản hồi, tập trung 100% dung lượng adapter vào lời giải.
DPO và hiện tượng Likelihood Displacement (Lab 12, Test 11), phát biểu nào CHÍNH XÁC?DPO. Theo dõi đồng thời chosen_mean_logp (-0.0338 -> -0.0377) kết hợp neo NLL nhỏ ngăn chặn triệt để Likelihood Displacement.
Constitutional AI & RLAIF (Anthropic, cài đặt mô phỏng tại Lab 12, Test 10) giải quyết nút thắt nào của RLHF truyền thống?Test 10, bộ phê bình Hiến pháp (C1-SAFE, C2-CONCISE) tự động phát hiện token vi phạm (UNSAFE, ERR, UMM, VERBOSE) trên rejected và tổng hợp cặp ưu tiên với chosen đạt điểm kiểm chứng 1.0.
GRPO + RLVR và bộ ước lượng Schulman k3 KL (Lab 12, Tests 03, 12, 13, 14), kết luận kỹ thuật nào ĐÚNG?0 tại \(u=1\) và \(\mathbb{E}_{\pi_\theta}[u-1]=0\) nên k3 vừa không âm tuyệt đối vừa không chệch; kết hợp với RLVR tất định giúp GRPO nâng mạnh năng lực suy luận không cần Critic.
Hướng dẫn & Gợi ý Từng bước cho 6 Bài tập Trụ cột 5
Bài tập 1 — Chứng minh Baseline Không chệch, GAE(lambda) & Kẹp Bi quan PPO 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Viết kỳ vọng theo phân phối \(\pi_\theta(a_t \mid s_t)\), rút \(b(s_t)\) ra ngoài tổng theo \(a_t\) và sử dụng đẳng thức \(\sum_a \pi_\theta(a\mid s) = 1\).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Thay trực tiếp \(\lambda = 0\) và \(\lambda = 1\) vào tổng lũy thừa \(\sum_{l} (\gamma\lambda)^l \delta_{t+l}\), rồi kiểm chứng trên compute_gae_advantages và ppo_clipped_surrogate_loss (Test 02).
Tiêu chí Đáp án & Số đối chứng
Đạo hàm của tổng xác suất bằng 0 chứng tỏ Baseline không chệch; GAE khớp chính xác TD(0) và MC tới 1e-12; PPO kẹp hai nhánh về +1.2 / -0.8 ở \(\epsilon = 0.2\) và nâng lợi nhuận MDP từ 1.31 lên 5.65 (tối ưu 6.00).
Bài tập 2 — Chứng minh Tính Không âm & Không chệch của Schulman k3 KL 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Đặt \(u = \pi_{\text{ref}}/\pi_\theta > 0\), tính đạo hàm bậc 1 và bậc 2 của \(f(u) = u - \ln u - 1\) để xác định cực tiểu toàn cục.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Tính riêng \(\mathbb{E}_{a\sim\pi_\theta}[u - 1]\) bằng định nghĩa kỳ vọng rời rạc rồi đối chiếu trên schulman_k3_kl (Test 03).
Tiêu chí Đáp án & Số đối chứng
\(f'(u)=1-1/u=0\iff u=1\), \(f''(u)=1/u^2>0\implies f(u)\ge f(1)=0\); đồng thời \(\mathbb{E}_{\pi_\theta}[u-1]=\sum_a \pi_{\text{ref}}(a)-1=0\), nên \(\mathbb{E}[k_3]=D_{\text{KL}}(\pi_\theta\|\pi_{\text{ref}})\) không chệch và không âm tuyệt đối.
Bài tập 3 — Kế toán VRAM 70B, Triển khai LoRA/DoRA Merge & Lượng tử hóa NF4 20%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Cộng 5 thành phần trạng thái tĩnh của AdamW hỗn hợp (2+2+4+4+4 = 16 B/param), sau đó tính số bit hiệu dụng 4 + 8/B + 32/(256*B) của NF4 + Double Quantization.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Kiểm tra khởi tạo 0 và phép gộp trọng số của LoRALinear, DoRALinear, cùng so sánh SNR của nf4_quantize_blockwise với INT4 đồng đều (Tests 04, 05, 06).
Tiêu chí Đáp án & Số đối chứng
Mô hình 70B: Full FT = 1,123.6 GB, LoRA = 147.2 GB, DoRA = 147.4 GB, QLoRA NF4 = 43.3 GB (25.9x cut, vừa 1x 80GB); NF4 đạt 20.69 dB SNR (+1.34 dB hơn INT4); sai số merge LoRA = 1.07e-06, DoRA = 0.00e+00.
Bài tập 4 — Dẫn xuất Đóng DPO, Chẩn đoán Likelihood Displacement & Constitutional AI 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Biểu diễn hàm mục tiêu RLHF dưới dạng \(-D_{\text{KL}}(\pi\|\pi^*) + \log Z(x)\) với \(\pi^*(y|x) = \frac{1}{Z(x)}\pi_{\text{ref}}(y|x)\exp(r(x,y)/\beta)\), rồi giải rút \(r(x,y)\).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Thay hiệu \(r(x,y_w) - r(x,y_l)\) vào hàm mất mát Bradley–Terry, kiểm chứng generate_constitutional_pairs và align_with_dpo (Tests 10, 11).
Tiêu chí Đáp án & Số đối chứng
Hằng số \(\beta\log Z(x)\) triệt tiêu chính xác khi lấy hiệu ưu tiên; thêm neo NLL 0.05 giữ ổn định chosen_mean_logp (-0.0338 -> -0.0377) trong khi đẩy preference_accuracy từ 50.0% lên 100.0% (margin = +9.40, k3 KL = 0.0003).
Bài tập 5 — Vòng đời 4 Chặng LLM: Pre-Train -> Prompt-Masked SFT -> GRPO + RLVR 20%
Gợi ý Bước 1 (Định hướng Nguyên lý)
So sánh mask_prompt=True vs mask_prompt=False trong sft_with_peft để thấy ảnh hưởng của 3 token tiêu đề ngữ cảnh biến thiên lên dung lượng adapter rank = 6.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Phân tích trường hợp \(\sigma_G = 0\) trong compute_group_relative_advantages và theo dõi posttrain_with_grpo_rlvr trên Cold-Start SFT (Tests 08, 09, 12, 13, 14).
Tiêu chí Đáp án & Số đối chứng
Pre-Train giảm PPL 11.6x (31.11 -> 2.69); Prompt-Masked SFT cắt Response NLL 3.5x (0.117 -> 0.034, DoRA 0.027 / 100% acc); GRPO + RLVR (G=8) nâng độ chính xác held-out từ 40.6% lên 71.9% (+31.2pp, k3 KL = 0.1104).
Bài tập 6 — An toàn Lưu trữ Safetensors & Nghiệm thu Trọn gói Lab 12 (16/16 Pytest) 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Thay đổi các token ở vị trí \(t > i\) để kiểm chứng bất biến mặt nạ nhân quả của TinyModernDecoderLM (Test 07), sau đó gộp adapter và lưu/nạp bằng safetensors (Test 15).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy trọn bộ scripts/run_lab_demo.py, ruff check, mypy src, và pytest -p no:cacheprovider -v kiểm định cổng AST cấm pickle (Test 16).
Tiêu chí Đáp án & Số đối chứng
Đạt 16/16 pytest (0 skips), 0 lỗi ruff/mypy, sai số mặt nạ nhân quả < 1e-6, sai số khôi phục safetensors == 0.0, và xuất artifacts/ch21_lab12_results.json đủ 6 KPI, 4 bar, 4 bảng.