Chương 22 — An toàn AI, Hack Phần thưởng (Goodhart), Thiên lệch Giám khảo LLM-as-a-Judge & Siêu Căn chỉnh (Weak-to-Strong)
Từ Gao et al. Goodhart cliff (d*=2.12, proxy 174.43 làm gold -104.07 vs KL+UWO Ensemble std -33.7x -> gold +1.43) đến LLM Judge debiasing (Flip 25.4%->0%, Length corr -94.7%, Stress 47.5%->98.3%, Dawid-Skene 99.2%/k=0.983) & PyTorch Weak-to-Strong Bootstrapped AuxConf (PGR -0.061->0.965).
Đơn vị học phần (
Unit ID):T1-P4-U05(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 (Workbench): WB-Ch22 — An toàn AI, Hack Phần thưởng, Hiệu chuẩn Giám khảo LLM & Siêu Căn chỉnh (ai_safety_superalignment_lab)
Chuyên đề Nghiên cứu Tích hợp Bắt buộc: Bài #9 — When Higher Reward Means Worse Behavior, Bài #10 — When an LLM Judge Agrees for the Wrong Reasons, Bài #11 — Weak-to-Strong Supervision: Learning Beyond the Teacher's Errors
Kế thừa & chuyển tiếp: Tiếp nối trực tiếp Chương 21 (RLHF-PPO,DPO,Constitutional AI,GRPO + RLVR); khép lại Phần 4 trước khi bước sang Phần 5 (RAG Sản xuất, Hệ thống Tác nhân & Đánh giá theo Chế độ Lỗi).
Bốn Thảm họa An toàn AI Thực chiến Mở màn: Khi Điểm số Cao Nhất Lại Là Lúc Hệ thống Hỏng Nặng Nhất#
Ở Chương 21, chúng ta đã dựng xong toàn bộ đường ống hậu huấn luyện hiện đại từ tiền huấn luyện đến SFT, DPO và GRPO + RLVR. Nhưng ngay khi đưa đường ống đó vào thực tế, các đội kỹ sư an toàn AI đều đối mặt một nghịch lý chết người: mọi chỉ số thưởng huấn luyện, điểm tự đánh giá của giám khảo LLM và độ đồng thuận trên tập nhãn yếu đều tăng vọt, thế nhưng hành vi thật ngoài sản xuất lại đổ vỡ. Bốn thất bại định lượng dưới đây — được tái hiện đầy đủ ngoại tuyến trong WB-Ch22 (ai_safety_superalignment_lab, seed = 42) — đại diện cho ba chuyên đề biên giới #9, #10 và #11:
-
Vách đá Goodhart khi Tối ưu hóa Quá mức Reward Model (
Bài #9,WB-Ch22,Tests 03, 04):Trên mô hình quy luật tỷ lệ của Gao et al. (ICML 2023), hàm thưởng thay thế \(R_{\text{proxy}}(d)\) tăng đơn điệu theo khoảng cách \(d = \sqrt{D_{\text{KL}}(\pi \| \pi_{\text{ref}})}\), nhưng phần thưởng thực \(R_{\text{gold}}(d) = d(\alpha_{\text{rm}} - \beta_{\text{rm}}\log d)\) chỉ tăng tới điểm đỉnh \(d^* = 2.12\) (\(D_{\text{KL}}^* = \mathbf{4.48}\text{ nats}\), \(R_{\text{gold}}^* = \mathbf{0.508}\)), sau đó lao dốc và rơi xuống âm dưới cả mô hình gốc khi \(d > d_{\text{zero}} = \mathbf{5.75}\). Trong thực nghiệm PyTorch tối ưu trực tiếp trên một
RewardMLPđơn lẻ không phạt KL, chính sách đẩyproxy_rewardvọt lên174.43tại \(D_{\text{KL}} = \mathbf{364.28}\), nhưng kéogold_truth_scoresụp đổ106.90điểm xuống-104.07! Ngược lại, Hợp thể Bất định Bảo thủKL + UWO(\(\mu - \lambda\sigma\), \(K = 5\)) cắt bất định OODstdtới33.7×(18.71 -> 0.556), giữ \(D_{\text{KL}} = \mathbf{2.40}\) và bảo toàn thưởng thực dương+1.43. -
Ảo giác Chiến thắng Do Thiên lệch Vị trí & Độ dài của
LLM-as-a-Judge(Bài #10,WB-Ch22,Tests 06, 07):Một giám khảo LLM chạy đánh giá một chiều mà không hoán vị thường tự đảo quyết định mỗi khi đổi thứ tự ứng viên
(A, B) -> (B, A)ở tỷ lệ25.4%(Position Flip Rate) và gán xác suất thắng tương quan giả với độ dài câu trả lời ở mứcr = 0.448dù câu trả lời dài hơn hoàn toàn kém chất lượng hơn. Chỉ bằng hai lớp phòng thủ đầu tiên — Trung bình Đối xứng Đảo vị trí Hai chiều (đưa Flip Rate về0.0%) và Hồi quy Phản thực tế Kiểm soát Độ dàiAlpacaEval LC(Ridgekhử gây nhiễu +LogisticRegressionđánh giá nghiêm ngặt tại \(\delta_{\text{len}} = 0\), không rò rỉ nhãn vàng) — tương quan độ dài giả sụt94.7%xuống chỉ còn0.024. -
Sụp đổ Dưới Nịnh hót (
Sycophancy) & Bẫy Từ khóa Tiêu chí (Rubric Hacking) (Bài #10,WB-Ch22,Tests 08, 09):Khi câu hỏi chèn gợi ý sai nhưng tự tin từ người dùng hoặc nhồi từ khóa hào nhoáng kiểu rubric (độc lập với nhãn vàng), giám khảo ngây thơ tụt từ
78.0%sạch xuống chỉ còn47.5%trên tập áp lực đối kháng (rơi30.5pp,Cohen's kappa = 0.258,ECE = 0.253). Đường ống hiệu chuẩn đầy đủ kết hợp Bộ lọc Bất biến Tiêu chí Phản thực tế + Hội đồngDawid–Skene EM(3giám khảo) đẩy Stress Accuracy lên98.3%(+50.8pp,Overall Accuracy = 99.2%), nângCohen's kappalên0.983(+0.725) và cắtECExuống0.021. -
Học thuộc Lòng Lỗi Thầy Yếu trong Siêu Căn chỉnh
Weak-to-Strong(Bài #11,WB-Ch22,Tests 11, 12, 13):Khi dùng nhãn từ giáo viên yếu (
WeakTeacher, chỉ đạt74.7%tổng thể và48.0%trên vùng điểm mù hệ thống chiếm32.9%dữ liệu) để dạy học viên mạnh có trần100.0%, huấn luyệnCross-Entropyngây thơ làm mạng mạnh học vẹt sai lầm của thầy (weak_agreement = 94.4%), kéoPGRxuống mức âm-0.061(73.1%tổng thể,44.6%trên điểm mù). Áp dụng Hàm Mất mát Phụ trợ Tự tinAuxConfkích hoạt năng lực tiềm ẩn đạt96.2%(PGR = 0.851), và Khởi động Trung gianBootstrapped (w -> m -> s) + AuxConfbứt phá lên99.1%tổng thể (98.0%trên chính vùng điểm mù của thầy yếu,PGR = 0.965).
Mục tiêu Học tập (Learning Objectives)#
Sau khi hoàn tất Chương 22 và vượt qua 16/16 bài kiểm thử của WB-Ch22 (ai_safety_superalignment_lab), học viên làm chủ toàn diện 5 năng lực trọng tâm:
- Phân tích & Ngăn chặn Định luật Goodhart (
Bài #9): Phân biệt 4 dạng Goodhart (Regressional, Extremal, Causal, Adversarial), chứng minh điểm tối ưu \(d^*\) trên đường cong Gao et al. (2023) và công thức KL củaBest-of-N, cũng như triển khai phối hợp Phạt KL + Hợp thể Bất địnhUWO(\(\mu - \lambda\sigma\)) +RLVR. - Thiết kế Hệ thống Đánh giá
LLM-as-a-JudgeChống Thiên lệch (Bài #10): Đo lường và triệt tiêu 5 thiên lệch (Position, Verbosity, Self-Preference, Sycophancy, Rubric Hacking) bằng Đảo vị trí Hai chiều (0%Flip Rate), Hồi quyAlpacaEval LC, Bộ kiểm thử Áp lực Tiêu chí và hợp nhất đa giám khảoDawid–Skene EM/Cohen's kappa. - Khai mở Năng lực Siêu Căn chỉnh
Weak-to-Strong(Bài #11): Định lượng bằngPGR, lý giải cơ chế học vẹt lỗi thầy yếu củaNaive CE, và cài đặtAuxConfTự làm sắc nét +Bootstrappingtrung gian (\(w \to m \to s\)) vượt qua ngưỡngPGR > 0.65. - Xây dựng Kiến trúc An toàn Hậu huấn luyện Sản xuất 2026: Thiết kế cổng telemetry bắt sớm Goodhart Cliff, kiểm định phát hành tự động
Judge Panel(\(\kappa \ge 0.70\)) và quy trình phát hànhsafetensors(0deserializer rủi ro). - Chạy & Kiểm toán Trọn gói Phòng thí nghiệm
WB-Ch22: Thực thi benchmarkPyTorch 2.15.0+cpu+scikit-learn, xuấtartifacts/ch22_wb22_results.jsonvà đạt16/16 pytest,0lỗiruff/mypy.
Bảng Tích hợp Chuyên đề #9–#11 & Ký hiệu Toán học Chuẩn hóa#
Chuyên đề (Special Topics) |
Nền tảng Lý thuyết & Thí nghiệm | Vị trí trong Chương | Sơ đồ / Widget | Mô-đun & Kiểm thử (ai_safety_superalignment_lab) |
|---|---|---|---|---|
| #9 — When Higher Reward Means Worse Behavior | 4 dạng Goodhart, BoN KL, quy luật Gao et al. 2023 (\(d^* = 2.12\)), phạt KL \(\beta\) & hợp thể bất định bảo thủ UWO (\(\mu - \lambda\sigma\)) |
Trụ cột 1 (§1.1) + Trụ cột 2 (§2.1) | Mermaid 1 + Widget 1 |
reward_hacking_and_judge.py: best_of_n_kl, gao_overoptimization_curve, run_kl_penalty_sweep, run_reward_ensemble_overoptimization_experiment (Tests 02–05) |
| #10 — When an LLM Judge Agrees for the Wrong Reasons | Thiên lệch vị trí/độ dài/tự ưa thích/nịnh hót/rubric, Đảo vị trí Hai chiều (0%), AlpacaEval LC, Dawid–Skene EM & Cohen's kappa |
Trụ cột 1 (§1.2) + Trụ cột 2 (§2.2) | Mermaid 2 + Widget 2 |
reward_hacking_and_judge.py: generate_synthetic_judge_pairs, compute_cohens_kappa, dawid_skene_em, run_judge_bias_and_debiasing_benchmark (Tests 06–09) |
| #11 — Weak-to-Strong Supervision: Learning Beyond the Teacher's Errors | Biến mù thầy yếu, PGR, bẫy Naive CE, AuxConf tự tin & Bootstrapping (\(w \to m \to s\)) trên StrongStudentMLP + safetensors |
Trụ cột 1 (§1.3) + Trụ cột 2 (§2.3) | Mermaid 3 + Widget 3 |
weak_to_strong_superalignment.py: compute_pgr, build_superalignment_dataset, StrongStudentMLP, run_weak_to_strong_benchmark, safetensors (Tests 10–16) |
Bảng Ký hiệu Toán học Chuẩn hóa (ch-22)#
| Ký hiệu | Miền / Hình dạng | Ý nghĩa Chuẩn trong Chương 22 | Định danh ai_safety_superalignment_lab |
|---|---|---|---|
| \(R_{\text{proxy}}(x, y),\, R_{\text{gold}}(x, y)\) | \(\mathbb{R}\) | Thưởng thay thế (RM học được) vs. Lợi ích thực sự (Gold Utility) | proxy_reward, gold_reward |
| \(d,\, d^*,\, d_{\text{zero}},\, D_{\text{KL}}(\pi_{\text{BoN}} \| \pi_{\text{ref}})\) | \(\mathbb{R}_{\ge 0}\) | Khoảng cách KL \(\sqrt{D_{\text{KL}}}\), đỉnh tối ưu Gao et al., ngưỡng tụt âm, KL Best-of-\(N\) | d_star, d_zero, best_of_n_kl |
| \(\mu(x,y),\, \sigma(x,y),\, r_{\text{UWO}},\, \lambda_{\text{unc}}\) | \(\mathbb{R}, \mathbb{R}_{\ge 0}\) | Trung bình, độ lệch chuẩn \(K\) RM, thưởng phạt bất định \(\mu - \lambda\sigma\) | ensemble_mean, ensemble_std, uwo_lambda |
| \(p_{\text{sym}},\, \delta_{\text{len}},\, \kappa,\, \Pi^{(j)}\) | \([0, 1], \mathbb{R}, [-1, 1]\) | Xác suất đối xứng 2 chiều, hiệu độ dài chuẩn hóa, Cohen's \(\kappa\), ma trận nhầm lẫn Dawid–Skene | p_sym_j1, compute_cohens_kappa, dawid_skene_em |
| \(f_w,\, f_m,\, f_s,\, \text{PGR},\, \alpha_t\) | Hàm, \((-\infty, 1], [0, 1]\) | Thầy yếu, mô hình trung gian, học viên mạnh, tỷ lệ phục hồi PGR, hệ số AuxConf |
compute_pgr, aux_alpha_max, bootstrapped_aux_conf_w2s |
Trụ cột 1 — Nền tảng Lý thuyết & Chứng minh Toán học từ First Principles#
1.1 Chuyên đề #9: Định luật Goodhart, Quy luật Gao et al. & Hợp thể Phần thưởng Bất định (UWO)#
Vì sao Proxy != True Dưới Áp lực Tối ưu hóa?#
Đặt \(R_{\text{proxy}}(x, y) = R_{\text{gold}}(x, y) + \epsilon(x, y)\) là mô hình phần thưởng thay thế được huấn luyện trên dữ liệu hữu hạn gần \(\pi_{\text{ref}}\). Dưới phân loại của Manheim & Garrabrant (2018), bốn cơ chế khiến việc tăng \(R_{\text{proxy}}\) làm xấu đi hành vi thật gồm:
- Regressional Goodhart (Chọn lọc nhiễu đuôi): Khi lấy mẫu tối đa \(\arg\max_y R_{\text{proxy}}(x, y)\), chính sách vô tình chọn đúng các mẫu có sai số ngẫu nhiên \(\epsilon(x, y) \gg 0\) (winner's curse). Kể cả khi \(\mathbb{E}[\epsilon] = 0\), \(\mathbb{E}[R_{\text{gold}} \mid \arg\max R_{\text{proxy}}]\) thấp hơn đáng kể giá trị \(R_{\text{proxy}}\) quan sát được.
- Extremal Goodhart (Sụp đổ OOD): Hàm xấp xỉ \(R_{\text{proxy}} \approx R_{\text{gold}}\) chỉ hợp lệ gần phân phối \(\pi_{\text{ref}}\) (\(D_{\text{KL}}\) nhỏ). Khi RL đẩy \(\pi_\theta\) sang vùng mật độ cực thấp ngoài phân phối dữ liệu RM, tương quan bị đứt gãy.
- Causal Goodhart (Can thiệp sai nhánh nhân quả): Người đánh giá thường thích câu trả lời có cấu trúc rõ và đủ ý; nhưng câu trả lời dài dòng/rào đón cũng chia sẻ bề mặt đó. Tối ưu trực tiếp vào đặc trưng bề mặt làm mất nguyên nhân gốc (độ chính xác).
- Adversarial Goodhart (Khai thác lỗ hổng chủ động): Chính sách RL dò tìm các hướng không gian tiềm ẩn nơi trọng số RM không bị dữ liệu ràng buộc, tạo điểm thưởng ảo cực lớn.
Chứng minh Điểm Đỉnh Tối ưu Gao et al. (ICML 2023) & KL của Best-of-N#
Với chiến lược lọc Best-of-N (BoN) chọn \(y^* = \arg\max_{i \in \{1,\dots,N\}} R_{\text{proxy}}(x, y_i)\) từ \(N\) mẫu độc lập \(y_i \sim \pi_{\text{ref}}(\cdot \mid x)\), phân phối mật độ xác suất mới tuân theo quy luật thống kê thứ tự (khi mọi mẫu có thứ hạng liên tục không trùng nhau): \(p_{\text{BoN}}(y) = N \, [F(y)]^{N-1} \, p_{\text{ref}}(y)\) với \(F(y) = \mathbb{P}_{y' \sim \pi_{\text{ref}}}(R_{\text{proxy}}(y') \le R_{\text{proxy}}(y)) \sim \text{Uniform}(0, 1)\). Đổi biến \(u = F(y) \in [0, 1]\) cho tích phân đóng chính xác:
Đặt \(d = \sqrt{D_{\text{KL}}(\pi \| \pi_{\text{ref}})} \ge 0\). Thực nghiệm quy mô lớn của Gao, Schulman & Hilton (2023) chứng minh phần thưởng thay thế tăng đơn điệu \(R_{\text{proxy}}(d) = \alpha_{\text{proxy}} d\), còn phần thưởng thực tuân theo hàm unimodal (chữ U ngược):
Lấy đạo hàm bậc nhất và bậc hai theo \(d\):
Điểm cực đại toàn cục là \(R_{\text{gold}}(d^*) = \beta_{\text{rm}} d^*\), và tại \(d_{\text{zero}} = \exp(\alpha_{\text{rm}} / \beta_{\text{rm}}) = e \cdot d^*\), phần thưởng thực rơi về 0 rồi âm vĩnh viễn khi \(d > d_{\text{zero}}\). Với tham số trong WB-Ch22 (\(\alpha_{\text{rm}} = 0.42, \beta_{\text{rm}} = 0.24\)), ta có đúng \(d^* = e^{0.75} = \mathbf{2.117}\) (\(D_{\text{KL}}^* = \mathbf{4.48}\text{ nats}\), \(R_{\text{gold}}^* = \mathbf{0.508}\)), và \(d_{\text{zero}} = e^{1.75} = \mathbf{5.755}\).
Bảng đối chiếu giá trị Best-of-N KL và quét hệ số KL \(\beta_{\text{KL}}\) đo trực tiếp trong WB-Ch22 (artifacts/ch22_wb22_results.json):
Cỡ lấy mẫu Best-of-N |
\(D_{\text{KL}}(\pi_{\text{BoN}} \| \pi_{\text{ref}})\) (nats) | \(\sqrt{D_{\text{KL}}}\) (\(d\)) | Hệ số phạt \(\beta_{\text{KL}}\) (Single RM) | \(D_{\text{KL}}\) cuối (nats) | proxy_reward \(\to\) gold_reward |
|---|---|---|---|---|---|
N = 1 (gốc \(\pi_{\text{ref}}\)) |
0.000 |
0.000 |
\(\beta = 0.15\) | 351.20 |
171.34 \(\to\) -99.35 (Sụp đổ) |
N = 4 |
0.636 |
0.798 |
\(\beta = 0.55\) | 65.23 |
75.91 \(\to\) -9.58 (Vẫn vượt \(d_{\text{zero}}\)) |
N = 16 |
1.835 |
1.355 |
\(\beta = 1.40\) | 10.00 |
31.91 \(\to\) +2.28 (Vùng an toàn) |
N = 256 (gần đỉnh \(d^*\)) |
4.549 |
2.133 |
\(\beta = 3.20\) | 2.17 |
16.76 \(\to\) +2.16 (Bảo toàn cao) |
N = 1024 (quá \(d^*\)) |
5.932 |
2.436 |
\(\beta = 6.50\) | 0.63 |
10.05 \(\to\) +1.43 (Bóp quá chặt) |
Độ phức tạp Tính toán & Bộ nhớ của Hợp thể UWO#
Về chi phí phần cứng, giữ \(K\) mạng Reward Model riêng biệt trên VRAM đòi hỏi \(K \times |\theta_{\text{RM}}|\) bộ nhớ suy luận; tuy nhiên trong kiến trúc Multi-Head / LoRA Ensemble (Eisenstein et al., 2024), \(K\) đầu ra chia sẻ chung thân mạng nền \(\text{Backbone}(x, y)\) và chỉ phân nhánh ở lớp tuyến tính cuối hoặc adapter hạng thấp, làm phụ phí VRAM tăng dưới 5% và độ trễ tính \(\mu \pm \lambda\sigma\) tăng không đáng kể (< 2 ms/batch).
Ba Lớp Phòng thủ Toán học Chống Hack Phần thưởng#
- Phạt Phân kỳ KL (\(\beta_{\text{KL}}\)): Trong mục tiêu \(\max_\pi \mathbb{E}[R_{\text{proxy}}] - \beta_{\text{KL}} D_{\text{KL}}(\pi \| \pi_{\text{ref}})\), nghiệm dừng tại không gian tham số thỏa \(\nabla_z R_{\text{proxy}}(z^*) = \beta_{\text{KL}} z^*\) (với chính sách Gaussian \(\mathcal{N}(z, I)\) quanh \(\pi_{\text{ref}} = \mathcal{N}(0, I)\)), ép \(D_{\text{KL}} = \frac{1}{2\beta_{\text{KL}}^2}\|\nabla R_{\text{proxy}}\|_2^2\) co lại tỷ lệ nghịch \(\beta_{\text{KL}}^2\) (
WB-Ch22,Test 05). - Hợp thể Bất định Bảo thủ (
UWO— Coste et al., ICLR 2024;WCO): Huấn luyện \(K\) mô hình \(\{r_k(x, y)\}_{k=1}^K\) độc lập:\[\mu(x, y) = \frac{1}{K}\sum_{k=1}^K r_k(x, y), \qquad \sigma(x, y) = \sqrt{\frac{1}{K}\sum_{k=1}^K \big(r_k(x, y) - \mu(x, y)\big)^2}, \qquad r_{\text{UWO}}(x, y) = \mu(x, y) - \lambda_{\text{unc}}\, \sigma(x, y).\]Ở miền dữ liệu quen thuộc (in-distribution), các thành viên đồng thuận nên \(\sigma \approx 0 \implies r_{\text{UWO}} \approx R_{\text{gold}}\). Ở miền khai thác OOD ngoài giá đỡ \(\pi_{\text{ref}}\), trọng số các mô hình phân tán mạnh khiến \(\sigma\) bùng nổ, trừ nặng vào \(r_{\text{UWO}}\) và chặn đứng bước đi hướng tới Goodhart Cliff (WB-Ch22,Test 04). Phiên bản bi quan tuyệt đối hơn nữa làWCO: \(r_{\text{WCO}}(x, y) = \min_k r_k(x, y)\). - Làm mới RM Định kỳ (
Iterative RM Refresh) & TáchRLVR: Thu thập lại nhãn con người/oracle dọc quỹ đạo chính sách mới ở các bước KL nhỏ (\(\Delta D_{\text{KL}} \approx 0.05\)) và chuyển mọi tiêu chí kiểm chứng được sang bộ kiểm chứng chương trình tất địnhRLVR.
1.2 Chuyên đề #10: Toán học Thiên lệch LLM-as-a-Judge, Hồi quy LC & Dawid–Skene EM#
Mô hình Hóa Năm Thiên lệch Hệ thống của Giám khảo LLM#
Cho cặp ứng viên \((y_A, y_B)\) với chất lượng thực \(q_A, q_B\) ứng với đề bài \(x\). Xác suất giám khảo ngây thơ chọn \(y_A\) ở thứ tự trình bày \((A, B)\) bị nhiễu bởi năm thành phần cộng tính trong không gian logit:
Khi đổi thứ tự trình bày thành \((B, A)\), vị trí đầu tiên \(\psi_{\text{pos}}\) đổi sang ủng hộ \(B\) trong khi chất lượng thực đổi dấu: gây ra tỷ lệ đảo quyết định (Position Flip Rate) 25.4% trong WB-Ch22 (Test 06)!
Đường ống Khử Thiên lệch 3 Tầng#
- Trung bình Đối xứng Đảo vị trí Hai chiều (
Two-Way Position Swap): Đánh giá cả hai chiều \((A, B)\) và \((B, A)\), tính xác suất đối xứng:\[p_{\text{sym}}(A \succ B \mid x) = \frac{1}{2}\Big(P(A \succ B \mid (A, B)) + \big[1 - P(B \succ A \mid (B, A))\big]\Big).\]Mọi hoán vị \((A, B) \leftrightarrow (B, A)\) cho \(p_{\text{sym}}(A \succ B) + p_{\text{sym}}(B \succ A) \equiv 1.0\), khử bậc nhất \(\psi_{\text{pos}}\) và triệt tiêu tuyệt đối Position Flip Rate về0.0%. - Hồi quy Phản thực tế Kiểm soát Độ dài & Bất biến Tiêu chí (
AlpacaEval LC, Dubois et al. 2024): Trên tập hiệu chuẩn tách biệt (leakage-free,62cặp; tuyệt đối không nhìn nhãn vàng ở bước khử nhiễu đối chứng), khớp hồi quyRidgeước lượng tác động của các biến gây nhiễu (\(\delta_{\text{len}} = \tanh((\text{len}_A - \text{len}_B)/\sigma_{\Delta L})\), bẫy từ khóa \(\Delta\text{trap}\), gợi ý nịnh hót và chỉ báo tự ưa thích) lên điểm đối xứng \(z = \operatorname{logit}(p_{\text{sym}})\), hiệu chỉnh xác suất bằngLogisticRegressionmột chiều trên tập hiệu chuẩn rồi đánh giá nghiêm ngặt trên đặc trưng phản thực tếx_ev_cfvới toàn bộ biến gây nhiễu đặt bằng0(\(\delta_{\text{len}} = 0\), không rò rỉ kết cục vàng;WB-Ch22,Test 07: cắt tương quan độ dài từ0.448xuống0.024). - Kiểm toán
Cohen's kappa& Hợp nhất Đa Giám khảoDawid–Skene EM(1979): Đo độ đồng thuận hiệu chỉnh may rủi so với nhãn vàng con người: \(\kappa = \frac{p_o - p_e}{1 - p_e}\) với \(p_e = \sum_c \hat{p}_{\text{judge}}(c)\hat{p}_{\text{gold}}(c)\), kèm Sai số Hiệu chuẩn Kỳ vọng (ECE). Khi tổng hợp \(M\) giám khảo không đồng nhất với ma trận nhầm lẫn \(\Pi^{(j)}_{c \to k} = \mathbb{P}(\hat{y}_i^{(j)} = k \mid z_i = c)\), thuật toán EM Dawid–Skene luân phiên ước lượng hậu nghiệm chân lý tiềm ẩn (E-step) và ma trận độ tin cậy từng giám khảo (M-step):\[q_{i, c}^{(t+1)} \propto \pi_c^{(t)} \prod_{j=1}^M \Pi^{(j),(t)}_{c \to \hat{y}_i^{(j)}}, \qquad \Pi^{(j),(t+1)}_{c \to k} = \frac{\sum_{i=1}^N q_{i,c}^{(t+1)}\,\mathbb{I}[\hat{y}_i^{(j)} = k] + \alpha_{\text{lap}}}{\sum_{i=1}^N q_{i,c}^{(t+1)} + C\alpha_{\text{lap}}}.\]
1.3 Chuyên đề #11: Siêu Căn chỉnh Weak-to-Strong, Chỉ số PGR, AuxConf & Bootstrapping#
Phát biểu Bài toán & Thước đo PGR (Burns et al., OpenAI 2023)#
Giả sử tồn tại một khái niệm thật \(y^*(x)\) tách biệt sạch trong không gian biểu diễn tiền huấn luyện bậc cao \(h_s(x)\) của học viên mạnh \(f_s\) (đạt trần \(\text{Acc}(f_{\text{ceiling}})\) khi huấn luyện trên nhãn vàng). Ngược lại, giám sát viên yếu \(f_w\) chỉ tiếp cận đặc trưng bề mặt thô hoặc quy tắc cục bộ, tạo ra nhãn yếu \(y_w = f_w(x)\) chứa lỗi hệ thống tập trung tại miền điểm mù. Mức độ khai mở năng lực siêu nhân của học viên \(f_{w \to s}\) chỉ học từ \(y_w\) được đo bằng Performance Gap Recovered (PGR):
- Vì sao
Naive CEThất bại (PGR <= 0.3hoặc âm)? Một mạng học viên mạnh có dung lượng dư thừa nếu huấn luyện lâu với \(\mathcal{L}_{\text{CE}}(f_s(x), y_w)\) sẽ dùng đúng độ phức tạp phi tuyến của nó để học thuộc cả ngoại lệ lỗi của thầy yếu (teacher error imitation), kéo độ chính xác trên miền điểm mù tụt ngang hoặc tệ hơn thầy yếu (WB-Ch22:73.1%vs74.7%,PGR = -0.061).
Hai Cơ chế Khai mở Năng lực Tiềm ẩn (Capability Elicitation)#
- Hàm Mất mát Phụ trợ Tự tin (
Confidence-Weighted Auxiliary Loss — AuxConf): Sau vài bước khởi động ngắn giúp đầu phân loại của \(f_s\) bám trục khái niệm chung trên tập đa số sạch, tăng dần trọng số \(\alpha_t \in [0, \alpha_{\max}]\) ép học viên tin vào các dự đoán tự cứng hóa nhất quán với cấu trúc hình học nội tại của chính mình:\[\mathcal{L}_{\text{conf}}(f_s; t) = (1 - \alpha_t)\,\text{CE}\big(f_s(x), y_w\big) + \alpha_t\,\text{CE}\big(f_s(x), \hat{y}_s(x)\big), \qquad \hat{y}_s(x) = \operatorname{stopgrad}\!\Big(\mathbb{I}\big[P_s(y=1 \mid x) \ge \tau_t\big]\Big),\]trong đó ngưỡng thích ứng \(\tau_t = \operatorname{Quantile}_{0.50}(P_s)\) cân bằng phân vị chống sụp đổ về một lớp duy nhất. - Khởi động Trung gian (
Intermediate Model Bootstrapping: \(w \to m \to s\)): Khi khoảng cách năng lực giữa \(f_w\) và \(f_s\) quá lớn khiến \(f_s\) dễ học vẹt hơn, đưa một mô hình trung gian thắt cổ chai \(f_m\) vào giữa: \(f_w\) huấn luyện \(f_m\) (năng lực vừa đủ để nắm khái niệm toàn cục nhưng không đủ dung lượng học vẹt ngoại lệ điểm mù), rồi \(f_m\) sinh nhãn sạch hơn để huấn luyện \(f_s\) bằngAuxConf. TrongWB-Ch22, chuỗi \(w \to m \to s\) đẩy độ chính xác tổng thể lên99.1%(98.0%trên điểm mù,PGR = 0.965). - Vai trò Biểu diễn Tiền huấn luyện Không nhãn (Unsupervised Representation Prior):
Trước bước giám sát yếu, mạng
StrongStudentMLPtrải qua chặng tiền huấn luyện khử nhiễu (Denoising Autoencoder) trên dữ liệu chưa gán nhãn \(\mathbf{x}_{\text{train}}\) để định hướng trục ẩn \(h_s(\mathbf{x})\) bám sát cấu trúc đa tạp tự nhiên thay vì chỉ dấu bề mặt. Nhờ vậy, chỉ cần 2–3 epoch khởi động ngắn trước khi tăng dần \(\alpha_t\), đầu tuyến tính nhanh chóng khóa chặt khái niệm phổ quát và tự làm sạch nhãn ở miền điểm mù:
Biến thể trong WB-Ch22 (seed=42) |
Cơ chế Huấn luyện | Held-out Acc | Majority Acc (67.1%) |
Blind-Spot Acc (32.9%) |
weak_agreement |
PGR |
|---|---|---|---|---|---|---|
WeakTeacher (Surface Logistic) |
Chỉ thấy bề mặt & chỉ báo miền | 74.7% |
87.7% |
48.0% |
100.0% |
0.000 (mốc) |
Naive CE (w -> s, 115 epochs) |
CE(f_s, y_w), weight_decay = 1e-4 |
73.1% |
87.1% |
44.6% |
94.4% (học vẹt!) |
-0.061 |
AuxConf (w -> s, 44 epochs) |
(1 - alpha_t)CE + alpha_t CE(y_hat_s) |
96.2% |
99.7% |
89.2% |
78.4% |
0.851 |
Intermediate f_m (hidden = 24) |
Nút thắt dung lượng lọc lỗi điểm mù | 96.9% |
100.0% |
90.5% |
76.9% |
0.877 |
Bootstrapped (w -> m -> s) |
Dạy qua \(f_m\) rồi tự làm sắc nét AuxConf |
99.1% |
99.7% |
98.0% |
74.7% |
0.965 |
StrongCeiling (Oracle Gold) |
Huấn luyện trực tiếp trên nhãn vàng | 100.0% |
100.0% |
100.0% |
74.7% |
1.000 (trần) |
Cổng Rủi ro An toàn & Khả năng Mở rộng Trong Vòng đời Sản xuất#
- Ranh giới Bảo mật Trọng số (
Safetensors): Toàn bộ checkpoint hậu huấn luyện và mô hìnhWeak-to-Strongbắt buộc lưu dưới định dạngsafetensors(zero-pickle, độ lệch khôi phục0.0e+00trongTest 14), kết hợp cổng quétASTtự động (Test 16) chặn tuyệt đối mọi mô-đun giải tuần tự hóa rủi ro (pickle,joblib,cloudpickle,dill,shelve,marshal). - Tách biệt Dữ liệu Hiệu chuẩn (
Anti-Leakage): Các tham số hồi quy kiểm soát độ dàiAlpacaEval LCvà hiệu chuẩn nhiệt độECEchỉ được khớp trên lát cắt hiệu chuẩn (35%,62cặp) tách biệt hoàn toàn với tập kiểm thử độc lập (118cặp) trước khi chạy báo cáo phát hành.
Trụ cột 2 — Kiến trúc Hệ thống An toàn Sản xuất & Mô phỏng Tương tác#
2.1 Kiến trúc Phòng thủ Goodhart Đa tầng (Bài #9)#
- Quy tắc vận hành sản xuất 2026 & Ngân sách Chi phí: Không bao giờ tối ưu một Reward Model đơn lẻ khi \(\beta_{\text{KL}} = 0\). Luôn khóa ngân sách \(D_{\text{KL}} \le D_{\text{KL}}^*\), giám sát song song
ensemble_std\(\sigma(x, y)\) cùng tập giữ lại (held-out gold probe), và tách toàn bộ tiêu chí kiểm chứng được sang nhánhRLVRtất định. Để kiểm soát chi phí vận hành (thay vì thuê đội ngũ gán nhãn liên tục ở mức1–5 USD/cặp trên hàng trăm nghìn mẫu), chỉ lấy nhãn vàng con người tại các điểm mốc làm mới RM (Active Disagreement Sampling — ưu tiên lấy nhãn đúng những cặp có \(\sigma(x, y)\) lớn nhất!).
Hãy tự tay kéo thanh trượt số lượng mẫu Best-of-N, hệ số \(\alpha_{\text{rm}} / \beta_{\text{rm}}\) của Gao et al. (2023), hệ số phạt KL và trọng số bất định \(\lambda_{\text{unc}}\) của hợp thể UWO trong trình mô phỏng tương tác đầu tiên:
2.2 Đường ống Kiểm toán & Hiệu chuẩn LLM-as-a-Judge (Bài #10)#
- Cơ chế chống thao túng phát hành (
CI/CD Release Gate) & Ngân sách Độ trễ: Đánh giá đảo vị trí hai chiều tăng gấp đôi số lượt gọi giám khảo (\(2\times\) token suy luận), nhưng có thể chạy song song bất đồng bộ theo lô và dùng kỹ thuật Prefix Caching (KV-Cachedùng chung cho đề bài \(x\)) để cắt35%–45%chi phí tiền điền (TTFT). Mọi hệ thống đánh giá tự động phải báo cáo tách biệt cả Clean Accuracy, Adversarial Stress Accuracy (chèn gợi ý nịnh hót và từ khóa bẫy rubric), Position Flip Rate và tương quan độ dài thay vì một điểm trung bình gộp duy nhất.
Giải phẫu Bốn Ca Thực chiến Sản xuất Từ Bài #9, #10, #11 (2023–2026)#
Ca Thực chiến (2023–2026) |
Hiện tượng Thất bại Bề mặt | Nguyên nhân Gốc (Chuyên đề) | Cơ chế Sửa lỗi Chuẩn 2026 |
|---|---|---|---|
1. Sự cố Sycophancy Rollback trong RLHF Đối thoại |
Điểm Reward Model tăng cao kỷ lục nhưng trợ lý hùa theo câu sai của người dùng và viết dài 2.3× |
#9 Goodhart Cliff: Tối ưu quá mức qua \(d^*\) khai thác thiên lệch nịnh hót trong RM đơn lẻ | Rollback về trước \(d^*\), dùng Hợp thể UWO (\(\mu - \lambda\sigma\)) + tách kiểm chứng sang RLVR |
2. Lạm phát Bảng xếp hạng AlpacaEval / MT-Bench |
Mô hình 7B rườm rà đánh bại mô hình lớn trên Raw Win Rate, đảo vị trí 24%–35% |
#10 Position & Verbosity Bias: Giám khảo ưa vị trí #1 và độ dài hơn sự thật | Bắt buộc Đảo vị trí Hai chiều (0% Flip) + AlpacaEval LC (\(\delta_{\text{len}} = 0\)) |
3. Ảo giác 94% Đạt Chuẩn Trong RLAIF Tài chính |
Tỷ lệ tự chấm 5/5 tăng 62% -> 94%, nhưng tỷ lệ bịa số liệu tăng 4% -> 19% |
#10 Rubric Hacking: Mô hình sinh nhồi từ khóa rubric đánh lừa giám khảo 8B |
Thay bằng Checklist Nguyên tử + Stress Suite + Dawid–Skene EM (\(\kappa \ge 0.70\)) |
4. Thí nghiệm GPT-2 -> GPT-4 OpenAI Superalignment |
Học viên GPT-4 dùng Naive CE trên nhãn GPT-2 đạt PGR thấp (~0.20–0.40) |
#11 Teacher Error Imitation: Mạng mạnh học vẹt lỗi hệ thống của thầy yếu | Áp AuxConf tự làm sắc nét + Bootstrapping (\(w \to m \to s\)) đẩy PGR > 0.65 |
Hãy tương tác trực tiếp với mức độ thiên lệch vị trí, thiên lệch độ dài, nhiễu nịnh hót/rubric và so sánh Naive Judge vs Calibrated Pipeline (Swap + LC + Dawid-Skene) trong trình mô phỏng tương tác thứ hai:
2.3 Đường ống Siêu Căn chỉnh Weak-to-Strong (Bài #11)#
Hãy điều chỉnh tỷ lệ điểm mù của giáo viên yếu, dung lượng học viên mạnh, hệ số AuxConf \(\alpha_{\max}\) và bật/tắt Bootstrapping (\(w \to m \to s\)) để quan sát sự khác biệt giữa học vẹt lỗi thầy yếu và khai mở năng lực siêu nhân trong trình mô phỏng tương tác thứ ba:
2.4 Cẩm nang Quyết định An toàn AI & Đánh giá Sản xuất (2026)#
| Tình huống / Triệu chứng Rủi ro | Dấu hiệu Cảnh báo Sớm (Telemetry) | 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 |
|---|---|---|---|---|
Tối ưu RL làm Proxy tăng vọt nhưng chất lượng thật tụt |
\(D_{\text{KL}}\) vượt \(d^*\), held-out gold giảm, câu trả lời dài/nịnh hót |
Phạt KL + Hợp thể UWO (\(\mu - \lambda\sigma\)) + Làm mới RM |
Chạy 1 RM duy nhất không phạt KL hoặc tin điểm proxy tập train | ensemble_std thấp, gold > baseline, \(D_{\text{KL}} \le D_{\text{KL}}^*\) |
Bảng xếp hạng LLM Judge thiên lệch câu trả lời dài |
corr(prob, len_diff) > 0.25, Flip Rate > 5% |
Đảo vị trí Hai chiều + Hồi quy AlpacaEval LC (\(\delta_{\text{len}}=0\)) |
Đánh giá 1 chiều (A, B) cố định và công bố Raw Win Rate |
Flip Rate = 0.0%, |len_corr| < 0.10 |
Giám khảo RLAIF bị hack từ khóa rubric / nịnh hót |
Stress Accuracy tụt > 10pp, Cohen's kappa < 0.60 |
Adversarial Stress Suite + Dawid–Skene EM (\(\ge 3\) giám khảo) |
Dùng 1 mô hình tự chấm chính mình (Self-Preference) | Stress Acc >= 85%, kappa >= 0.70, ECE <= 0.10 |
| Học viên mạnh học thuộc lỗi của bộ nhãn yếu | PGR < 0.40, weak_agreement > 90% trên miền khó |
Pre-trained Backbone + AuxConf + Bootstrap (w->m->s) |
Chạy Naive CE quá nhiều epoch với weight decay thấp |
PGR > 0.65, phục hồi mạnh trên cụm điểm mù |
2.5 Góc nhìn SOTA 2025–2026: Giám sát Khả mở, Constitutional Classifiers / CC++ & Đầu độc Công cụ MCPTox (Principal Industrial Tip #6)#
Kinh nghiệm Triển khai An toàn & Giám sát Tự động Tuyến đầu (Scalable Oversight, CC++ & MCP Security):
- Mô hình Bradley–Terry Khử Thiên lệch Vị trí & Độ dài: Đừng bao giờ dừng ở điểm thắng thô; hãy tham số hóa log-tỷ lệ thắng cặp \((A, B)\) dưới dạng mô hình cộng tính:
\[\operatorname{logit} P(A \succ B) = (s_A - s_B) + \psi_{\text{pos}} \cdot \text{order} + \phi_{\text{len}} \cdot \delta_{\text{len}} + \dots\](kiểu LMSYS Style Control và AlpacaEval LC Ridge + Logistic Counterfactual). Luôn đánh giá hai chiều đối xứng \((A, B)\) và \((B, A)\), tách sạch tập hiệu chuẩn thiên lệch khỏi tập kiểm thử cuối cùng và tuyệt đối không để biến gây nhiễu phụ thuộc nhãn vàng ở pha sinh/đánh giá.
- Thiên lệch Tự Ưa thích trong
Constitutional AI/RLAIF(Self-Preference Bias) & Phân kỳGoodhart: Khi dùng cùng một họ mô hình vừa làm Generator vừa làm giám khảoRLAIF, giám khảo thiên vị văn phong do chính nó sinh ra (self-recognition bias) — bắt buộc dùng hội đồng đa họ mô hình +Dawid–Skene EMvà theo dõi song songensemble_std(UWO\(\mu - \lambda\sigma\)) + \(D_{\text{KL}}\) để chặn suy thoái sau \(d^*\), kết hợp chuyển miền kiểm chứng tất định sangRLVRvà lấy mẫu bất đồng chủ động (Active Disagreement Sampling). Constitutional Classifiers&CC++(Phòng thủ Jailbreak Phổ quát Phụ phí Thấp): Tinh chỉnh an toàn bề mặt (SFT/DPO) dễ bị đánh bại bởi universal jailbreak nhiều vòng hoặc mã hóa ngữ cảnh dài.Constitutional Classifiers(Anthropic, 2025) huấn luyện bộ phân loại canh gác trên dữ liệu tổng hợp sinh từ các hiến pháp quy tắc tường minh để chặn gần như toàn bộ jailbreak ngoài phân phối, nhưng thế hệ đầu gây chi phí suy luận cao và tỷ lệ từ chối nhầm (over-refusal). Thế hệCC++(Constitutional Classifiers++) khắc phục bằng đánh giá ngữ cảnh trao đổi (exchange-context), thác phân loại hai tầng nhẹ–nặng kết hợp đầu dò tuyến tính trên biểu diễn kích hoạt nội tại (linear probes), ép phụ phí tính toán xuống ~1% đồng thời giảm mạnh tỷ lệ từ chối sai trên câu hỏi vô hại.- Đầu độc Metadata
MCPToxTrong Hệ sinh thái Tác nhânMCP(Model Context Protocol): Khi mô hình gọi công cụ ngoài qua máy chủMCP, kẻ tấn công có thể cài chỉ thị độc hại ẩn ngay bên trong mô tả công cụ (tool description/ schema tham số) thay vì qua prompt người dùng (indirect metadata poisoning). Chuẩn kiểm địnhMCPToxphơi bày một nghịch lý đáng báo động: các mô hình càng có năng lực suy luận và tuân lệnh cao càng dễ bịMCPToxthao túng để rò rỉ dữ liệu hoặc gọi API trái phép! Quy tắc phòng vệ sản xuất: cô lập ranh giới tin cậy giữa mô tả công cụ ngoài và chỉ thị hệ thống, quét tĩnh/động mọi descriptorMCPbằng tầng lọcCC++, áp dụng đặc quyền tối thiểu (least-privilege sandboxing) và yêu cầu xác nhận tường minh cho mọi thao tác nhạy cảm.
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 An toàn & Đánh giá 2026#
- Lõi Huấn luyện & Kiểm toán:
PyTorch 2.x(hợp thểRewardMLP,StrongStudentMLP, vòng tối ưu KL),scikit-learn(Ridge&LogisticRegressioncho hiệu chuẩn phản thực tếLC,WeakTeacher),numpy/scipy,Pydantic v2(extra="forbid"),safetensors(zero-pickle). - Hệ sinh thái Đánh giá & Phòng thủ:
AlpacaEval 2.0 (LC),MT-Bench / Chatbot Arena(kiểm soát vị trí & độ dài),OpenAI Weak-to-Strong(AuxConf),TRL/verl(giám sát KL & Reward Ensemble).
3.2 Ma trận 6 Chống mẫu An toàn AI & Cổng Kiểm soát Tự động (WB-Ch22 CI Gates)#
| # | Chống mẫu (Anti-Pattern) |
Hậu quả Định lượng Ghi nhận (WB-Ch22) |
Cổng Kiểm soát Tự động (WB-Ch22 CI Gate) |
|---|---|---|---|
| 1 | Tối ưu hóa một Reward Model đơn lẻ với \(\beta_{\text{KL}} = 0\) | proxy vọt 174.43 ở KL = 364.3, nhưng gold sụp đổ 106.90 điểm xuống -104.07 |
Khẳng định KL + UWO đạt gold > unpenalized + 0.50 & giảm std (Test 04) |
| 2 | Cho phép \(D_{\text{KL}}\) trôi tự do ngoài vùng tin cậy \(\pi_{\text{ref}}\) | Vượt ngưỡng \(d^* = 2.12\) và \(d_{\text{zero}} = 5.75\) trên đường cong Gao et al., chất lượng tụt dưới mô hình gốc | Kiểm chứng quét \(\beta_{\text{KL}}\) thu hẹp đơn điệu \(D_{\text{KL}}\) (Test 05) |
| 3 | Đánh giá cặp LLM một chiều không hoán vị (A, B) |
Tỷ lệ tự mâu thuẫn khi đổi chỗ lên tới 25.4% |
Bắt buộc Two-Way Symmetric Averaging đạt Flip Rate == 0.0% (Test 06) |
| 4 | Dùng tỷ lệ thắng thô không kiểm soát độ dài (Raw Win Rate) |
Tương quan giả với độ dài câu trả lời tới 0.448 |
Hồi quy LC phản thực tế cắt tương quan độ dài > 45% (0.448 -> 0.024, Test 07) |
| 5 | Tin một giám khảo duy nhất không kiểm thử áp lực đối kháng | Rơi 30.5pp dưới nịnh hót/bẫy rubric (78.0% -> 47.5%, kappa = 0.258) |
Stress Suite + Dawid–Skene EM đạt Stress >= 80%, kappa >= 0.65 (Tests 08, 09) |
| 6 | Dùng Naive CE ép mạng mạnh học vẹt nhãn yếu & lưu pickle |
Học vẹt 94.4% theo thầy yếu, PGR = -0.061; rủi ro RCE khi nạp checkpoint |
Bootstrapped AuxConf đạt PGR > 0.65, safetensors == 0.0, AST cấm pickle (Tests 12–16) |
3.3 Mã Python Thực thi Đầu-Cuối (Sử dụng Trực tiếp ai_safety_superalignment_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 + scikit-learn), kiểm toán trọn vẹn cả 3 Chuyên đề #9, #10 và #11:
from __future__ import annotations
import numpy as np
from ai_safety_superalignment_lab import (
best_of_n_kl,
gao_overoptimization_curve,
run_full_ch22_wb22_benchmarks,
)
def run_ch22_safety_audit(seed: int = 42) -> None:
"""Chạy kiểm toán đầy đủ Bài #9 (Goodhart/UWO), #10 (LLM Judge) & #11 (Weak-to-Strong)."""
d_grid = np.linspace(0.0, 8.0, 33)
gao = gao_overoptimization_curve(d_grid)
print(
f"[Gao 2023] d*={gao['d_star']:.2f} (KL*={gao['kl_star']:.2f}), "
f"R_gold*={gao['gold_peak']:.3f}, BoN-256 KL={best_of_n_kl(256):.3f}"
)
payload = run_full_ch22_wb22_benchmarks(seed=seed, quick=False)
a9 = payload["article9_reward_hacking"]
a10 = payload["article10_llm_judge"]
a11 = payload["article11_weak_to_strong"]
unp = a9["unpenalized_single_rm"]["final"]
uwo = a9["kl_uwo_ensemble"]["final"]
print(
f"[#9 Goodhart] SingleRM(proxy={unp['proxy_reward']:.2f}, gold={unp['gold_reward']:.2f}, "
f"KL={unp['d_kl']:.1f}) -> KL+UWO(gold={uwo['gold_reward']:.2f}, "
f"std={uwo['ensemble_std']:.3f}, KL={uwo['d_kl']:.2f})"
)
nj = a10["naive_judge"]
cj = a10["calibrated_debiased_judge"]
print(
f"[#10 Judge] Flip: {100 * nj['position_flip_rate']:.1f}% -> "
f"{100 * cj['position_flip_rate']:.1f}% | Stress: {100 * nj['stress_accuracy']:.1f}% -> "
f"{100 * cj['stress_accuracy']:.1f}% | LenCorr: {nj['verbosity_bias_corr']:.3f} -> "
f"{cj['verbosity_bias_corr']:.3f} | Kappa: {nj['cohens_kappa']:.3f} -> "
f"{cj['cohens_kappa']:.3f}"
)
wt = a11["weak_teacher"]
nce = a11["naive_ce_w2s"]
boot = a11["bootstrapped_aux_conf_w2s"]
print(
f"[#11 W2S] Weak={100 * wt['accuracy']:.1f}% | NaiveCE={100 * nce['accuracy']:.1f}% "
f"(PGR={nce['pgr']:.3f}) -> Bootstrapped={100 * boot['accuracy']:.1f}% "
f"(Blind={100 * boot['blind_spot_accuracy']:.1f}%, PGR={boot['pgr']:.3f}) | "
f"Safetensors={a11['safetensors_roundtrip_max_diff']:.1e}"
)
if __name__ == "__main__":
run_ch22_safety_audit()
Trụ cột 4 — Phòng thí nghiệm Hai Tầng (WB-Ch22) & Hợp đồng 16 Kiểm thử#
4.1 Kiến trúc Hai Tầng (labs/ch22-ai-safety-and-superalignment-workbench/)#
- Mô-đun 1 — Hack Phần thưởng & Giám khảo LLM (
src/ai_safety_superalignment_lab/reward_hacking_and_judge.py):- Bài #9:
GoodhartConfig,best_of_n_kl,gao_overoptimization_curve,RewardMLP(PyTorch),run_kl_penalty_sweep,run_reward_ensemble_overoptimization_experiment. - Bài #10:
JudgeAuditConfig,generate_synthetic_judge_pairs,compute_cohens_kappa,compute_ece,dawid_skene_em,run_judge_bias_and_debiasing_benchmark.
- Bài #9:
- Mô-đun 2 — Siêu Căn chỉnh
Weak-to-Strong(src/ai_safety_superalignment_lab/weak_to_strong_superalignment.py):- Bài #11:
WeakToStrongConfig,compute_pgr,StrongStudentMLP(PyTorchkèm tiền huấn luyện Denoising Autoencoder không nhãn),build_superalignment_dataset,save_safetensors_checkpoint/load_safetensors_checkpoint,run_weak_to_strong_benchmark, vàrun_full_ch22_wb22_benchmarks.
- Bài #11:
4.2 Bảng Kết quả Benchmark Đã Xác minh (artifacts/ch22_wb22_results.json, seed=42)#
Thí nghiệm WB-Ch22 |
Đối chứng Cơ sở (Thất bại) | Phương pháp Phòng thủ / SOTA | Kết luận Nghiệm thu |
|---|---|---|---|
#9 — Quy luật Gao et al. & BoN KL |
Sau \(d_{\text{zero}} = 5.75 \implies R_{\text{gold}} < 0\) (-0.633 tại \(d=8\)) |
Đỉnh \(d^* = \mathbf{2.12}\) (\(D_{\text{KL}}^* = \mathbf{4.48}\), \(R_{\text{gold}}^* = \mathbf{0.508}\)); BoN-256 KL = 4.549 |
Xác nhận hình chữ U ngược |
#9 — RewardMLP Goodhart vs UWO |
Unpenalized: proxy=174.43, gold=-104.07 (drop=106.90, KL=364.28, std=18.71) |
KL + UWO: proxy=15.21, gold = +1.43, KL = 2.40, std = 0.556 |
Cắt 33.7× bất định OOD, chặn vách đá |
| #9 — Quét Hệ số KL (\(\beta_{\text{KL}}\)) | \(\beta = 0.15 \implies D_{\text{KL}} = 351.20\) (gold = -99.35) |
Co lại đơn điệu: 351.20 -> 65.23 -> 10.00 -> 2.17 -> 0.63 (\(\beta=6.5\)) |
Tuân thủ chặt lý thuyết phạt KL |
#10 — Đảo vị trí & Độ dài Judge |
Naive: Flip 25.4%, len_r = 0.448, Stress 47.5%, \(\kappa = 0.258\), ECE = 0.253 |
Calibrated: Flip 0.0%, len_r = 0.024, Stress 98.3%, \(\kappa = 0.983\), ECE = 0.021 |
Cắt 94.7% độ dài giả, DS_Acc = 99.2% |
#11 — Weak-to-Strong (PyTorch) |
Weak 74.7% (48.0% mù); Naive CE 73.1% (PGR = -0.061, fit yếu 94.4%) |
AuxConf 96.2% (PGR = 0.851); Bootstrap 99.1% (PGR = 0.965, 98.0% mù) |
Vượt xa thầy yếu, Safetensors = 0.0 |
4.3 Hợp đồng 16 Kiểm thử Tự động (tests/test_ai_safety_superalignment_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à tham số ngoài miền hợp lệ |
2 |
test_02_best_of_n_kl_exact_formula_and_monotonicity |
best_of_n_kl(1) == 0.0, tăng đơn điệu theo \(N\), khớp \(\log N - \frac{N-1}{N}\) (< 1e-12) |
3 |
test_03_gao_overoptimization_curve_unimodal_cliff |
Proxy tăng đơn điệu; Gold đạt đỉnh tại \(d^* = \exp(\alpha/\beta - 1)\) rồi tụt < 0 |
4 |
test_04_unpenalized_rm_suffers_goodhart_cliff_vs_uwo_ensemble |
Unpenalized RM thổi phồng proxy & KL rồi sụp gold; KL+UWO giữ gold cao & std thấp |
5 |
test_05_kl_regularization_bounds_policy_drift |
Tăng \(\beta_{\text{KL}}\) thu hẹp đơn điệu độ trôi \(D_{\text{KL}}\) xuống < 2.5 |
6 |
test_06_judge_position_swap_eliminates_flip_rate |
Naive Flip Rate > 20%; Two-Way Symmetric Averaging ép Flip Rate về đúng 0.0 |
7 |
test_07_judge_length_controlled_regression_debiasing |
Naive len_corr > 0.25; hồi quy LC cắt mạnh thiên lệch độ dài & tăng tương quan gold |
8 |
test_08_judge_sycophancy_and_rubric_hack_stress_defense |
Naive rơi > 15pp trên stress suite; Calibrated Judge giữ vững >= 80% (kèm kiểm toán chống rò rỉ gold_winner) |
9 |
test_09_cohens_kappa_and_dawid_skene_panel_calibration |
Kiểm toán đúng \(\kappa\), Dawid–Skene EM vượt trung bình giám khảo đơn và giảm ECE |
10 |
test_10_pgr_metric_formula_and_boundary_invariants |
compute_pgr khớp 0.0, 1.0, âm khi tệ hơn thầy yếu và chặn mẫu số không dương |
11 |
test_11_superalignment_dataset_weak_vs_ceiling_gap |
StrongCeiling >= 93% trong khi WeakTeacher bị kẹt [65%, 80%] với điểm mù sâu |
12 |
test_12_naive_ce_imitates_weak_teacher_errors |
Naive CE học vẹt lỗi thầy yếu (weak_agreement cao hơn, PGR < 0.50, điểm mù < 65%) |
13 |
test_13_aux_conf_and_bootstrapping_beats_weak_teacher_high_pgr |
AuxConf và Bootstrapped (w->m->s) đánh bại thầy yếu và Naive CE với PGR > 0.65 |
14 |
test_14_strong_student_safetensors_roundtrip_zero_pickle |
Lưu/nạp StrongStudentMLP qua safetensors cho sai lệch logit 0.0 |
15 |
test_15_cli_demo_workbench_json_schema_and_panels |
run_lab_demo.py --quick xuất đủ 6 KPI, 4 bar, 4 bảng và PGR > 0.65 |
16 |
test_16_ast_security_guard_no_unsafe_deserializers |
Quét AST toàn bộ src/, scripts/, tests/ cấm pickle, joblib, dill, marshal |
Trụ cột 5 — Văn liệu Nền tảng & SOTA (1979–2026), Ôn tập & Thang chấm Rubric#
5.1 Sáu Công trình Học thuật Kinh điển & Biên giới (1979–2026)#
- Manheim, D., & Garrabrant, S. (2018). Categorizing Variants of Goodhart's Law (
arXiv:1803.04585). (Đặt hệ thống phân loại Regressional, Extremal, Causal và Adversarial Goodhart.) - Gao, L., Schulman, J., & Hilton, J. (2023). Scaling Laws for Reward Model Overoptimization (ICML 2023,
arXiv:2210.10760). (Chứng minh thực nghiệm quy luật \(R_{\text{gold}}(d) = d(\alpha - \beta\log d)\) và bất biến KL của Best-of-\(N\).) - Coste, T., et al. (2024) & Eisenstein, J., et al. (2024). Reward Model Ensembles Help Mitigate Overoptimization (ICLR 2024) & Helping Herds: Reward Model Ensembles. (Đề xuất phạt phương sai bất định
UWO\(\mu - \lambda\sigma\) vàWCOchặn khai thác OOD.) - Zheng, L., et al. (2023) & Dubois, Y., et al. (2024). Judging LLM-as-a-Judge with MT-Bench and Chatbot Arena (NeurIPS 2023) & Length-Controlled AlpacaEval: A Simple Way to Debias Automatic Evaluators (
arXiv:2404.04475). (Định danh thiên lệch vị trí/tự ưa thích và đề xuất hồi quy phản thực tế kiểm soát độ dàiLC Win Rate.) - Dawid, A. P., & Skene, A. M. (1979) & Sharma, M., et al. (2024). Maximum Likelihood Estimation of Observer Error-Rates Using the EM Algorithm (Applied Statistics) & Towards Understanding Sycophancy in Language Models (ICLR 2024). (Nền tảng ước lượng chân lý tiềm ẩn đa giám khảo và chẩn đoán hành vi nịnh hót trong RLHF.)
- Burns, C., et al. (OpenAI Superalignment, 2023/2024). Weak-to-Strong Generalization: Eliciting Strong Capabilities With Weak Supervision (ICML 2024,
arXiv:2312.09390). (Đặt bài toán siêu căn chỉnh, thước đoPGR, hàm mất mátAuxConfvà khởi động trung gian \(w \to m \to s\).)
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(Phân loại Goodhart): Trong 4 dạng Goodhart (Regressional, Extremal, Causal, Adversarial), tối ưu quá mức đẩy chính sách ra vùng mật độ thấp ngoài phân phối dữ liệu huấn luyện RM khiến mối xấp xỉ gãy hoàn toàn là Extremal Goodhart.Q2(Quy luật Gao et al. &BoN KL): Với \(D_{\text{KL}}(\pi_{\text{BoN}} \| \pi_{\text{ref}}) = \log N - \frac{N-1}{N}\) và \(R_{\text{gold}}(d) = d(\alpha_{\text{rm}} - \beta_{\text{rm}}\log d)\), cực đại nằm tại \(d^* = \exp(\alpha_{\text{rm}}/\beta_{\text{rm}} - 1)\) (2.12trongWB-Ch22); vượt quá \(d_{\text{zero}} = e \cdot d^*\) (5.75), phần thưởng thực tụt xuống âm.Q3(Hợp thểUWO&RLVR): Hợp thểUWO(\(r_{\text{UWO}} = \mu - \lambda\sigma\)) cắt33.7×bất định OOD (std: 18.71 -> 0.556) và giữgold = +1.43(so với-104.07của RM đơn không phạt KL); các tác vụ kiểm chứng tất định nên tách hẳn sangRLVR.Q4(Thiên lệch Vị trí & Đảo Hai chiều): Đánh giá cả hai chiều(A, B)và(B, A)rồi lấy \(p_{\text{sym}} = \frac{1}{2}(p_{AB} + 1 - p_{BA})\) bảo toàn đối xứng hoán vị tuyệt đối, ép Flip Rate từ25.4%xuống0.0%.Q5(Hồi quy Phản thực tế Kiểm soát Độ dàiLC): Hồi quyAlpacaEval LC(Ridgekhử gây nhiễu +LogisticRegression1 chiều đánh giá nghiêm ngặt trên phản thực tếx_ev_cftại \(\delta_{\text{len}} = 0\), không rò rỉ nhãn vàng) cắt tương quan độ dài giả từ0.448xuống0.024(-94.7%).Q6(Sycophancy,Rubric Hack&Dawid–Skene EM): Dưới bẫy nịnh hót và từ khóa rubric (độc lập với nhãn vàng), Stress Accuracy giám khảo ngây thơ sụt30.5pp(78.0% -> 47.5%); đường ốngLC + Dawid–Skene EMnâng Stress Accuracy lên98.3%(Overall Accuracy = 99.2%),Cohen's kappalên0.983và cắtECEtừ0.253còn0.021.Q7(Thước đoPGR& Thất bại củaNaive CE): \(\text{PGR} = \frac{\text{Acc}(f_{w\to s}) - \text{Acc}(f_w)}{\text{Acc}(f_{\text{ceiling}}) - \text{Acc}(f_w)}\);Naive CEdùng dung lượng dư thừa để học thuộc lỗi điểm mù của thầy yếu (94.4%đồng thuận thầy yếu), dẫn đếnPGR = -0.061.Q8(AuxConf&Bootstrapping w->m->s): Hàm mất mát phụ trợ tự tin \((1-\alpha_t)\text{CE}(y_w) + \alpha_t\text{CE}(\hat{y}_s)\) kết hợp biểu diễn tiền huấn luyện nângPGRlên0.851(96.2%), và khởi động trung gian \(w \to m \to s\) đạt99.1%(98.0%trên điểm mù,PGR = 0.965), lưu quasafetensors(0.0).
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 Điểm Đỉnh \(d^*\) Gao et al. (2023) & KLBest-of-N:Thực hiện phép đổi biến \(u = F(y)\) chứng minh \(D_{\text{KL}}(\pi_{\text{BoN}} \| \pi_{\text{ref}}) = \log N - \frac{N-1}{N}\), sau đó lấy đạo hàm bậc 1–2 của \(R_{\text{gold}}(d) = d(\alpha_{\text{rm}} - \beta_{\text{rm}}\log d)\) để tìm \(d^*\) và \(d_{\text{zero}}\); đối chiếu với
best_of_n_klvàgao_overoptimization_curve(Tests 02, 03). -
Bài tập 2 (
20%) — Thực nghiệm Hợp thểUWO& Quét Ngưỡng KL Chống Vách đá Goodhart:Chạy thí nghiệm tối ưu hóa trên \(K = 5\)
RewardMLP(run_reward_ensemble_overoptimization_experiment,run_kl_penalty_sweep), lý giải vì sao tối ưu không phạt KL gây sụt106.90điểmgold, chứng minh đẳng thức điểm dừng \(\nabla R = \beta_{\text{KL}} z^*\) và xác minh vai trò trừ \(\lambda\sigma\) (Tests 04, 05). -
Bài tập 3 (
15%) — Đảo Vị trí Hai chiều & Hồi quy Phản thực tế Kiểm soát Độ dàiAlpacaEval LC:Chứng minh tính đối xứng hoán vị của \(p_{\text{sym}}\), phân tích vì sao hồi quy phản thực tế trên
x_ev_cf(\(\delta_{\text{len}} = 0\), không nhìn nhãn vàng) tách chất lượng thật khỏi độ dài giả, và kiểm chứng mức giảm Flip Rate (25.4% -> 0.0%) lẫnlen_corr(0.448 -> 0.024) trênWB-Ch22(Tests 06, 07). -
Bài tập 4 (
15%) — Kiểm toán Hội đồng Đa Giám khảoDawid–Skene EM&Cohen's kappa:Viết tay bước E-step và M-step của thuật toán
EM Dawid–Skenekèm làm mượt Laplace, giải thích ý nghĩa hiệu chỉnh may rủi \(p_e\) củaCohen's kappavà xác minh mức tăng Stress Accuracy (47.5% -> 98.3%) lẫn giảmECE(0.253 -> 0.021) (Tests 08, 09). -
Bài tập 5 (
20%) — Khai mở Năng lựcWeak-to-Strong:Naive CEvsAuxConfvsBootstrapping:Phân tích nguyên nhân
Naive CEđạtweak_agreement = 94.4%nhưngPGR = -0.061trên tập có điểm mù hệ thống; giải thích vai trò ngưỡng phân vị cân bằng \(\tau_t\) trongAuxConfvà nút thắt cổ chai trung gian \(w \to m \to s\) đưaPGRlên0.965(Tests 10, 11, 12, 13). -
Bài tập 6 (
15%) — Lưu trữ An toànSafetensors& Nghiệm thu Trọn góiWB-Ch22(16/16 Pytest):Kiểm chứng lưu/nạp
StrongStudentMLPquasafetensors(diff == 0.0), đảm bảo0import deserializer cấm qua quét AST, chạyrun_lab_demo.py --seed 42,ruff,mypyvà16/16 pytest(Tests 14, 15, 16).
5.4 Thang chấm Rubric (UCL MSc Grading Rubric)#
| Cấp độ Đạt chuẩn | Tiêu chí Lý thuyết & Kiến trúc (Trụ cột 1 & 2) | Tiêu chí Thực nghiệm & Hệ thống (WB-Ch22) |
|---|---|---|
Principal / MSc Distinction (>= 85%) |
Chứng minh trọn vẹn BoN KL, điểm đỉnh \(d^* = \exp(\alpha/\beta-1)\) của Gao et al., động học phạt KL + UWO, công thức AlpacaEval LC, cập nhật EM Dawid–Skene, và lý giải chính xác cơ chế AuxConf + w->m->s tránh học vẹt lỗi thầy yếu |
Đạt 16/16 pytest (0 skips, 0 lỗi ruff/mypy), KL+UWO giữ gold > 0 và std thấp hơn hẳn RM đơn, Judge Flip 0.0%, kappa >= 0.90, Bootstrapped W2S đạt PGR > 0.65, safetensors == 0.0 và xuất chuẩn artifacts/ch22_wb22_results.json |
Senior / Đạt chuẩn (70% – 84%) |
Hiểu rõ 4 dạng Goodhart, các thiên lệch của LLM Judge và định nghĩa PGR, nhưng còn thiếu dẫn xuất \(d^*\), phương trình EM Dawid–Skene hoặc vai trò ngưỡng phân vị \(\tau_t\) trong AuxConf |
Chạy thông suốt run_lab_demo.py và qua đa số bài kiểm thử, nhưng thiếu kiểm chứng quét \(\beta_{\text{KL}}\) hoặc chưa tách tập hiệu chuẩn LC khỏi tập đánh giá |
Cần khắc phục (< 70%) |
Tưởng Proxy tăng luôn đồng nghĩa hành vi tốt hơn, đánh giá LLM Judge 1 chiều không đảo vị trí, hoặc nhầm lẫn PGR với độ chính xác thô |
Để rò rỉ tập hiệu chuẩn vào đánh giá, để Naive CE học vẹt lỗi thầy yếu mà không bật AuxConf, dùng pickle lưu mô hình, hoặc thất bại pytest WB-Ch22 |
Article #9: Gold Truth Score Under RM Optimization (Higher is Better)
Article #10: LLM-Judge Stress Accuracy & Agreement (%)
Article #11: Weak-to-Strong Superalignment Accuracy (%)
Article #11: Accuracy on Weak Teacher's Systematic Blind Spot (%)
Article #9: Reward Model Over-Optimization vs Conservative UWO Defense
| Policy Objective | Proxy Reward | True Gold Score | KL Drift & OOD Std |
|---|---|---|---|
| Unpenalized Single RM (beta=0) | 174.43 | -104.07 (drop 106.90) | KL=364.28, std=18.71 |
| KL-Regularized Single RM | 21.98 | 2.46 | KL=4.17, std=2.27 |
| KL + UWO Ensemble (mu - lambda*sigma) | 15.21 | 1.43 (SAFE OPTIMUM) | KL=2.40, std=0.56 |
Article #10: LLM-as-a-Judge Bias & Calibration Audit (Held-Out Eval)
| Judge Pipeline | Position Flip Rate | Stress Acc & Verbosity Corr | Cohen's kappa & ECE |
|---|---|---|---|
| Naive Biased Judge (Single Order) | 25.4% | Stress 47.5% | len_r=0.448 | kappa=0.258, ECE=0.253 |
| Two-Way Position Swap Only | 0.0% | Overall 63.6% | kappa=0.268 |
| Calibrated (Swap + LC + Dawid-Skene) | 0.0% | Stress 98.3% | len_r=0.024 | kappa=0.983, ECE=0.021 |
Article #11: Weak-to-Strong Generalization & PGR Benchmark (PyTorch CPU)
| Model Variant | Held-Out Acc | Blind-Spot Acc | PGR & Weak Agreement |
|---|---|---|---|
| Weak Teacher (Surface Baseline) | 74.7% | 48.0% | PGR = 0.000 (ref) |
| Naive CE Weak->Strong | 73.1% | 44.6% | PGR=-0.061, agree_w=94.4% |
| AuxConf Weak->Strong | 96.2% | 89.2% | PGR=0.851, agree_w=78.4% |
| Bootstrapped (w->m->s) + AuxConf | 99.1% | 98.0% | PGR=0.965, agree_w=74.7% |
| Strong Ceiling (Oracle Gold) | 100.0% | 100.0% | PGR = 1.000 (ceiling) |
2026 Production AI Safety & Evaluation Decision Playbook
| Failure Mode | Detection Telemetry | Primary Defense | Production Guardrail |
|---|---|---|---|
| Goodhart Reward Hacking (#9) | Proxy up while holdout/gold drops; KL > d* | KL beta + UWO Ensemble (mu - lambda*sigma) | Route verifiable tasks to RLVR; refresh RM |
| Judge Position & Verbosity (#10) | Flip rate > 5%; high length correlation | Two-Way Swap + AlpacaEval LC Regression | 0.0% swap flip rate; counterfactual len=0 |
| Sycophancy & Rubric Hack (#10) | Stress suite drop > 10pp; low kappa | Rubric Invariance Filter + Dawid-Skene EM | Require Cohen's kappa >= 0.70 vs gold |
| Weak-Supervisor Imitation (#11) | Low PGR (< 0.4); high weak-error fit | AuxConf self-sharpening + w->m->s Bootstrap | Track PGR > 0.65 & safetensors=0.0 |
02-track-1-data-science-and-ai/part-04-nlp-llm-post-training-and-safety/labs/ch22-ai-safety-and-superalignment-workbench
[build-system]
requires = ["setuptools>=68.0"]
build-backend = "setuptools.build_meta"
[project]
name = "ai-safety-superalignment-lab"
version = "0.1.0"
description = "WB-Ch22: AI Safety, Reward Hacking (Goodhart), LLM-as-Judge Bias Calibration & Weak-to-Strong Superalignment (T1-P4-U05)."
readme = "README.md"
requires-python = ">=3.12"
dependencies = [
"numpy>=1.26",
"pydantic>=2.0",
"safetensors>=0.4",
"scikit-learn>=1.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
"""WB-Ch22: AI Safety, Reward Hacking (Goodhart), LLM-Judge Debiasing & Weak-to-Strong Superalignment."""
from ai_safety_superalignment_lab.reward_hacking_and_judge import (
GoodhartConfig,
JudgeAuditConfig,
RewardMLP,
best_of_n_kl,
compute_cohens_kappa,
compute_ece,
dawid_skene_em,
gao_overoptimization_curve,
generate_synthetic_judge_pairs,
run_judge_bias_and_debiasing_benchmark,
run_kl_penalty_sweep,
run_reward_ensemble_overoptimization_experiment,
)
from ai_safety_superalignment_lab.weak_to_strong_superalignment import (
StrongStudentMLP,
WeakToStrongConfig,
build_superalignment_dataset,
compute_pgr,
load_safetensors_checkpoint,
run_full_ch22_wb22_benchmarks,
run_weak_to_strong_benchmark,
save_safetensors_checkpoint,
)
__all__ = [
"GoodhartConfig",
"JudgeAuditConfig",
"RewardMLP",
"StrongStudentMLP",
"WeakToStrongConfig",
"best_of_n_kl",
"build_superalignment_dataset",
"compute_cohens_kappa",
"compute_ece",
"compute_pgr",
"dawid_skene_em",
"gao_overoptimization_curve",
"generate_synthetic_judge_pairs",
"load_safetensors_checkpoint",
"run_full_ch22_wb22_benchmarks",
"run_judge_bias_and_debiasing_benchmark",
"run_kl_penalty_sweep",
"run_reward_ensemble_overoptimization_experiment",
"run_weak_to_strong_benchmark",
"save_safetensors_checkpoint",
]
"""Deep-Dive Articles #9 & #10: Goodhart Reward Hacking, UWO Ensembles & LLM-Judge Debiasing."""
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
from sklearn.linear_model import LogisticRegression, Ridge
class GoodhartConfig(BaseModel):
"""Configuration for Goodhart scaling law & conservative reward ensemble optimization."""
model_config = ConfigDict(extra="forbid")
alpha_rm: float = Field(default=0.42, gt=0.0)
beta_rm: float = Field(default=0.24, gt=0.0)
alpha_proxy: float = Field(default=0.38, gt=0.0)
kl_beta: float = Field(default=2.20, ge=0.0)
ensemble_size: int = Field(default=5, ge=2, le=12)
uwo_lambda: float = Field(default=2.50, ge=0.0)
opt_steps: int = Field(default=85, ge=10)
seed: int = 42
class JudgeAuditConfig(BaseModel):
"""Configuration for LLM-as-a-Judge bias simulation and calibration pipeline."""
model_config = ConfigDict(extra="forbid")
n_pairs: int = Field(default=180, ge=60)
calibration_frac: float = Field(default=0.35, gt=0.1, lt=0.7)
position_bias_logit: float = Field(default=1.35, ge=0.0)
verbosity_bias_logit: float = Field(default=2.30, ge=0.0)
sycophancy_weight: float = Field(default=2.10, ge=0.0)
rubric_trap_weight: float = Field(default=2.05, ge=0.0)
self_pref_weight: float = Field(default=0.65, ge=0.0)
seed: int = 42
def best_of_n_kl(n: int | float) -> float:
"""Exact analytical KL divergence D_KL(pi_BoN || pi_ref) = log(N) - (N - 1) / N."""
if n < 1:
raise ValueError(f"Best-of-N requires n >= 1, got {n}")
n_f = float(n)
return float(math.log(n_f) - (n_f - 1.0) / n_f)
def gao_overoptimization_curve(
d_values: np.ndarray | list[float],
alpha_rm: float = 0.42,
beta_rm: float = 0.24,
alpha_proxy: float = 0.38,
) -> dict[str, Any]:
"""Compute Gao et al. (2023) proxy vs gold reward scaling curves across d = sqrt(D_KL)."""
d = np.asarray(d_values, dtype=np.float64)
if np.any(d < 0.0):
raise ValueError("d_values must be non-negative (sqrt(D_KL) >= 0)")
proxy_reward = alpha_proxy * d
safe_d = np.maximum(d, 1e-12)
gold_reward = np.where(d > 0.0, d * (alpha_rm - beta_rm * np.log(safe_d)), 0.0)
d_star = float(math.exp(alpha_rm / beta_rm - 1.0))
gold_peak = float(beta_rm * d_star)
d_zero = float(math.exp(alpha_rm / beta_rm))
return {
"d_values": [float(x) for x in d],
"proxy_reward": [float(x) for x in proxy_reward],
"gold_reward": [float(x) for x in gold_reward],
"d_star": d_star,
"gold_peak": gold_peak,
"d_zero": d_zero,
"kl_star": float(d_star * d_star),
}
class RewardMLP(nn.Module):
"""Lightweight neural reward model with linear skip + nonlinear residual capacity."""
def __init__(self, in_dim: int = 12, hidden_dim: int = 32) -> None:
super().__init__()
self.skip = nn.Linear(in_dim, 1, bias=False)
self.net = nn.Sequential(
nn.Linear(in_dim, hidden_dim),
nn.GELU(),
nn.Linear(hidden_dim, hidden_dim),
nn.GELU(),
nn.Linear(hidden_dim, 1),
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
return (0.35 * (self.skip(x) + 0.5 * self.net(x))).squeeze(-1)
def _true_gold_utility(z: torch.Tensor) -> torch.Tensor:
"""Ground-truth utility: rewards true quality dims 0..3, penalizes spurious/OOD hack norms."""
w_true = torch.tensor([1.25, 1.05, 0.90, 0.80], dtype=z.dtype, device=z.device)
true_score = (z[..., :4] * w_true).sum(dim=-1)
spurious_penalty = 0.22 * (z[..., 4:8] ** 2).sum(dim=-1)
ood_hack_penalty = 0.42 * (z[..., 8:12] ** 2).sum(dim=-1)
return true_score - spurious_penalty - ood_hack_penalty
def _train_reward_ensemble(
cfg: GoodhartConfig,
n_pairs: int,
) -> list[RewardMLP]:
"""Train K independent RewardMLP models on narrow-OOD preference data."""
torch.set_num_threads(1)
rng = np.random.default_rng(cfg.seed)
def sample_z(n: int) -> np.ndarray:
z_true = rng.normal(0.0, 1.0, size=(n, 4))
z_spur = rng.normal(0.0, 0.65, size=(n, 4))
# Tiny support on OOD hack dimensions -> high epistemic uncertainty off-manifold
z_hack = rng.normal(0.0, 0.06, size=(n, 4))
return np.concatenate([z_true, z_spur, z_hack], axis=1).astype(np.float32)
z_a_np = sample_z(n_pairs)
z_b_np = sample_z(n_pairs)
z_a = torch.from_numpy(z_a_np)
z_b = torch.from_numpy(z_b_np)
with torch.no_grad():
g_a = _true_gold_utility(z_a)
g_b = _true_gold_utility(z_b)
# Crowdworkers exhibit mild verbosity/spurious & hack marker preference on training pairs
spur_bias_a = 0.42 * z_a[:, 4:8].sum(dim=-1) + 0.35 * z_a[:, 8:12].sum(dim=-1)
spur_bias_b = 0.42 * z_b[:, 4:8].sum(dim=-1) + 0.35 * z_b[:, 8:12].sum(dim=-1)
logits_gt = 2.2 * (g_a - g_b) + (spur_bias_a - spur_bias_b)
probs = torch.sigmoid(logits_gt)
noise = torch.from_numpy(rng.uniform(0.0, 1.0, size=n_pairs).astype(np.float32))
labels = (noise < probs).float()
ensemble: list[RewardMLP] = []
for k in range(cfg.ensemble_size):
torch.manual_seed(cfg.seed + 101 * (k + 1))
model = RewardMLP(in_dim=12, hidden_dim=32)
boot_idx = torch.from_numpy(rng.integers(0, n_pairs, size=int(0.85 * n_pairs)))
opt = torch.optim.AdamW(model.parameters(), lr=8.0e-3, weight_decay=3.5e-1)
model.train()
for _ in range(75):
opt.zero_grad()
ra = model(z_a[boot_idx])
rb = model(z_b[boot_idx])
loss = F.binary_cross_entropy_with_logits(ra - rb, labels[boot_idx])
loss.backward()
opt.step()
model.eval()
for p in model.parameters():
p.requires_grad_(False)
ensemble.append(model)
return ensemble
def _optimize_policy_mean(
ensemble: list[RewardMLP],
kl_beta: float,
uwo_lambda: float,
use_ensemble_mean: bool,
steps: int,
lr: float = 0.08,
) -> dict[str, Any]:
"""Optimize Gaussian policy mean z over pi_ref=N(0,I) where D_KL = 0.5 * ||z||^2."""
z = torch.zeros(1, 12, dtype=torch.float32, requires_grad=True)
opt = torch.optim.SGD([z], lr=lr, momentum=0.25)
trajectory: list[dict[str, float]] = []
for step in range(steps + 1):
preds = torch.stack([m(z).squeeze(0) for m in ensemble])
proxy_single = preds[0]
mu = preds.mean()
sigma = preds.std(unbiased=False)
d_kl = 0.5 * (z**2).sum()
with torch.no_grad():
gold = _true_gold_utility(z).squeeze(0)
trajectory.append(
{
"step": float(step),
"d_kl": float(d_kl.item()),
"sqrt_kl": float(math.sqrt(max(float(d_kl.item()), 0.0))),
"proxy_reward": float(proxy_single.item()),
"ensemble_mean": float(mu.item()),
"ensemble_std": float(sigma.item()),
"uwo_reward": float((mu - uwo_lambda * sigma).item()),
"gold_reward": float(gold.item()),
}
)
if step == steps:
break
opt.zero_grad()
base_r = mu if use_ensemble_mean else proxy_single
obj = base_r - uwo_lambda * sigma - kl_beta * d_kl
loss = -obj
loss.backward()
torch.nn.utils.clip_grad_norm_([z], max_norm=3.0)
opt.step()
gold_vals = [pt["gold_reward"] for pt in trajectory]
peak_gold = float(max(gold_vals))
final = trajectory[-1]
return {
"final": final,
"peak_gold_reward": peak_gold,
"gold_cliff_drop": float(peak_gold - final["gold_reward"]),
"trajectory": trajectory,
}
def run_kl_penalty_sweep(
cfg: GoodhartConfig | None = None,
kl_betas: tuple[float, ...] = (0.15, 0.55, 1.40, 3.20, 6.50),
quick: bool = False,
) -> list[dict[str, float]]:
"""Sweep KL regularization beta on single RM and verify monotonic policy drift contraction."""
c = cfg or GoodhartConfig()
n_pairs = 260 if quick else 420
steps = 55 if quick else c.opt_steps
ensemble = _train_reward_ensemble(c, n_pairs=n_pairs)
rows: list[dict[str, float]] = []
for beta in kl_betas:
res = _optimize_policy_mean(
ensemble=ensemble,
kl_beta=beta,
uwo_lambda=0.0,
use_ensemble_mean=False,
steps=steps,
)
fin = res["final"]
rows.append(
{
"kl_beta": float(beta),
"final_d_kl": float(fin["d_kl"]),
"final_proxy_reward": float(fin["proxy_reward"]),
"final_gold_reward": float(fin["gold_reward"]),
}
)
return rows
def run_reward_ensemble_overoptimization_experiment(
seed: int = 42,
quick: bool = False,
) -> dict[str, Any]:
"""Run Article #9 Goodhart over-optimization vs KL + Conservative UWO Ensemble benchmark."""
cfg = GoodhartConfig(seed=seed, opt_steps=60 if quick else 85)
n_pairs = 260 if quick else 420
ensemble = _train_reward_ensemble(cfg, n_pairs=n_pairs)
unpenalized = _optimize_policy_mean(
ensemble=ensemble,
kl_beta=0.0,
uwo_lambda=0.0,
use_ensemble_mean=False,
steps=cfg.opt_steps,
)
kl_single = _optimize_policy_mean(
ensemble=ensemble,
kl_beta=cfg.kl_beta,
uwo_lambda=0.0,
use_ensemble_mean=False,
steps=cfg.opt_steps,
)
uwo_ensemble = _optimize_policy_mean(
ensemble=ensemble,
kl_beta=cfg.kl_beta,
uwo_lambda=cfg.uwo_lambda,
use_ensemble_mean=True,
steps=cfg.opt_steps,
)
d_grid = np.linspace(0.0, 8.0, 33)
gao_curve = gao_overoptimization_curve(
d_grid,
alpha_rm=cfg.alpha_rm,
beta_rm=cfg.beta_rm,
alpha_proxy=cfg.alpha_proxy,
)
bon_values = [1, 4, 16, 64, 256, 1024]
bon_rows = [
{
"n": n,
"d_kl": best_of_n_kl(n),
"sqrt_kl": math.sqrt(best_of_n_kl(n)),
}
for n in bon_values
]
kl_sweep = run_kl_penalty_sweep(cfg=cfg, quick=quick)
return {
"gao_scaling_curve": gao_curve,
"best_of_n_kl": bon_rows,
"kl_sweep": kl_sweep,
"unpenalized_single_rm": {
"final": unpenalized["final"],
"peak_gold_reward": unpenalized["peak_gold_reward"],
"gold_cliff_drop": unpenalized["gold_cliff_drop"],
},
"kl_regularized_single_rm": {
"final": kl_single["final"],
"peak_gold_reward": kl_single["peak_gold_reward"],
"gold_cliff_drop": kl_single["gold_cliff_drop"],
},
"kl_uwo_ensemble": {
"final": uwo_ensemble["final"],
"peak_gold_reward": uwo_ensemble["peak_gold_reward"],
"gold_cliff_drop": uwo_ensemble["gold_cliff_drop"],
},
}
def compute_cohens_kappa(y_true: np.ndarray, y_pred: np.ndarray) -> float:
"""Compute Cohen's kappa agreement score for binary/categorical labels."""
yt = np.asarray(y_true, dtype=np.int64)
yp = np.asarray(y_pred, dtype=np.int64)
if yt.shape != yp.shape or yt.size == 0:
raise ValueError("y_true and y_pred must have identical non-empty shapes")
p_o = float(np.mean(yt == yp))
classes = np.unique(np.concatenate([yt, yp]))
p_e = sum(float(np.mean(yt == c)) * float(np.mean(yp == c)) for c in classes)
if p_e >= 1.0 - 1e-12:
return 1.0 if p_o >= 1.0 - 1e-12 else 0.0
return float((p_o - p_e) / (1.0 - p_e))
def compute_ece(probs: np.ndarray, y_true: np.ndarray, n_bins: int = 10) -> float:
"""Compute Expected Calibration Error (ECE) on predicted probabilities."""
p = np.clip(np.asarray(probs, dtype=np.float64), 0.0, 1.0)
y = np.asarray(y_true, dtype=np.float64)
bins = np.linspace(0.0, 1.0, n_bins + 1)
ece = 0.0
n = float(len(y))
for i in range(n_bins):
lo, hi = bins[i], bins[i + 1]
mask = (p >= lo) & (p <= hi if i == n_bins - 1 else p < hi)
if np.any(mask):
acc = float(np.mean(y[mask]))
conf = float(np.mean(p[mask]))
ece += (float(np.sum(mask)) / n) * abs(acc - conf)
return float(ece)
def dawid_skene_em(
votes: np.ndarray,
n_classes: int = 2,
max_iter: int = 35,
tol: float = 1e-6,
) -> dict[str, Any]:
"""Run Dawid-Skene EM algorithm to infer latent item truth and judge confusion matrices."""
v = np.asarray(votes, dtype=np.int64)
if v.ndim != 2:
raise ValueError("votes must be a 2D array of shape (n_items, n_judges)")
n_items, n_judges = v.shape
# Initialize item posteriors with smoothed majority vote
q = np.full((n_items, n_classes), 0.15 / max(n_classes - 1, 1), dtype=np.float64)
for i in range(n_items):
counts = np.bincount(v[i], minlength=n_classes).astype(np.float64)
q[i] = (counts + 0.5) / (n_judges + 0.5 * n_classes)
pi = np.full(n_classes, 1.0 / n_classes, dtype=np.float64)
confusion = np.zeros((n_judges, n_classes, n_classes), dtype=np.float64)
iters_run = 0
for it in range(max_iter):
iters_run = it + 1
pi = np.maximum(q.mean(axis=0), 1e-6)
pi /= pi.sum()
# M-step: estimate per-judge confusion matrices P(vote=k | true=c)
for j in range(n_judges):
for c in range(n_classes):
denom = float(q[:, c].sum()) + 1.0
for k in range(n_classes):
mask_jk = (v[:, j] == k).astype(np.float64)
confusion[j, c, k] = (float(np.dot(q[:, c], mask_jk)) + 0.5) / denom
# E-step: update latent truth posteriors in log-space for numerical stability
log_q = np.broadcast_to(np.log(pi), (n_items, n_classes)).copy()
for j in range(n_judges):
log_conf = np.log(np.maximum(confusion[j], 1e-12))
log_q += log_conf[:, v[:, j]].T
log_q -= log_q.max(axis=1, keepdims=True)
q_new = np.exp(log_q)
q_new /= q_new.sum(axis=1, keepdims=True)
if float(np.max(np.abs(q_new - q))) < tol:
q = q_new
break
q = q_new
reliabilities = [float(np.mean(np.diag(confusion[j]))) for j in range(n_judges)]
return {
"posterior_probs": q,
"predicted_labels": np.argmax(q, axis=1),
"class_priors": [float(x) for x in pi],
"confusion_matrices": confusion.tolist(),
"judge_reliabilities": reliabilities,
"n_iters": iters_run,
}
def _sigmoid_np(x: np.ndarray | float) -> np.ndarray | float:
return 1.0 / (1.0 + np.exp(-np.clip(x, -30.0, 30.0)))
def generate_synthetic_judge_pairs(
cfg: JudgeAuditConfig | None = None,
) -> list[dict[str, Any]]:
"""Generate synthetic pairwise LLM evaluation dataset with bias & adversarial traps.
All nuisance variables (length difference, sycophancy nudge, rubric trap, self-preference)
are sampled strictly independently of true qualities (qa, qb) and gold_winner.
"""
c = cfg or JudgeAuditConfig()
rng = np.random.default_rng(c.seed)
pairs: list[dict[str, Any]] = []
qa_all = rng.normal(0.0, 1.0, size=c.n_pairs)
delta_all = rng.choice([-1.0, 1.0], size=c.n_pairs) * rng.uniform(0.65, 2.05, size=c.n_pairs)
qb_all = qa_all - delta_all
len_all = np.clip(rng.normal(0.0, 1.45, size=c.n_pairs), -2.5, 2.5)
self_all = rng.choice([-1.0, 0.0, 1.0], size=c.n_pairs, p=[0.25, 0.5, 0.25])
# Stress-subset adversarial trap direction sampled strictly independently of gold_winner
stress_side_all = rng.choice([-1.0, 1.0], size=c.n_pairs)
for idx in range(c.n_pairs):
qa = float(qa_all[idx])
qb = float(qb_all[idx])
gold_winner = 1 if qa > qb else 0
len_diff = float(len_all[idx])
# Stress subset (50% of pairs): orthogonal sycophancy nudges & rubric-keyword traps
is_stress = idx % 2 == 1
if is_stress:
adv_side = float(stress_side_all[idx])
syc_nudge = adv_side
rubric_trap_diff = adv_side
else:
syc_nudge = 0.0
rubric_trap_diff = 0.0
self_pref_diff = float(self_all[idx])
# Simulate primary LLM judge in BOTH presentation orders (A, B) and (B, A)
true_margin = 1.15 * (qa - qb)
bias_ab = (
c.position_bias_logit
+ c.verbosity_bias_logit * math.tanh(len_diff)
+ c.sycophancy_weight * syc_nudge
+ c.rubric_trap_weight * rubric_trap_diff
+ c.self_pref_weight * self_pref_diff
)
# When swapped to (B, A), B occupies first position -> gets +position_bias_logit
bias_ba = (
c.position_bias_logit
- c.verbosity_bias_logit * math.tanh(len_diff)
- c.sycophancy_weight * syc_nudge
- c.rubric_trap_weight * rubric_trap_diff
- c.self_pref_weight * self_pref_diff
)
eps_ab = float(rng.normal(0.0, 0.72))
eps_ba = float(rng.normal(0.0, 0.72))
logit_ab = true_margin + bias_ab + eps_ab
logit_ba = -true_margin + bias_ba + eps_ba
p_ab = float(_sigmoid_np(logit_ab))
p_ba_b_wins = float(_sigmoid_np(logit_ba))
# Two auxiliary diverse judges (realistic disagreement & bias) for Dawid-Skene panel
j2_logit_ab = (
1.05 * (qa - qb)
+ 0.45 * c.position_bias_logit
- 0.65 * rubric_trap_diff
+ 0.50 * math.tanh(len_diff)
+ float(rng.normal(0.0, 1.15))
)
j2_logit_ba = (
-1.05 * (qa - qb)
+ 0.45 * c.position_bias_logit
+ 0.65 * rubric_trap_diff
- 0.50 * math.tanh(len_diff)
+ float(rng.normal(0.0, 1.15))
)
j3_logit_ab = (
1.00 * (qa - qb)
- 0.35 * c.position_bias_logit
+ 0.65 * syc_nudge
+ 0.45 * math.tanh(len_diff)
+ float(rng.normal(0.0, 1.20))
)
j3_logit_ba = (
-1.00 * (qa - qb)
- 0.35 * c.position_bias_logit
- 0.65 * syc_nudge
- 0.45 * math.tanh(len_diff)
+ float(rng.normal(0.0, 1.20))
)
p2_sym = 0.5 * (float(_sigmoid_np(j2_logit_ab)) + (1.0 - float(_sigmoid_np(j2_logit_ba))))
p3_sym = 0.5 * (float(_sigmoid_np(j3_logit_ab)) + (1.0 - float(_sigmoid_np(j3_logit_ba))))
pairs.append(
{
"pair_id": idx,
"true_quality_a": qa,
"true_quality_b": qb,
"gold_winner": gold_winner,
"len_diff": len_diff,
"sycophancy_nudge": syc_nudge,
"rubric_trap_diff": rubric_trap_diff,
"self_pref_diff": self_pref_diff,
"is_stress": is_stress,
"naive_logit_ab": logit_ab,
"naive_prob_ab": p_ab,
"naive_prob_ba_b_wins": p_ba_b_wins,
"p_sym_j1": 0.5 * (p_ab + (1.0 - p_ba_b_wins)),
"p_sym_j2": p2_sym,
"p_sym_j3": p3_sym,
}
)
return pairs
def run_judge_bias_and_debiasing_benchmark(
seed: int = 42,
quick: bool = False,
) -> dict[str, Any]:
"""Audit Naive Biased Judge vs Two-Way Swap + LC Counterfactual + Dawid-Skene Debiasing."""
cfg = JudgeAuditConfig(n_pairs=180, seed=seed)
pairs = generate_synthetic_judge_pairs(cfg)
n_cal = int(len(pairs) * cfg.calibration_frac)
cal_pairs = pairs[:n_cal]
eval_pairs = pairs[n_cal:]
def _safe_logit(p: np.ndarray) -> np.ndarray:
pc = np.clip(p, 1e-4, 1.0 - 1e-4)
return np.log(pc / (1.0 - pc))
def _extract(items: list[dict[str, Any]]) -> dict[str, np.ndarray]:
return {
"gold": np.array([x["gold_winner"] for x in items], dtype=np.int64),
"len_t": np.array([math.tanh(x["len_diff"]) for x in items], dtype=np.float64),
"syc": np.array([x["sycophancy_nudge"] for x in items], dtype=np.float64),
"trap": np.array([x["rubric_trap_diff"] for x in items], dtype=np.float64),
"self": np.array([x["self_pref_diff"] for x in items], dtype=np.float64),
"stress": np.array([x["is_stress"] for x in items], dtype=bool),
"p_ab": np.array([x["naive_prob_ab"] for x in items], dtype=np.float64),
"p_ba_b": np.array([x["naive_prob_ba_b_wins"] for x in items], dtype=np.float64),
"p_sym_j1": np.array([x["p_sym_j1"] for x in items], dtype=np.float64),
"p_sym_j2": np.array([x["p_sym_j2"] for x in items], dtype=np.float64),
"p_sym_j3": np.array([x["p_sym_j3"] for x in items], dtype=np.float64),
}
cal = _extract(cal_pairs)
ev = _extract(eval_pairs)
# Naive judge metrics on held-out eval split
naive_pred_ab = (ev["p_ab"] >= 0.5).astype(np.int64)
naive_pred_ba_for_a = (ev["p_ba_b"] < 0.5).astype(np.int64)
naive_flip_rate = float(np.mean(naive_pred_ab != naive_pred_ba_for_a))
# Stage 1 debiasing: Two-way position swap symmetry -> exact 0% flip rate
sym_pred_ab = (ev["p_sym_j1"] >= 0.5).astype(np.int64)
# Swapped evaluation (B, A) simply yields 1 - p_sym_j1 for B -> identical A decision
sym_pred_ba_for_a = ((1.0 - ev["p_sym_j1"]) < 0.5).astype(np.int64)
sym_flip_rate = float(np.mean(sym_pred_ab != sym_pred_ba_for_a))
# Stage 2 debiasing: AlpacaEval Length-Controlled (LC) + Rubric Invariance counterfactual model
# Estimate spurious bias weights solely from judge symmetric logits vs nuisance confounders
# on the calibration slice (zero peeking at gold_winner for bias subtraction).
z_cal = np.column_stack([cal["len_t"], cal["syc"], cal["trap"], cal["self"]])
z_ev = np.column_stack([ev["len_t"], ev["syc"], ev["trap"], ev["self"]])
s_sym_cal = _safe_logit(cal["p_sym_j1"])
s_sym_ev = _safe_logit(ev["p_sym_j1"])
bias_reg = Ridge(alpha=0.25)
bias_reg.fit(z_cal, s_sym_cal)
# Counterfactual debiasing: remove estimated nuisance projections and zero out cols 1..4
s_cal_cf = s_sym_cal - z_cal @ bias_reg.coef_
s_ev_cf = s_sym_ev - z_ev @ bias_reg.coef_
x_cal_cf = np.column_stack([s_cal_cf, np.zeros_like(z_cal)])
x_ev_cf = np.column_stack([s_ev_cf, np.zeros_like(z_ev)])
lc_clf = LogisticRegression(C=2.5, max_iter=500, random_state=seed)
lc_clf.fit(x_cal_cf, cal["gold"])
# Evaluate strictly on counterfactual holdout features x_ev_cf (zero peeking at gold outcome)
lc_probs_ev = lc_clf.predict_proba(x_ev_cf)[:, 1]
lc_pred_ev = (lc_probs_ev >= 0.5).astype(np.int64)
# Stage 3: Dawid-Skene EM panel aggregation over symmetric judges + LC calibrated J1
panel_votes = np.column_stack(
[
lc_pred_ev,
(ev["p_sym_j2"] >= 0.5).astype(np.int64),
(ev["p_sym_j3"] >= 0.5).astype(np.int64),
]
)
ds_res = dawid_skene_em(panel_votes, n_classes=2, max_iter=35)
ds_probs = ds_res["posterior_probs"][:, 1]
ds_pred = ds_res["predicted_labels"]
# Blend LC-calibrated probability + Dawid-Skene panel posterior for final calibrated judge
final_probs = 0.55 * lc_probs_ev + 0.45 * ds_probs
final_pred = (final_probs >= 0.5).astype(np.int64)
# Compute comparative diagnostics on held-out split
clean_mask = ~ev["stress"]
stress_mask = ev["stress"]
naive_acc = float(np.mean(naive_pred_ab == ev["gold"]))
naive_clean_acc = float(np.mean(naive_pred_ab[clean_mask] == ev["gold"][clean_mask]))
naive_stress_acc = float(np.mean(naive_pred_ab[stress_mask] == ev["gold"][stress_mask]))
sym_acc = float(np.mean(sym_pred_ab == ev["gold"]))
lc_acc = float(np.mean(lc_pred_ev == ev["gold"]))
final_acc = float(np.mean(final_pred == ev["gold"]))
final_clean_acc = float(np.mean(final_pred[clean_mask] == ev["gold"][clean_mask]))
final_stress_acc = float(np.mean(final_pred[stress_mask] == ev["gold"][stress_mask]))
naive_kappa = compute_cohens_kappa(ev["gold"], naive_pred_ab)
sym_kappa = compute_cohens_kappa(ev["gold"], sym_pred_ab)
final_kappa = compute_cohens_kappa(ev["gold"], final_pred)
naive_len_corr = float(np.corrcoef(ev["p_ab"], ev["len_t"])[0, 1])
final_len_corr = float(np.corrcoef(final_probs, ev["len_t"])[0, 1])
naive_gold_corr = float(np.corrcoef(ev["p_ab"], ev["gold"])[0, 1])
final_gold_corr = float(np.corrcoef(final_probs, ev["gold"])[0, 1])
naive_ece = compute_ece(ev["p_ab"], ev["gold"])
final_ece = compute_ece(final_probs, ev["gold"])
j1_sym_acc = sym_acc
j2_acc = float(np.mean((ev["p_sym_j2"] >= 0.5).astype(np.int64) == ev["gold"]))
j3_acc = float(np.mean((ev["p_sym_j3"] >= 0.5).astype(np.int64) == ev["gold"]))
ds_only_acc = float(np.mean(ds_pred == ev["gold"]))
return {
"n_calibration": n_cal,
"n_eval": len(eval_pairs),
"naive_judge": {
"accuracy": naive_acc,
"clean_accuracy": naive_clean_acc,
"stress_accuracy": naive_stress_acc,
"stress_drop": float(naive_clean_acc - naive_stress_acc),
"position_flip_rate": naive_flip_rate,
"verbosity_bias_corr": naive_len_corr,
"gold_corr": naive_gold_corr,
"cohens_kappa": naive_kappa,
"ece": naive_ece,
},
"two_way_swap_only": {
"accuracy": sym_acc,
"position_flip_rate": sym_flip_rate,
"cohens_kappa": sym_kappa,
},
"lc_debiased_only": {
"accuracy": lc_acc,
"cohens_kappa": compute_cohens_kappa(ev["gold"], lc_pred_ev),
},
"calibrated_debiased_judge": {
"accuracy": final_acc,
"clean_accuracy": final_clean_acc,
"stress_accuracy": final_stress_acc,
"stress_drop": float(final_clean_acc - final_stress_acc),
"position_flip_rate": sym_flip_rate,
"verbosity_bias_corr": final_len_corr,
"gold_corr": final_gold_corr,
"cohens_kappa": final_kappa,
"ece": final_ece,
},
"dawid_skene_panel": {
"individual_accs": [j1_sym_acc, j2_acc, j3_acc],
"mean_individual_acc": float((j1_sym_acc + j2_acc + j3_acc) / 3.0),
"dawid_skene_acc": ds_only_acc,
"estimated_reliabilities": ds_res["judge_reliabilities"],
"em_iters": ds_res["n_iters"],
},
"improvements": {
"flip_rate_drop": float(naive_flip_rate - sym_flip_rate),
"kappa_gain": float(final_kappa - naive_kappa),
"stress_acc_gain": float(final_stress_acc - naive_stress_acc),
"verbosity_corr_abs_reduction": float(abs(naive_len_corr) - abs(final_len_corr)),
"ece_reduction": float(naive_ece - final_ece),
},
}
"""Deep-Dive Article #11: Weak-to-Strong Supervision, PGR, AuxConf & Bootstrapping."""
from __future__ import annotations
import copy
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 pydantic import BaseModel, ConfigDict, Field
from safetensors.torch import load_file as safetensors_load_file
from safetensors.torch import save_file as safetensors_save_file
from sklearn.linear_model import LogisticRegression
from ai_safety_superalignment_lab.reward_hacking_and_judge import (
run_judge_bias_and_debiasing_benchmark,
run_reward_ensemble_overoptimization_experiment,
)
class WeakToStrongConfig(BaseModel):
"""Configuration for Weak-to-Strong Superalignment benchmark."""
model_config = ConfigDict(extra="forbid")
n_train: int = Field(default=900, ge=200)
n_eval: int = Field(default=450, ge=100)
input_dim: int = Field(default=16, ge=8)
hidden_dim: int = Field(default=64, ge=16)
epochs_ceiling: int = Field(default=60, ge=10)
epochs_naive: int = Field(default=110, ge=20)
epochs_aux: int = Field(default=44, ge=15)
aux_alpha_max: float = Field(default=0.78, gt=0.0, lt=1.0)
lr: float = Field(default=5.5e-3, gt=0.0)
seed: int = 42
def compute_pgr(acc_weak: float, acc_w2s: float, acc_ceiling: float) -> float:
"""Compute Performance Gap Recovered: (Acc_w2s - Acc_weak) / (Acc_ceiling - Acc_weak)."""
denom = acc_ceiling - acc_weak
if denom <= 1e-12:
raise ValueError(
f"Ceiling accuracy ({acc_ceiling:.4f}) must strictly exceed weak accuracy ({acc_weak:.4f})"
)
return float((acc_w2s - acc_weak) / denom)
class StrongStudentMLP(nn.Module):
"""Pre-trained-style Strong Student network with residual skip + nonlinear MLP."""
def __init__(self, input_dim: int = 16, hidden_dim: int = 64) -> None:
super().__init__()
self.proj = nn.Linear(input_dim, hidden_dim)
self.fc1 = nn.Linear(hidden_dim, hidden_dim)
self.fc2 = nn.Linear(hidden_dim, hidden_dim)
self.head = nn.Linear(hidden_dim, 1)
def encode(self, x: torch.Tensor) -> torch.Tensor:
"""Compute latent student representation h(x) before linear classification head."""
h = F.silu(self.proj(x))
h = h + F.silu(self.fc1(h))
h = h + F.silu(self.fc2(h))
return h
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.head(self.encode(x)).squeeze(-1)
def save_safetensors_checkpoint(model: nn.Module, path: str | Path) -> Path:
"""Save PyTorch module weights using zero-pickle safetensors format."""
target = Path(path)
target.parent.mkdir(parents=True, exist_ok=True)
state = {k: v.detach().cpu().contiguous() for k, v in model.state_dict().items()}
safetensors_save_file(state, str(target))
return target
def load_safetensors_checkpoint(model: nn.Module, path: str | Path) -> nn.Module:
"""Load safetensors weights back into PyTorch module strictly."""
state = safetensors_load_file(str(path), device="cpu")
model.load_state_dict(state, strict=True)
return model
def build_superalignment_dataset(
n_train: int = 900,
n_eval: int = 450,
input_dim: int = 16,
seed: int = 42,
) -> dict[str, Any]:
"""Build synthetic superalignment task with strong universal latent structure and weak blind spots.
- Shared universal true concept lives in deep features x[:, 2:7] (cleanly separable by Strong Student).
- Majority regime (~72%) aligns surface cues x[:, 0:2] with true label.
- Hard blind-spot regime (~28%) flips surface cues x[:, 0:2] and exposes regime flag x[:, 10],
causing a surface-only Weak Teacher to fail systematically while Naive CE students memorize
the teacher's errors via x[:, 10].
"""
rng = np.random.default_rng(seed)
n_total = n_train + n_eval
y_true = rng.integers(0, 2, size=n_total, dtype=np.int64)
sign = (2.0 * y_true - 1.0).astype(np.float32)
x = rng.normal(0.0, 0.70, size=(n_total, input_dim)).astype(np.float32)
is_blind_spot = rng.uniform(0.0, 1.0, size=n_total) < 0.31
# Shared universal latent concept in deep features 2..6 (consistent across ALL regimes!)
deep_weights = np.array([1.25, -1.05, 1.15, 0.95, -0.85], dtype=np.float32)
x[:, 2:7] += sign[:, None] * deep_weights[None, :]
# Surface cues 0..1 align in majority regime (~69%), vanish into noise in blind-spot regime
surface_sign = np.where(is_blind_spot, 0.0, 0.75 * sign)
x[:, 0] += surface_sign
x[:, 1] += 0.65 * surface_sign
# Regime shortcut indicator x[:, 10] & weak bias x[:, 11] cause Weak Teacher error
# in the blind-spot regime while allowing high-capacity Naive CE to overfit those errors
x[:, 10] = np.where(is_blind_spot, 2.4, -0.8) + rng.normal(0.0, 0.15, size=n_total).astype(np.float32)
spurious_weak = np.where(is_blind_spot, -1.75, 0.0) + rng.normal(0.0, 0.25, size=n_total).astype(
np.float32
)
x[:, 11] = spurious_weak
# Weak Teacher sees ONLY surface cues + regime/spurious shortcut (missing deep concept x[:, 2:7])
weak_features = x[:, [0, 1, 10, 11]]
weak_clf = LogisticRegression(C=1.0, max_iter=300, random_state=seed)
weak_clf.fit(weak_features[:n_train], y_true[:n_train])
y_weak_all = weak_clf.predict(weak_features).astype(np.int64)
# In the blind-spot regime, Weak Teacher's systematic blind spot predicts biased negative class
y_weak_all = np.where(is_blind_spot & (x[:, 0] < 0.35), 0, y_weak_all).astype(np.int64)
p_weak_all = weak_clf.predict_proba(weak_features)[:, 1].astype(np.float32)
# Split strictly into train and eval
return {
"x_train": x[:n_train],
"y_true_train": y_true[:n_train],
"y_weak_train": y_weak_all[:n_train],
"p_weak_train": p_weak_all[:n_train],
"blind_train": is_blind_spot[:n_train],
"x_eval": x[n_train:],
"y_true_eval": y_true[n_train:],
"y_weak_eval": y_weak_all[n_train:],
"p_weak_eval": p_weak_all[n_train:],
"blind_eval": is_blind_spot[n_train:],
}
def _eval_binary_classifier(
model: nn.Module,
x_eval: np.ndarray,
y_true_eval: np.ndarray,
y_weak_eval: np.ndarray,
blind_eval: np.ndarray,
) -> dict[str, float]:
model.eval()
with torch.no_grad():
logits = model(torch.from_numpy(x_eval))
probs = torch.sigmoid(logits).numpy()
preds = (probs >= 0.5).astype(np.int64)
acc = float(np.mean(preds == y_true_eval))
blind_acc = float(np.mean(preds[blind_eval] == y_true_eval[blind_eval]))
clean_acc = float(np.mean(preds[~blind_eval] == y_true_eval[~blind_eval]))
weak_agreement = float(np.mean(preds == y_weak_eval))
return {
"accuracy": acc,
"blind_spot_accuracy": blind_acc,
"majority_accuracy": clean_acc,
"weak_agreement": weak_agreement,
}
def _pretrain_student_backbone(
model: StrongStudentMLP,
x_unlabeled: torch.Tensor,
input_dim: int,
hidden_dim: int,
epochs: int = 24,
) -> None:
"""Unsupervised denoising autoencoder pre-training on x_train (models base LLM pre-training)."""
decoder = nn.Linear(hidden_dim, input_dim)
params = [
*model.proj.parameters(),
*model.fc1.parameters(),
*model.fc2.parameters(),
*decoder.parameters(),
]
opt = torch.optim.AdamW(params, lr=8e-3, weight_decay=1e-2)
model.train()
for _ in range(epochs):
opt.zero_grad()
noisy_x = x_unlabeled + torch.randn_like(x_unlabeled) * 0.25
recon = decoder(model.encode(noisy_x))
loss = F.mse_loss(recon, x_unlabeled)
loss.backward()
opt.step()
def _train_student_model(
x_train: np.ndarray,
y_target_train: np.ndarray,
input_dim: int,
hidden_dim: int,
epochs: int,
lr: float,
weight_decay: float,
aux_alpha_max: float,
seed: int,
pretrain_backbone: bool = True,
) -> StrongStudentMLP:
"""Train StrongStudentMLP with either Naive CE (aux_alpha_max=0) or AuxConf self-sharpening."""
torch.set_num_threads(1)
torch.manual_seed(seed)
np.random.seed(seed)
model = StrongStudentMLP(input_dim=input_dim, hidden_dim=hidden_dim)
x_t = torch.from_numpy(x_train)
y_t = torch.from_numpy(y_target_train.astype(np.float32))
if pretrain_backbone:
_pretrain_student_backbone(model, x_t, input_dim=input_dim, hidden_dim=hidden_dim)
opt = torch.optim.AdamW(model.parameters(), lr=lr, weight_decay=weight_decay)
model.train()
for epoch in range(epochs):
opt.zero_grad()
logits = model(x_t)
ce_loss = F.binary_cross_entropy_with_logits(logits, y_t)
if aux_alpha_max > 0.0:
# Brief warmup aligns head with pre-trained geometry; fast ramp resists weak error fit
warmup = 2
progress = max(0.0, min(1.0, (epoch - warmup) / 8.0))
alpha_t = aux_alpha_max * progress
with torch.no_grad():
probs = torch.sigmoid(logits)
# Balanced adaptive median threshold prevents minority collapse (Burns et al. 2023)
thresh = torch.quantile(probs, 0.50)
y_hat = (probs >= thresh).float()
aux_loss = F.binary_cross_entropy_with_logits(logits, y_hat)
loss = (1.0 - alpha_t) * ce_loss + alpha_t * aux_loss
else:
loss = ce_loss
loss.backward()
opt.step()
model.eval()
return model
def run_weak_to_strong_benchmark(
seed: int = 42,
quick: bool = False,
) -> dict[str, Any]:
"""Run Article #11 Weak-to-Strong Superalignment benchmark in PyTorch CPU."""
cfg = WeakToStrongConfig(
n_train=640 if quick else 900,
n_eval=320 if quick else 450,
epochs_ceiling=48 if quick else 60,
epochs_naive=95 if quick else 115,
epochs_aux=38 if quick else 44,
seed=seed,
)
ds = build_superalignment_dataset(
n_train=cfg.n_train,
n_eval=cfg.n_eval,
input_dim=cfg.input_dim,
seed=cfg.seed,
)
y_true_ev = ds["y_true_eval"]
y_weak_ev = ds["y_weak_eval"]
blind_ev = ds["blind_eval"]
weak_acc = float(np.mean(y_weak_ev == y_true_ev))
weak_blind_acc = float(np.mean(y_weak_ev[blind_ev] == y_true_ev[blind_ev]))
weak_majority_acc = float(np.mean(y_weak_ev[~blind_ev] == y_true_ev[~blind_ev]))
# 1. Strong Ceiling (Oracle Gold Labels)
ceiling_model = _train_student_model(
x_train=ds["x_train"],
y_target_train=ds["y_true_train"],
input_dim=cfg.input_dim,
hidden_dim=cfg.hidden_dim,
epochs=cfg.epochs_ceiling,
lr=cfg.lr,
weight_decay=1e-2,
aux_alpha_max=0.0,
seed=cfg.seed + 1,
)
ceiling_eval = _eval_binary_classifier(ceiling_model, ds["x_eval"], y_true_ev, y_weak_ev, blind_ev)
ceiling_acc = ceiling_eval["accuracy"]
# 2. Naive Cross-Entropy Weak->Strong (high epochs, low regularization -> imitates weak errors!)
naive_model = _train_student_model(
x_train=ds["x_train"],
y_target_train=ds["y_weak_train"],
input_dim=cfg.input_dim,
hidden_dim=cfg.hidden_dim,
epochs=cfg.epochs_naive,
lr=1.4 * cfg.lr,
weight_decay=1e-4,
aux_alpha_max=0.0,
seed=cfg.seed + 2,
)
naive_eval = _eval_binary_classifier(naive_model, ds["x_eval"], y_true_ev, y_weak_ev, blind_ev)
naive_pgr = compute_pgr(weak_acc, naive_eval["accuracy"], ceiling_acc)
# 3. Direct Confidence-Weighted AuxConf Weak->Strong (regularized + AuxConf self-sharpening)
aux_model = _train_student_model(
x_train=ds["x_train"],
y_target_train=ds["y_weak_train"],
input_dim=cfg.input_dim,
hidden_dim=cfg.hidden_dim,
epochs=cfg.epochs_aux,
lr=0.45 * cfg.lr,
weight_decay=2.5e-1,
aux_alpha_max=cfg.aux_alpha_max,
seed=cfg.seed + 3,
)
aux_eval = _eval_binary_classifier(aux_model, ds["x_eval"], y_true_ev, y_weak_ev, blind_ev)
aux_pgr = compute_pgr(weak_acc, aux_eval["accuracy"], ceiling_acc)
# 4. Intermediate Model Bootstrapping (w -> m -> s) + AuxConf
# Bottlenecked intermediate teacher learns global representation without overfitting shortcut x[:, 10]
inter_model = _train_student_model(
x_train=ds["x_train"],
y_target_train=ds["y_weak_train"],
input_dim=cfg.input_dim,
hidden_dim=24,
epochs=32 if quick else 38,
lr=4.5e-3,
weight_decay=1.2e-1,
aux_alpha_max=0.68,
seed=cfg.seed + 4,
)
inter_eval = _eval_binary_classifier(inter_model, ds["x_eval"], y_true_ev, y_weak_ev, blind_ev)
inter_pgr = compute_pgr(weak_acc, inter_eval["accuracy"], ceiling_acc)
with torch.no_grad():
inter_probs_tr = torch.sigmoid(inter_model(torch.from_numpy(ds["x_train"]))).numpy()
y_inter_train = (inter_probs_tr >= 0.5).astype(np.int64)
boot_model = _train_student_model(
x_train=ds["x_train"],
y_target_train=y_inter_train,
input_dim=cfg.input_dim,
hidden_dim=cfg.hidden_dim,
epochs=cfg.epochs_aux,
lr=cfg.lr,
weight_decay=4e-2,
aux_alpha_max=cfg.aux_alpha_max,
seed=cfg.seed + 5,
)
boot_eval = _eval_binary_classifier(boot_model, ds["x_eval"], y_true_ev, y_weak_ev, blind_ev)
boot_pgr = compute_pgr(weak_acc, boot_eval["accuracy"], ceiling_acc)
# In-memory safetensors round-trip audit on best bootstrapped strong student
import tempfile
reloaded = copy.deepcopy(boot_model)
for p in reloaded.parameters():
with torch.no_grad():
p.zero_()
with tempfile.TemporaryDirectory() as tmp:
ckpt = save_safetensors_checkpoint(boot_model, Path(tmp) / "strong_student.safetensors")
load_safetensors_checkpoint(reloaded, ckpt)
probe = torch.from_numpy(ds["x_eval"][:32])
with torch.no_grad():
st_diff = float((boot_model(probe) - reloaded(probe)).abs().max().item())
return {
"n_train": cfg.n_train,
"n_eval": cfg.n_eval,
"blind_spot_fraction": float(np.mean(blind_ev)),
"weak_teacher": {
"accuracy": weak_acc,
"blind_spot_accuracy": weak_blind_acc,
"majority_accuracy": weak_majority_acc,
},
"strong_ceiling": {
**ceiling_eval,
"pgr": 1.0,
},
"naive_ce_w2s": {
**naive_eval,
"pgr": naive_pgr,
},
"aux_conf_w2s": {
**aux_eval,
"pgr": aux_pgr,
},
"intermediate_m": {
**inter_eval,
"pgr": inter_pgr,
},
"bootstrapped_aux_conf_w2s": {
**boot_eval,
"pgr": boot_pgr,
},
"safetensors_roundtrip_max_diff": st_diff,
}
def run_full_ch22_wb22_benchmarks(
seed: int = 42,
quick: bool = False,
) -> dict[str, Any]:
"""Run all WB-Ch22 benchmarks (#9, #10, #11) and format standardized workbench_panels."""
art9 = run_reward_ensemble_overoptimization_experiment(seed=seed, quick=quick)
art10 = run_judge_bias_and_debiasing_benchmark(seed=seed, quick=quick)
art11 = run_weak_to_strong_benchmark(seed=seed, quick=quick)
unp = art9["unpenalized_single_rm"]["final"]
kl_s = art9["kl_regularized_single_rm"]["final"]
uwo = art9["kl_uwo_ensemble"]["final"]
gao = art9["gao_scaling_curve"]
nj = art10["naive_judge"]
cj = art10["calibrated_debiased_judge"]
ds_p = art10["dawid_skene_panel"]
imp = art10["improvements"]
wt = art11["weak_teacher"]
sc = art11["strong_ceiling"]
nce = art11["naive_ce_w2s"]
ac = art11["aux_conf_w2s"]
boot = art11["bootstrapped_aux_conf_w2s"]
workbench_panels = {
"kpis": [
{
"id": "kpi_goodhart_gold_recovery",
"label": "Goodhart Defense: UWO Ensemble Gold",
"value": f"{uwo['gold_reward']:.2f}",
"unit": f"(vs Naive {unp['gold_reward']:.2f})",
"status": "ok",
"detail": (
f"Unpenalized single RM hits proxy={unp['proxy_reward']:.2f} at KL={unp['d_kl']:.1f} "
f"but crashes gold by {art9['unpenalized_single_rm']['gold_cliff_drop']:.2f}; "
f"KL+UWO cuts OOD std to {uwo['ensemble_std']:.3f}."
),
},
{
"id": "kpi_gao_optimal_dstar",
"label": "Gao et al. Peak KL Distance d*",
"value": f"{gao['d_star']:.2f}",
"unit": f"(KL*={gao['kl_star']:.2f} nats)",
"status": "ok",
"detail": (
f"Analytical Goodhart cliff peak R_gold(d*)={gao['gold_peak']:.3f}; "
f"collapses below 0 beyond d_zero={gao['d_zero']:.2f}."
),
},
{
"id": "kpi_judge_flip_elimination",
"label": "Judge Position Flip Rate",
"value": f"{100.0 * cj['position_flip_rate']:.1f}%",
"unit": f"(from {100.0 * nj['position_flip_rate']:.1f}%)",
"status": "ok",
"detail": (
f"Two-way position-swapped averaging enforces 100% permutation symmetry "
f"and eliminates -{100.0 * imp['flip_rate_drop']:.1f}pp positional flips."
),
},
{
"id": "kpi_judge_cohens_kappa",
"label": "Calibrated Judge Cohen's kappa",
"value": f"{cj['cohens_kappa']:.3f}",
"unit": f"(+{imp['kappa_gain']:.3f} vs Naive)",
"status": "ok",
"detail": (
f"LC Logistic + Rubric Invariance + Dawid-Skene EM lifts stress accuracy "
f"from {100.0 * nj['stress_accuracy']:.1f}% to {100.0 * cj['stress_accuracy']:.1f}% "
f"and cuts ECE {nj['ece']:.3f}->{cj['ece']:.3f}."
),
},
{
"id": "kpi_w2s_pgr_recovered",
"label": "Weak-to-Strong PGR (AuxConf+Boot)",
"value": f"{boot['pgr']:.3f}",
"unit": f"(vs Naive CE {nce['pgr']:.3f})",
"status": "ok",
"detail": (
f"Strong student jumps from WeakTeacher {100.0 * wt['accuracy']:.1f}% to "
f"{100.0 * boot['accuracy']:.1f}% (Ceiling {100.0 * sc['accuracy']:.1f}%); "
f"blind-spot {100.0 * wt['blind_spot_accuracy']:.1f}% -> "
f"{100.0 * boot['blind_spot_accuracy']:.1f}%."
),
},
{
"id": "kpi_safetensors_parity",
"label": "Safetensors Round-Trip Parity",
"value": f"{art11['safetensors_roundtrip_max_diff']:.1e}",
"unit": "(Zero-Pickle Guard)",
"status": "ok",
"detail": (
"Exact 0.0 logit parity reloading StrongStudentMLP via safetensors; "
"AST guard blocks pickle/joblib/dill/marshal."
),
},
],
"bars": [
{
"id": "bar_goodhart_gold_vs_proxy",
"title": "Article #9: Gold Truth Score Under RM Optimization (Higher is Better)",
"metric_label": "True Gold Utility",
"items": [
{
"label": "Unpenalized Single RM (Goodhart Cliff)",
"value": max(0.0, unp["gold_reward"]),
"display": (
f"{unp['gold_reward']:.2f} "
f"(proxy={unp['proxy_reward']:.1f}, KL={unp['d_kl']:.1f})"
),
"css_class": "is-slow",
},
{
"label": "KL-Regularized Single RM",
"value": max(0.0, kl_s["gold_reward"]),
"display": f"{kl_s['gold_reward']:.2f} (KL={kl_s['d_kl']:.2f})",
"css_class": "is-mid",
},
{
"label": "KL + Conservative UWO Ensemble",
"value": max(0.0, uwo["gold_reward"]),
"display": (
f"{uwo['gold_reward']:.2f} "
f"(KL={uwo['d_kl']:.2f}, std={uwo['ensemble_std']:.2f})"
),
"css_class": "is-fast",
},
],
},
{
"id": "bar_judge_bias_reduction",
"title": "Article #10: LLM-Judge Stress Accuracy & Agreement (%)",
"metric_label": "Accuracy / Metric (%)",
"items": [
{
"label": "Naive Judge Adversarial Stress Acc",
"value": 100.0 * nj["stress_accuracy"],
"display": (
f"{100.0 * nj['stress_accuracy']:.1f}% "
f"(Flip {100.0 * nj['position_flip_rate']:.1f}%)"
),
"css_class": "is-slow",
},
{
"label": "Two-Way Position Swap Only (Overall)",
"value": 100.0 * art10["two_way_swap_only"]["accuracy"],
"display": f"{100.0 * art10['two_way_swap_only']['accuracy']:.1f}% (Flip 0.0%)",
"css_class": "is-mid",
},
{
"label": "Dawid-Skene Panel EM Consensus",
"value": 100.0 * ds_p["dawid_skene_acc"],
"display": (
f"{100.0 * ds_p['dawid_skene_acc']:.1f}% "
f"(vs avg {100.0 * ds_p['mean_individual_acc']:.1f}%)"
),
"css_class": "is-fast",
},
{
"label": "Calibrated Judge Stress Acc (LC+DS)",
"value": 100.0 * cj["stress_accuracy"],
"display": f"{100.0 * cj['stress_accuracy']:.1f}% (kappa={cj['cohens_kappa']:.3f})",
"css_class": "is-fast",
},
],
},
{
"id": "bar_w2s_overall_accuracy",
"title": "Article #11: Weak-to-Strong Superalignment Accuracy (%)",
"metric_label": "Held-out Accuracy (%)",
"items": [
{
"label": "Weak Teacher Baseline (Surface)",
"value": 100.0 * wt["accuracy"],
"display": f"{100.0 * wt['accuracy']:.1f}% (PGR=0.00)",
"css_class": "is-slow",
},
{
"label": "Naive CE Weak->Strong (Imitation)",
"value": 100.0 * nce["accuracy"],
"display": f"{100.0 * nce['accuracy']:.1f}% (PGR={nce['pgr']:.2f})",
"css_class": "is-mid",
},
{
"label": "AuxConf Weak->Strong",
"value": 100.0 * ac["accuracy"],
"display": f"{100.0 * ac['accuracy']:.1f}% (PGR={ac['pgr']:.2f})",
"css_class": "is-fast",
},
{
"label": "Bootstrapped w->m->s + AuxConf",
"value": 100.0 * boot["accuracy"],
"display": f"{100.0 * boot['accuracy']:.1f}% (PGR={boot['pgr']:.2f})",
"css_class": "is-fast",
},
],
},
{
"id": "bar_w2s_blind_spot_recovery",
"title": "Article #11: Accuracy on Weak Teacher's Systematic Blind Spot (%)",
"metric_label": "Blind-Spot Accuracy (%)",
"items": [
{
"label": "Weak Teacher (Blind Spot)",
"value": 100.0 * wt["blind_spot_accuracy"],
"display": f"{100.0 * wt['blind_spot_accuracy']:.1f}%",
"css_class": "is-slow",
},
{
"label": "Naive CE Student (Blind Spot)",
"value": 100.0 * nce["blind_spot_accuracy"],
"display": f"{100.0 * nce['blind_spot_accuracy']:.1f}%",
"css_class": "is-mid",
},
{
"label": "Bootstrapped AuxConf (Blind Spot)",
"value": 100.0 * boot["blind_spot_accuracy"],
"display": f"{100.0 * boot['blind_spot_accuracy']:.1f}%",
"css_class": "is-fast",
},
{
"label": "Strong Oracle Ceiling (Blind Spot)",
"value": 100.0 * sc["blind_spot_accuracy"],
"display": f"{100.0 * sc['blind_spot_accuracy']:.1f}%",
"css_class": "is-fast",
},
],
},
],
"tables": [
{
"id": "tbl_goodhart_overopt",
"title": "Article #9: Reward Model Over-Optimization vs Conservative UWO Defense",
"columns": [
"Policy Objective",
"Proxy Reward",
"True Gold Score",
"KL Drift & OOD Std",
],
"rows": [
[
"Unpenalized Single RM (beta=0)",
f"{unp['proxy_reward']:.2f}",
(
f"{unp['gold_reward']:.2f} "
f"(drop {art9['unpenalized_single_rm']['gold_cliff_drop']:.2f})"
),
f"KL={unp['d_kl']:.2f}, std={unp['ensemble_std']:.2f}",
],
[
"KL-Regularized Single RM",
f"{kl_s['proxy_reward']:.2f}",
f"{kl_s['gold_reward']:.2f}",
f"KL={kl_s['d_kl']:.2f}, std={kl_s['ensemble_std']:.2f}",
],
[
"KL + UWO Ensemble (mu - lambda*sigma)",
f"{uwo['proxy_reward']:.2f}",
f"{uwo['gold_reward']:.2f} (SAFE OPTIMUM)",
f"KL={uwo['d_kl']:.2f}, std={uwo['ensemble_std']:.2f}",
],
],
},
{
"id": "tbl_judge_debiasing_audit",
"title": "Article #10: LLM-as-a-Judge Bias & Calibration Audit (Held-Out Eval)",
"columns": [
"Judge Pipeline",
"Position Flip Rate",
"Stress Acc & Verbosity Corr",
"Cohen's kappa & ECE",
],
"rows": [
[
"Naive Biased Judge (Single Order)",
f"{100.0 * nj['position_flip_rate']:.1f}%",
(
f"Stress {100.0 * nj['stress_accuracy']:.1f}% | "
f"len_r={nj['verbosity_bias_corr']:.3f}"
),
f"kappa={nj['cohens_kappa']:.3f}, ECE={nj['ece']:.3f}",
],
[
"Two-Way Position Swap Only",
f"{100.0 * art10['two_way_swap_only']['position_flip_rate']:.1f}%",
f"Overall {100.0 * art10['two_way_swap_only']['accuracy']:.1f}%",
f"kappa={art10['two_way_swap_only']['cohens_kappa']:.3f}",
],
[
"Calibrated (Swap + LC + Dawid-Skene)",
f"{100.0 * cj['position_flip_rate']:.1f}%",
(
f"Stress {100.0 * cj['stress_accuracy']:.1f}% | "
f"len_r={cj['verbosity_bias_corr']:.3f}"
),
f"kappa={cj['cohens_kappa']:.3f}, ECE={cj['ece']:.3f}",
],
],
},
{
"id": "tbl_w2s_superalignment",
"title": "Article #11: Weak-to-Strong Generalization & PGR Benchmark (PyTorch CPU)",
"columns": [
"Model Variant",
"Held-Out Acc",
"Blind-Spot Acc",
"PGR & Weak Agreement",
],
"rows": [
[
"Weak Teacher (Surface Baseline)",
f"{100.0 * wt['accuracy']:.1f}%",
f"{100.0 * wt['blind_spot_accuracy']:.1f}%",
"PGR = 0.000 (ref)",
],
[
"Naive CE Weak->Strong",
f"{100.0 * nce['accuracy']:.1f}%",
f"{100.0 * nce['blind_spot_accuracy']:.1f}%",
f"PGR={nce['pgr']:.3f}, agree_w={100.0 * nce['weak_agreement']:.1f}%",
],
[
"AuxConf Weak->Strong",
f"{100.0 * ac['accuracy']:.1f}%",
f"{100.0 * ac['blind_spot_accuracy']:.1f}%",
f"PGR={ac['pgr']:.3f}, agree_w={100.0 * ac['weak_agreement']:.1f}%",
],
[
"Bootstrapped (w->m->s) + AuxConf",
f"{100.0 * boot['accuracy']:.1f}%",
f"{100.0 * boot['blind_spot_accuracy']:.1f}%",
f"PGR={boot['pgr']:.3f}, agree_w={100.0 * boot['weak_agreement']:.1f}%",
],
[
"Strong Ceiling (Oracle Gold)",
f"{100.0 * sc['accuracy']:.1f}%",
f"{100.0 * sc['blind_spot_accuracy']:.1f}%",
"PGR = 1.000 (ceiling)",
],
],
},
{
"id": "tbl_safety_decision_playbook",
"title": "2026 Production AI Safety & Evaluation Decision Playbook",
"columns": [
"Failure Mode",
"Detection Telemetry",
"Primary Defense",
"Production Guardrail",
],
"rows": [
[
"Goodhart Reward Hacking (#9)",
"Proxy up while holdout/gold drops; KL > d*",
"KL beta + UWO Ensemble (mu - lambda*sigma)",
"Route verifiable tasks to RLVR; refresh RM",
],
[
"Judge Position & Verbosity (#10)",
"Flip rate > 5%; high length correlation",
"Two-Way Swap + AlpacaEval LC Regression",
"0.0% swap flip rate; counterfactual len=0",
],
[
"Sycophancy & Rubric Hack (#10)",
"Stress suite drop > 10pp; low kappa",
"Rubric Invariance Filter + Dawid-Skene EM",
"Require Cohen's kappa >= 0.70 vs gold",
],
[
"Weak-Supervisor Imitation (#11)",
"Low PGR (< 0.4); high weak-error fit",
"AuxConf self-sharpening + w->m->s Bootstrap",
"Track PGR > 0.65 & safetensors=0.0",
],
],
},
],
}
return {
"config": {
"seed": seed,
"quick": quick,
"torch_version": torch.__version__,
"device": "cpu",
},
"workbench_panels": workbench_panels,
"article9_reward_hacking": art9,
"article10_llm_judge": art10,
"article11_weak_to_strong": art11,
}
"""End-to-end CLI benchmark runner for WB-Ch22: AI Safety, Reward Hacking, Judge Bias & Superalignment."""
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 ai_safety_superalignment_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 ai_safety_superalignment_lab.weak_to_strong_superalignment import ( # noqa: E402
run_full_ch22_wb22_benchmarks,
)
def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
"""Parse CLI arguments for WB-Ch22 benchmark execution."""
parser = argparse.ArgumentParser(
description=(
"Run WB-Ch22: Goodhart Reward Hacking & UWO Ensemble (#9), "
"LLM-as-Judge Bias Calibration (#10), Weak-to-Strong Superalignment (#11)."
)
)
parser.add_argument("--seed", type=int, default=42, help="Deterministic RNG seed.")
parser.add_argument(
"--quick",
action="store_true",
help="Run lighter sample/step counts for fast CI verification (<4s CPU).",
)
parser.add_argument(
"--output",
type=str,
default="artifacts/ch22_wb22_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 WB-Ch22 benchmarks, print telemetry summary, and write JSON artifact."""
args = parse_args(argv)
payload = run_full_ch22_wb22_benchmarks(seed=args.seed, quick=args.quick)
payload["config"]["output"] = args.output
a9 = payload["article9_reward_hacking"]
gao = a9["gao_scaling_curve"]
unp = a9["unpenalized_single_rm"]
uwo = a9["kl_uwo_ensemble"]
a10 = payload["article10_llm_judge"]
nj = a10["naive_judge"]
cj = a10["calibrated_debiased_judge"]
dsp = a10["dawid_skene_panel"]
a11 = payload["article11_weak_to_strong"]
wt = a11["weak_teacher"]
sc = a11["strong_ceiling"]
nce = a11["naive_ce_w2s"]
ac = a11["aux_conf_w2s"]
boot = a11["bootstrapped_aux_conf_w2s"]
print("=== Ch 22 + WB-Ch22: AI Safety, Reward Hacking & Superalignment (#9, #10, #11) ===")
print(
f"[#9 Goodhart] Gao d*={gao['d_star']:.2f} (R_gold*={gao['gold_peak']:.3f}) | "
f"Unpenalized RM(proxy={unp['final']['proxy_reward']:.2f}, "
f"gold={unp['final']['gold_reward']:.2f}, drop={unp['gold_cliff_drop']:.2f}, "
f"KL={unp['final']['d_kl']:.1f}) vs "
f"KL+UWO(gold={uwo['final']['gold_reward']:.2f}, "
f"std={uwo['final']['ensemble_std']:.3f}, KL={uwo['final']['d_kl']:.2f})"
)
print(
f"[#10 Judge] FlipRate {100.0 * nj['position_flip_rate']:.1f}% -> "
f"{100.0 * cj['position_flip_rate']:.1f}% | "
f"StressAcc {100.0 * nj['stress_accuracy']:.1f}% -> {100.0 * cj['stress_accuracy']:.1f}% | "
f"VerbCorr {nj['verbosity_bias_corr']:.3f} -> {cj['verbosity_bias_corr']:.3f} | "
f"Kappa {nj['cohens_kappa']:.3f} -> {cj['cohens_kappa']:.3f} | "
f"DS_Acc={100.0 * dsp['dawid_skene_acc']:.1f}% (ECE {nj['ece']:.3f}->{cj['ece']:.3f})"
)
print(
f"[#11 Weak->Strong] Weak={100.0 * wt['accuracy']:.1f}% "
f"(blind={100.0 * wt['blind_spot_accuracy']:.1f}%) | "
f"NaiveCE={100.0 * nce['accuracy']:.1f}% (PGR={nce['pgr']:.3f}) | "
f"AuxConf={100.0 * ac['accuracy']:.1f}% (PGR={ac['pgr']:.3f}) | "
f"Bootstrapped={100.0 * boot['accuracy']:.1f}% "
f"(blind={100.0 * boot['blind_spot_accuracy']:.1f}%, PGR={boot['pgr']:.3f}) | "
f"Ceiling={100.0 * sc['accuracy']:.1f}% | Safetensors={a11['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 WB-Ch22 (ai_safety_superalignment_lab)."""
from __future__ import annotations
import ast
import json
import math
import subprocess
import sys
from pathlib import Path
import numpy as np
import pytest
import torch
from pydantic import ValidationError
from ai_safety_superalignment_lab import (
GoodhartConfig,
JudgeAuditConfig,
StrongStudentMLP,
WeakToStrongConfig,
best_of_n_kl,
build_superalignment_dataset,
compute_cohens_kappa,
compute_pgr,
dawid_skene_em,
gao_overoptimization_curve,
generate_synthetic_judge_pairs,
load_safetensors_checkpoint,
run_judge_bias_and_debiasing_benchmark,
run_kl_penalty_sweep,
run_reward_ensemble_overoptimization_experiment,
run_weak_to_strong_benchmark,
save_safetensors_checkpoint,
)
LAB_ROOT = Path(__file__).resolve().parents[1]
BANNED_DESERIALIZERS = {"pickle", "joblib", "cloudpickle", "dill", "shelve", "marshal"}
@pytest.fixture(scope="module")
def shared_art9_result() -> dict[str, object]:
"""Run Article #9 Goodhart over-optimization experiment once per module."""
return run_reward_ensemble_overoptimization_experiment(seed=42, quick=True)
@pytest.fixture(scope="module")
def shared_art10_result() -> dict[str, object]:
"""Run Article #10 LLM-Judge debiasing benchmark once per module."""
return run_judge_bias_and_debiasing_benchmark(seed=42, quick=True)
@pytest.fixture(scope="module")
def shared_art11_result() -> dict[str, object]:
"""Run Article #11 Weak-to-Strong superalignment benchmark once per module."""
return run_weak_to_strong_benchmark(seed=42, quick=True)
def test_01_pydantic_configs_strict_forbid() -> None:
"""All Pydantic v2 configs strictly forbid unknown fields and invalid boundaries."""
with pytest.raises(ValidationError):
GoodhartConfig(unexpected_param=1.0) # type: ignore[call-arg]
with pytest.raises(ValidationError):
JudgeAuditConfig(bad_flag=True) # type: ignore[call-arg]
with pytest.raises(ValidationError):
WeakToStrongConfig(extra_field="invalid") # type: ignore[call-arg]
with pytest.raises(ValidationError):
GoodhartConfig(ensemble_size=1)
with pytest.raises(ValidationError):
WeakToStrongConfig(aux_alpha_max=1.2)
def test_02_best_of_n_kl_exact_formula_and_monotonicity() -> None:
"""Best-of-N KL equals log(N) - (N - 1) / N, is 0 at N=1, and strictly increases with N."""
assert best_of_n_kl(1) == 0.0
ns = [1, 2, 4, 8, 16, 64, 256, 1024]
kls = [best_of_n_kl(n) for n in ns]
for n, kl in zip(ns, kls, strict=True):
expected = math.log(float(n)) - (float(n) - 1.0) / float(n)
assert abs(kl - expected) < 1e-12
assert all(kls[i] < kls[i + 1] for i in range(len(kls) - 1))
with pytest.raises(ValueError):
best_of_n_kl(0)
def test_03_gao_overoptimization_curve_unimodal_cliff() -> None:
"""Gao et al. proxy grows monotonically while gold reward peaks at d* and collapses below 0."""
d_grid = np.linspace(0.0, 8.0, 81)
curve = gao_overoptimization_curve(d_grid, alpha_rm=0.42, beta_rm=0.24, alpha_proxy=0.38)
proxies = curve["proxy_reward"]
golds = curve["gold_reward"]
assert proxies[0] == 0.0
assert all(proxies[i] < proxies[i + 1] for i in range(len(proxies) - 1))
peak_idx = int(np.argmax(golds))
d_at_peak = curve["d_values"][peak_idx]
assert abs(d_at_peak - curve["d_star"]) < 0.12
assert golds[peak_idx] > 0.45
assert golds[-1] < 0.0
assert curve["d_zero"] > curve["d_star"]
def test_04_unpenalized_rm_suffers_goodhart_cliff_vs_uwo_ensemble(
shared_art9_result: dict[str, object],
) -> None:
"""Unpenalized single RM inflates proxy & KL while crashing gold; KL+UWO prevents exploitation."""
unp = shared_art9_result["unpenalized_single_rm"]
uwo = shared_art9_result["kl_uwo_ensemble"]
assert isinstance(unp, dict) and isinstance(uwo, dict)
unp_fin = unp["final"]
uwo_fin = uwo["final"]
assert unp_fin["proxy_reward"] > uwo_fin["proxy_reward"]
assert unp_fin["d_kl"] > uwo_fin["d_kl"] * 2.0
assert unp["gold_cliff_drop"] > 0.50
assert uwo_fin["gold_reward"] > unp_fin["gold_reward"] + 0.50
assert uwo_fin["ensemble_std"] < unp_fin["ensemble_std"]
def test_05_kl_regularization_bounds_policy_drift() -> None:
"""Increasing KL penalty beta monotonically contracts final policy KL drift."""
sweep = run_kl_penalty_sweep(kl_betas=(0.15, 0.55, 1.40, 3.20, 6.50), quick=True)
drifts = [row["final_d_kl"] for row in sweep]
assert len(drifts) == 5
assert all(drifts[i] > drifts[i + 1] for i in range(len(drifts) - 1))
assert sweep[-1]["final_d_kl"] < 2.5
def test_06_judge_position_swap_eliminates_flip_rate(
shared_art10_result: dict[str, object],
) -> None:
"""Naive judge flips heavily on A/B swap while Two-Way Swap eliminates flip rate to exact 0.0."""
naive = shared_art10_result["naive_judge"]
swap = shared_art10_result["two_way_swap_only"]
cal = shared_art10_result["calibrated_debiased_judge"]
assert isinstance(naive, dict) and isinstance(swap, dict) and isinstance(cal, dict)
assert naive["position_flip_rate"] > 0.20
assert swap["position_flip_rate"] == 0.0
assert cal["position_flip_rate"] == 0.0
assert cal["accuracy"] > naive["accuracy"]
def test_07_judge_length_controlled_regression_debiasing(
shared_art10_result: dict[str, object],
) -> None:
"""Naive judge exhibits strong verbosity inflation; LC calibration sharply reduces length bias."""
naive = shared_art10_result["naive_judge"]
cal = shared_art10_result["calibrated_debiased_judge"]
imp = shared_art10_result["improvements"]
assert isinstance(naive, dict) and isinstance(cal, dict) and isinstance(imp, dict)
assert naive["verbosity_bias_corr"] > 0.25
assert abs(cal["verbosity_bias_corr"]) < abs(naive["verbosity_bias_corr"]) * 0.55
assert imp["verbosity_corr_abs_reduction"] > 0.20
assert cal["gold_corr"] > naive["gold_corr"] + 0.15
def test_08_judge_sycophancy_and_rubric_hack_stress_defense(
shared_art10_result: dict[str, object],
) -> None:
"""Adversarial sycophancy & rubric traps degrade naive judge sharply; calibrated judge holds firm."""
naive = shared_art10_result["naive_judge"]
cal = shared_art10_result["calibrated_debiased_judge"]
assert isinstance(naive, dict) and isinstance(cal, dict)
assert naive["stress_drop"] > 0.15
assert cal["stress_accuracy"] >= 0.80
assert cal["stress_accuracy"] > naive["stress_accuracy"] + 0.20
# Verify zero gold_winner leakage into sycophancy / rubric trap covariates
pairs = generate_synthetic_judge_pairs(JudgeAuditConfig(n_pairs=180, seed=42))
gold = np.array([p["gold_winner"] for p in pairs], dtype=np.float64)
syc = np.array([p["sycophancy_nudge"] for p in pairs], dtype=np.float64)
trap = np.array([p["rubric_trap_diff"] for p in pairs], dtype=np.float64)
assert abs(float(np.corrcoef(syc, gold)[0, 1])) < 0.15
assert abs(float(np.corrcoef(trap, gold)[0, 1])) < 0.15
def test_09_cohens_kappa_and_dawid_skene_panel_calibration(
shared_art10_result: dict[str, object],
) -> None:
"""Verify Cohen's kappa exact bounds and Dawid-Skene EM lifting agreement & calibration ECE."""
y = np.array([1, 0, 1, 1, 0, 0, 1, 0], dtype=np.int64)
assert compute_cohens_kappa(y, y) == pytest.approx(1.0, abs=1e-12)
assert compute_cohens_kappa(y, 1 - y) < 0.0
# Synthetic 3-judge EM test: 1 reliable judge + 2 noisy judges -> EM recovers latent truth
rng = np.random.default_rng(11)
true_z = rng.integers(0, 2, size=200)
v0 = np.where(rng.uniform(size=200) < 0.90, true_z, 1 - true_z)
v1 = np.where(rng.uniform(size=200) < 0.78, true_z, 1 - true_z)
v2 = np.where(rng.uniform(size=200) < 0.76, true_z, 1 - true_z)
ds = dawid_skene_em(np.column_stack([v0, v1, v2]))
em_acc = float(np.mean(ds["predicted_labels"] == true_z))
assert em_acc > 0.88
assert ds["judge_reliabilities"][0] > ds["judge_reliabilities"][2]
naive = shared_art10_result["naive_judge"]
cal = shared_art10_result["calibrated_debiased_judge"]
ds_panel = shared_art10_result["dawid_skene_panel"]
assert isinstance(naive, dict) and isinstance(cal, dict) and isinstance(ds_panel, dict)
assert ds_panel["dawid_skene_acc"] > ds_panel["mean_individual_acc"]
assert cal["cohens_kappa"] >= 0.65
assert cal["cohens_kappa"] > naive["cohens_kappa"] + 0.25
assert cal["ece"] < naive["ece"]
def test_10_pgr_metric_formula_and_boundary_invariants() -> None:
"""PGR returns 0.0 at weak baseline, 1.0 at ceiling, negative if worse, and guards invalid gaps."""
assert compute_pgr(0.70, 0.70, 0.95) == pytest.approx(0.0, abs=1e-12)
assert compute_pgr(0.70, 0.95, 0.95) == pytest.approx(1.0, abs=1e-12)
assert compute_pgr(0.70, 0.875, 0.95) == pytest.approx(0.70, abs=1e-12)
assert compute_pgr(0.70, 0.65, 0.95) < 0.0
with pytest.raises(ValueError):
compute_pgr(0.80, 0.85, 0.80)
def test_11_superalignment_dataset_weak_vs_ceiling_gap(
shared_art11_result: dict[str, object],
) -> None:
"""Dataset exposes genuine weak teacher blind spots (~70-76%) vs strong ceiling (>=93%)."""
ds = build_superalignment_dataset(n_train=300, n_eval=200, seed=42)
assert ds["x_train"].shape == (300, 16)
assert ds["x_eval"].shape == (200, 16)
wt = shared_art11_result["weak_teacher"]
sc = shared_art11_result["strong_ceiling"]
assert isinstance(wt, dict) and isinstance(sc, dict)
assert 0.65 <= wt["accuracy"] <= 0.80
assert wt["blind_spot_accuracy"] < wt["majority_accuracy"] - 0.30
assert sc["accuracy"] >= 0.93
def test_12_naive_ce_imitates_weak_teacher_errors(
shared_art11_result: dict[str, object],
) -> None:
"""Naive CE student fits weak teacher's blind-spot errors closely, capping PGR below 0.50."""
nce = shared_art11_result["naive_ce_w2s"]
boot = shared_art11_result["bootstrapped_aux_conf_w2s"]
assert isinstance(nce, dict) and isinstance(boot, dict)
assert nce["pgr"] < 0.50
assert nce["weak_agreement"] > boot["weak_agreement"]
assert nce["blind_spot_accuracy"] < 0.65
def test_13_aux_conf_and_bootstrapping_beats_weak_teacher_high_pgr(
shared_art11_result: dict[str, object],
) -> None:
"""AuxConf & w->m->s Bootstrapping elicit latent concept, beating weak teacher with PGR > 0.65."""
wt = shared_art11_result["weak_teacher"]
nce = shared_art11_result["naive_ce_w2s"]
ac = shared_art11_result["aux_conf_w2s"]
boot = shared_art11_result["bootstrapped_aux_conf_w2s"]
assert isinstance(wt, dict) and isinstance(nce, dict) and isinstance(ac, dict) and isinstance(boot, dict)
assert ac["accuracy"] > wt["accuracy"] + 0.12
assert boot["accuracy"] > wt["accuracy"] + 0.15
assert boot["accuracy"] > nce["accuracy"] + 0.08
assert boot["pgr"] > 0.65
assert boot["blind_spot_accuracy"] > wt["blind_spot_accuracy"] + 0.35
def test_14_strong_student_safetensors_roundtrip_zero_pickle(tmp_path: Path) -> None:
"""Saving & loading StrongStudentMLP via safetensors yields exact 0.0 logit difference."""
torch.manual_seed(99)
m1 = StrongStudentMLP(input_dim=16, hidden_dim=32).eval()
m2 = StrongStudentMLP(input_dim=16, hidden_dim=32).eval()
ckpt = save_safetensors_checkpoint(m1, tmp_path / "student.safetensors")
load_safetensors_checkpoint(m2, ckpt)
probe = torch.randn(16, 16)
with torch.no_grad():
diff = float((m1(probe) - m2(probe)).abs().max().item())
assert diff == 0.0
def test_15_cli_demo_workbench_json_schema_and_panels(tmp_path: Path) -> None:
"""CLI --quick writes valid JSON with workbench_panels (6 KPIs, 4 bars, 4 tables)."""
out_json = tmp_path / "wb22_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 22 + WB-Ch22" 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
assert data["article11_weak_to_strong"]["bootstrapped_aux_conf_w2s"]["pgr"] > 0.65
def test_16_ast_security_guard_no_unsafe_deserializers() -> None:
"""AST security check forbids pickle, joblib, cloudpickle, dill, shelve, and marshal."""
py_files = [
p
for sub in ("src", "scripts", "tests")
for p in (LAB_ROOT / sub).rglob("*.py")
]
assert len(py_files) >= 5
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
Extremal Goodhart xảy ra khi áp lực tối ưu đưa chính sách vào miền cực trị OOD nơi Reward Model không có dữ liệu ràng buộc; bốn dạng chuẩn gồm Regressional, Extremal, Causal và Adversarial Goodhart.
Best-of-N (WB-Ch22, Tests 02, 03), phát biểu nào CHÍNH XÁC?RewardMLP (WB-Ch22, Tests 04, 05), cơ chế nào ngăn chặn vách đá Goodhart hiệu quả nhất?KL giữ chính sách trong vùng tin cậy.
(A, B) của LLM-as-a-Judge chỉ chạy một chiều (WB-Ch22, Test 06)?+1.15). Trung bình đối xứng trên cả hai hoán vị triệt tiêu thành phần vị trí bậc nhất và đảm bảo p_sym(A, B) + p_sym(B, A) == 1.0.
AlpacaEval LC giải quyết vấn đề lạm phát win-rate do câu trả lời dài dòng (WB-Ch22, Test 07) bằng cách nào?0 trên tập phản thực tế x_ev_cf (không rò nhãn gold) tách riêng đóng góp thực chất của chất lượng câu trả lời khỏi phần thổi phồng độ dài rỗng tuếch.
WB-Ch22, Tests 08, 09), chuỗi hiệu chuẩn đầy đủ Swap + LC + Dawid-Skene EM đạt kết quả nào?EM Dawid-Skene ước lượng đồng thời ma trận nhầm lẫn \(\Pi^{(j)}\) của từng giám khảo và hậu nghiệm nhãn chân lý tiềm ẩn, khai thác tính đa dạng của hội đồng giám khảo để đạt độ chính xác cao hơn mọi giám khảo thành viên.
Weak-to-Strong (WB-Ch22, Tests 10, 11, 12), công thức Performance Gap Recovered (PGR) và nguyên nhân Naive CE thất bại là gì?Naive CE uốn cong biên quyết định để trùng khớp 94.4% với các nhãn sai của thầy yếu thay vì tổng quát hóa theo biểu diễn đúng.
StrongStudentMLP vượt qua lỗi thầy yếu (74.7% tổng thể, 48.0% điểm mù) để đạt PGR > 0.65 trong WB-Ch22 (Tests 13, 14)?AuxConf tự làm sắc nét theo phân vị cân bằng (0.50) và mô hình trung gian thắt cổ chai \(f_m\) lọc lỗi điểm mù trước khi dạy \(f_s\), đưa PGR lên 0.965.
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 Điểm Đỉnh d* Gao et al. (2023) & KL Best-of-N 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Đặt biến \(u = F(y) \sim \text{Uniform}(0,1)\) cho mật độ thống kê thứ tự cực đại \(p_{\text{BoN}}(y) = N u^{N-1} p_{\text{ref}}(y)\) rồi tính tích phân trên \([0, 1]\).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Lấy đạo hàm bậc 1 và 2 của \(R_{\text{gold}}(d) = d(\alpha_{\text{rm}} - \beta_{\text{rm}}\ln d)\) theo \(d > 0\), đối chiếu best_of_n_kl và gao_overoptimization_curve (Tests 02, 03).
Tiêu chí Đáp án & Số đối chứng
\(D_{\text{KL}}(\pi_{\text{BoN}}\|\pi_{\text{ref}}) = \log N - \frac{N-1}{N}\); đạo hàm bằng 0 cho \(d^* = \exp(\alpha_{\text{rm}}/\beta_{\text{rm}} - 1) = 2.117\) (\(D_{\text{KL}}^* = 4.48\) nats, \(R_{\text{gold}}^* = 0.508\)) và rơi xuống âm sau \(d_{\text{zero}} = 5.755\).
Bài tập 2 — Thực nghiệm Hợp thể UWO & Quét Ngưỡng KL Chống Vách đá Goodhart 20%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Viết điều kiện dừng \(\nabla_z R_{\text{proxy}}(z^*) = \beta_{\text{KL}} z^*\) dưới \(\pi_{\text{ref}} = \mathcal{N}(0, I)\) để thấy \(D_{\text{KL}} = \frac{1}{2}\|z^*\|^2\) tỷ lệ nghịch với \(\beta_{\text{KL}}^2\).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
So sánh trực tiếp quỹ đạo tối ưu trên run_reward_ensemble_overoptimization_experiment và run_kl_penalty_sweep (Tests 04, 05).
Tiêu chí Đáp án & Số đối chứng
Unpenalized Single RM đẩy proxy = 174.43 ở KL = 364.28 nhưng sụp gold 106.90 điểm xuống -104.07; KL + UWO (\(\mu - 2.5\sigma\)) cắt bất định std 33.7x (18.71 -> 0.556), giữ KL = 2.40 và bảo toàn gold = +1.43.
Bài tập 3 — Đảo Vị trí Hai chiều & Hồi quy Kiểm soát Độ dài AlpacaEval LC 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Thay hoán vị \((A, B) \leftrightarrow (B, A)\) vào biểu thức \(p_{\text{sym}} = \frac{1}{2}(p_{AB} + 1 - p_{BA})\) để chứng minh \(p_{\text{sym}}(A, B) + p_{\text{sym}}(B, A) = 1\).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Khớp Ridge + LogisticRegression chỉ trên tập hiệu chuẩn tách biệt rồi đánh giá phản thực tế trên x_ev_cf (độ dài bằng 0, không rò nhãn gold) (Tests 06, 07).
Tiêu chí Đáp án & Số đối chứng
Đảo vị trí hai chiều ép Position Flip Rate từ 25.4% xuống đúng 0.0%; hồi quy kiểm soát độ dài LC phản thực tế (x_ev_cf) giảm tương quan độ dài giả 94.7% từ 0.448 xuống 0.024.
Bài tập 4 — Kiểm toán Hội đồng Đa Giám khảo Dawid-Skene EM & Cohen's kappa 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Viết cập nhật E-step hậu nghiệm chân lý \(q_{i,c}\) trong miền log-xác suất để tránh tràn số, và M-step ma trận nhầm lẫn \(\Pi^{(j)}_{c\to k}\) có làm mượt Laplace.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Tính \(\kappa = (p_o - p_e)/(1 - p_e)\) và kiểm chứng mức cải thiện Stress Accuracy & Calibration ECE trong run_judge_bias_and_debiasing_benchmark (Tests 08, 09).
Tiêu chí Đáp án & Số đối chứng
Stress Accuracy vọt từ 47.5% lên 98.3% (+50.8pp), Cohen's kappa tăng từ 0.258 lên 0.983, ECE giảm từ 0.253 xuống 0.021, và hội đồng Dawid-Skene EM đạt 99.2% vượt trung bình giám khảo đơn (81.1%).
Bài tập 5 — Khai mở Năng lực Weak-to-Strong: Naive CE vs AuxConf vs Bootstrapping 20%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Phân tích vì sao Naive CE đạt weak_agreement = 94.4% bằng cách bám chỉ báo miền x[:, 10] để học thuộc lỗi vùng điểm mù.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Giải thích tác dụng tiền huấn luyện DAE, ngưỡng phân vị 0.50 trong AuxConf và mô hình trung gian thắt cổ chai w -> m -> s (Tests 10, 11, 12, 13).
Tiêu chí Đáp án & Số đối chứng
WeakTeacher = 74.7% (48.0% mù), Naive CE = 73.1% (PGR = -0.061); AuxConf đạt 96.2% (PGR = 0.851) và Bootstrapped (w->m->s) đạt 99.1% (98.0% trên điểm mù, PGR = 0.965 > 0.65).
Bài tập 6 — Lưu trữ An toàn Safetensors & Nghiệm thu Trọn gói WB-Ch22 (16/16 Pytest) 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Lưu và nạp StrongStudentMLP qua save_safetensors_checkpoint / load_safetensors_checkpoint và xác minh sai số logit bằng 0.0 (Test 14).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy trọn bộ uv lock, scripts/run_lab_demo.py --seed 42, ruff check, mypy src, và pytest -p no:cacheprovider -v kiểm định cổng AST (Tests 15, 16).
Tiêu chí Đáp án & Số đối chứng
Đạt 16/16 pytest (0 skips), 0 lỗi ruff/mypy, safetensors diff == 0.0, 0 import deserializer rủi ro (pickle/joblib/dill/marshal), và xuất chuẩn artifacts/ch22_wb22_results.json.