Chương 30 — Phương pháp luận Nghiên cứu & Luận văn Khoa học Chuẩn A*/Q1: Giả thuyết, Thực nghiệm Loại trừ, Thống kê Đa Seed, Ngân sách Compute & Viết bài LaTeX
Hoàn thiện Track 1 DSAI: Kiểm định Wilcoxon / hoán vị & IQM rliable đa seed (n=10: +2.5259pp, p=0.003999, kháng 1 outlier crash 39.5%), chống lạm phát đa kiểm định m=20 (FWER 64.0% -> 4.95% Holm / 5.0% BH), kiểm toán Confounder (Fair +4.17pp vs Inflated +4.89pp) & Rò rỉ chia tập (+20.09pp accuracy), hoạch định n*=7 seeds ($41.31 vast.ai RTX 4090) & 8/8 cổng tái lập LaTeX/Rebuttal.
Đơn vị học phần (
Unit ID):T1-P7-U03(Phần 7: Hội thảo Nghiên cứu Tiền tiêu —World Models,Embodied AI& Luận văn Nghiên cứu — Mục lục Phần 7)
Xưởng Thực chiến Song hành: WB-Ch30 — Xưởng Phương pháp luận Nghiên cứu & Luận văn Khoa học (research_methodology_lab)
Định hướng & Truy xuất Nguồn: Hoàn thiện lộ trình Track 1 (DSAI) tại FSDS Research Lab theo Đề cương SOTA 2026 (Chương 30), kết nối nền tảng kiến trúc từ Chương 28 — Mô hình Thế giới,Chương 29(Robotics:DiffusionvsFlow Matching,VLAs&Sim-to-Real) và đánh giá theo chế độ lỗi ở Chương 25.
Công trình Tham chiếu Đã Được Chấp nhận (FSDS Research Lab—RIVF 2026):arXiv:2607.24332vàarXiv:2607.24331.
Bốn Ca Thất bại Nghiên cứu Mở màn: Vì sao Kết quả Đẹp Vẫn Bị Từ chối Tại Hội nghị A*/Q1#
Một ý tưởng thuật toán sắc sảo vẫn thường xuyên nhận đánh giá Reject tại NeurIPS, ICML, ICLR, RIVF hay tạp chí Q1 vì bốn lỗ hổng phương pháp luận lặp đi lặp lại. Cả bốn ca thất bại đều được tái lập định lượng và kiểm toán tự động bằng NumPy thuần + Pydantic v2 tất định (seed=42) trong WB-Ch30 (artifacts/ch30_wb30_results.json):
Minh bạch Bằng chứng Thực thi (WB-Ch30 Kiểm chứng Định lượng):
- Toàn bộ tính toán thống kê (
rliableIQM,Optimality Gap,Stratified Bootstrap 95% CIvớiR = 5,000lần tái mẫu,Paired Sign-Flip Permutation Test,Wilcoxon Signed-Rank Testchính xác/tiệm cận có hiệu chỉnh tie,Holm–Bonferroni&Benjamini–Hochberg), phát hiện biến nhiễu bảng loại trừ (Confounder Detector), bộ kiểm toán rò rỉ dữ liệu trên bài toán phân loại tuyến tínhRidge(960mẫu dọc theo120nhóm bệnh nhân), và bộ giải công suất phi trung tâmStudent-tđều chạy thực trên CPU trongresearch_methodology_labmà không phụ thuộcPyTorchhay API ngoài. - Hai công trình
arXiv:2607.24332vàarXiv:2607.24331được trích dẫn đúng tư cách là bài báo nghiên cứu đã được chấp nhận công bố tạiRIVF 2026dưới sự hướng dẫn của FSDS Research Lab; chương học không suy diễn thêm bất kỳ chi tiết nội bộ nào ngoài nguồn lưu trữ chuẩn của giáo trình.
-
Ca 1 — Thiếu Công suất ở
n=3Seed & Méo Trung bình Khi1Seed Sụp đổ (WB-Ch30, Exp 1A,Test 06):Khi một cải tiến có hiệu ứng thực
+2.44pptrên10seeds (81.97%vs79.53%), nhóm nghiên cứu vội chạy chỉn = 3seeds sẽ chỉ thu đượcdiff_iqm = +1.05pp, khoảng tin cậy95% CI = [-0.45, +2.35]cắt ngang số0,permutation p = 0.4953vàWilcoxon p = 0.500— tự tay vứt bỏ phát hiện thật (âm tính giả). Ngược lại, khi chạy đủn = 10seeds, hiệu ứng đạtdiff_iqm = +2.53pp(95% CI = [+1.66, +3.18]),permutation p = 0.0040,Wilcoxon exact p = 0.0039(W=1.0),Cohen's d = 1.91vàP(X > Y) = 0.860. Nguy hiểm hơn, nếu1/10seed bị sụp gradient xuống39.5%, trung bình cộng lật âm thành-1.42pp(permutation p = 1.0,Wilcoxon p = 0.0840), cònrliableIQMgiữ vững+2.53pp! -
Ca 2 — Ảo giác
p-Hacking Khi Thửm=20Biến thể (FWERBùng nổ Tới64.0%,WB-Ch30, Exp 1B,Test 07):Nếu thử
m = 20cấu hình siêu tham số hoặc tập con kiểm thử dưới giả thuyết không \(H_0\) đúng hoàn toàn tại ngưỡng danh nghĩa \(\alpha = 0.05\), xác suất ít nhất một lần dương tính giả toàn họ vọt lên \(1 - (1 - 0.05)^{20} = \mathbf{64.15\%}\) (đo thực nghiệm qua2,000nghiên cứu mô phỏng đạt64.0%!). Trong minh họa20phép so sánh (17nhiễu thuần +3hiệu ứng thật), cách chọn thô tạo3/17dương tính giả (6lần bác bỏ \(H_0\)). Khi áp dụng hiệu chỉnh bước xuốngHolm–Bonferroni,FWERthực nghiệm quay về4.95%(0/17dương tính giả); cònBenjamini–Hochbergkhống chếFDRkỳ vọng dưới \(H_0\) ở5.0%và giữ trọn3/3phát hiện thật. -
Ca 3 — Đánh tráo Nguyên nhân Bằng Bảng Ablation Trộn Nhiều Yếu tố & Baseline Bỏ Mặc (
WB-Ch30, Exp 2,Tests 09–10):Trên mô phỏng đa seed kèm chọn lọc siêu tham số thực nghiệm (
run_exp2_ablation_confounder_audit), một bản thảo lỗi thay đổi đồng thời 3 yếu tố (arch_gate,cosine_lr,mixup_aug) với15lượt tìm kiếm HP (84.71%) trong khi chạy baseline với1cấu hình mặc định (79.82%), tuyên bố cải thiện+4.89pp. Bộ kiểm toán tự động bắt ngay2lỗiCRITICAL(confounded_multi_factorvàunfair_tuning_asymmetry). Khi chỉnh đối xứng thành8lượt tinh chỉnh đều hai phía và tách bảng trực giao1-yếu tố (clean_audit), baseline thật tăng lên80.50%, bóc tách+0.72ppthiên lệch tinh chỉnh ảo và quy kết chuẩn xác phần đóng góp thật+4.17pp(80.50% -> 84.67%):arch_gate(+2.28pp),mixup_aug(+1.40pp),cosine_lr(+0.31pp), và tương tácarch_gate x mixup_aug(+0.39pp). -
Ca 4 — Bốn Kênh Rò rỉ Dữ liệu Tạo Ảo ảnh
+20.09pp& Vượt Trần Ngân sách GPU (WB-Ch30, Exp 3 & 4,Tests 11–14):Chia ngẫu nhiên bảng dữ liệu dọc
960quan sát (120bệnh nhân \(\times 8\) mốc thời gian) sau khi fitStandardScalertrên toàn bộ tập cộng thêm24mẫu trùng lặp tạo ra4/4kênh rò rỉ (id_overlap = 24,group_leakage = 260,temporal_leakage = 766dòng,preprocessing_leakage = 216). Điểm đánh giá ảo vọt lên88.4%(ROC-AUC 0.968), rồi rơi thẳng xuống68.3%(ROC-AUC 0.868) trên tập chia rời nhóm theo trình tự thời gian — bóc trần+20.09ppảo ảnh rò rỉ. Song song, bộ giảiStudent-ttính được tối thiểun* = 7seeds cho công suất84.9%(\(\ge 80\%\)), giúp tối ưu ma trận66lượt chạy trênvast.ai RTX 4090 Spotchỉ còn$41.31(vượt trần$150rất xa so với$224.38trênOn-Demand A100).
Mục tiêu Học tập (Learning Objectives)#
Sau khi hoàn tất Chương 30 và vượt qua 20/20 bài kiểm thử của WB-Ch30, học viên làm chủ năm năng lực cốt lõi để dẫn dắt một đề tài nghiên cứu từ ý tưởng tới bài báo A*/Q1/RIVF:
- Thiết kế Giả thuyết Kiểm chứng & Đối chứng Công bằng: Viết giả thuyết định hướng có tiêu chí bác bỏ tường minh, chống
HARKing, và áp dụng nguyên tắc đối xứngTune-the-Baseline. - Thống kê Đa Seed Chuẩn
rliable& Kiểm soát Sai số Đa Kiểm định: TínhIQM,Optimality Gap,Stratified Bootstrap 95% CI,Paired Permutation Test(\(R \ge 5{,}000\)), đồng thời hiệu chỉnhp-value bằngHolm–Bonferroni(FWER) vàBenjamini–Hochberg(FDR). - Thiết kế Thực nghiệm Loại trừ Trực giao (
AOI/LOO) & Kiểm toán Rò rỉ: Phân rã tác động chính và tương tác bậc hai, phát hiện nhiễu trộn đa yếu tố và khóa chặt bốn kênh rò rỉ (ID,Group,Temporal,Preprocessing). - Hoạch định Công suất
Student-t(MDE\(\leftrightarrow\)n*) & Ngân sách Đám mây: Quy đổi hiệu ứng kỳ vọng thành số seed tối thiểu \(n^*\) và tối ưu chi phí trênColab/vast.aiSpot kèm dự phòng ngắt phiên. - Kỹ nghệ Bài báo
LaTeXbooktabs& Chiến lược Phản biện (Rebuttal): Cấu trúc IMRaD gắn ma trận Claim–Evidence, xuất bảng tự động tô đậm đồng hạng thống kê, tự chấm cổng tái lập8/8và xử lý phản biện theo phân loạiType A/B/C.
Bảng Ký hiệu Phi Mơ hồ (Disambiguated Notation Contract)#
| Ký hiệu LaTeX | Miền / Đơn vị | Định nghĩa chuẩn trong Chương 30 | Tên biến trong WB-Ch30 |
|---|---|---|---|
| \(\Delta_i, \delta_{\min}\) | \(\mathbb{R}, \mathbb{R}_{>0}\) | Chênh lệch hiệu năng ghép cặp ở seed \(i\) và Ngưỡng Hiệu ứng Tối thiểu Phát hiện được (MDE) |
diff, effect_size_delta |
| \(\operatorname{IQM}, \operatorname{OG}\) | \(\mathbb{R}, \mathbb{R}_{\ge 0}\) | Trung bình tứ phân vị giữa (25%–75%) và Khoảng trống Tối ưu \(\frac{1}{n}\sum (\tau - s_i)_+\) |
method_iqm, optimality_gap_method |
| \(p_{\text{perm}}, d_z, \hat{P}(X>Y)\) | \((0, 1], \mathbb{R}, [0, 1]\) | Trị số \(p\) kiểm định hoán vị ghép cặp (\(R \ge 5{,}000\)), Cohen's \(d_z\) và xác suất trội hơn | permutation_p_value, cohens_d, prob_improvement |
| \(m, \operatorname{FWER}, \operatorname{FDR}\) | \(\mathbb{Z}_{\ge 1}, [0, 1], [0, 1]\) | Số phép kiểm thử đồng thời, tỷ lệ sai lầm toàn họ \(1 - (1 - \alpha)^m\) và tỷ lệ phát hiện sai | m_comparisons, empirical_null_fwer, bh_empirical_null_fdr |
| \(\Delta_{\text{main}}, \Delta_{\text{int}}\) | \(\mathbb{R}, \mathbb{R}\) | Tác động chính đơn yếu tố và tương tác hai chiều \(y_{11} - y_{10} - y_{01} + y_{00}\) | main_effects, interaction_effects |
| \(n^*, 1 - \beta, \sigma_{\text{seed}}\) | \(\mathbb{Z}_{\ge 2}, (0, 1), \mathbb{R}_{>0}\) | Số seed tối thiểu đạt công suất \(1 - \beta = 0.80\) theo phân phối Student-t phi trung tâm |
required_seeds_n, target_power, seed_std |
| \(C_{\text{USD}}, \kappa_{\text{spot}}\) | \(\mathbb{R}_{\ge 0}, \mathbb{R}_{\ge 1}\) | Tổng chi phí đám mây (USD) sau khi nhân hệ số dự phòng ngắt Spot và checkpoint |
total_cost_usd, preemption_overhead_factor |
Trụ cột 1 — Nền tảng Khoa học: Giả thuyết Kiểm chứng, Thống kê Đa Seed rliable & Kiểm soát FWER/FDR#
1.1 Giả thuyết Khả bác bỏ (Falsifiable Hypothesis), Chống HARKing & Nguyên tắc Tune-the-Baseline#
Một công trình nghiên cứu khoa học tại A*/Q1 không bắt đầu từ việc chạy thử mười biến thể rồi tìm câu chuyện giải thích hợp lý hóa kết quả đẹp nhất (Hypothesizing After Results are Known — HARKing). Mọi nghiên cứu chuẩn mực bắt buộc đăng ký trước bộ ba thành phần trước khi chạy lưới thực nghiệm:
- Cơ chế Nhân quả & Biên Phạm vi: Chỉ rõ cơ chế cấu trúc nào tạo ra lợi thế (ví dụ: chuẩn hóa
EMA + VICRegở Chương 28 triệt tiêu nhiễu ngoại sinh) và điều kiện biên khiến giả thuyết bị bác bỏ. - Cặp Giả thuyết Định hướng &
MDE(\(\delta_{\min}\)): Với sai phân ghép cặp \(\Delta_i = M_{\text{new}, i} - M_{\text{base}, i}\) trên \(n\) hạt giống ngẫu nhiên độc lập:\[H_0: \mathbb{E}[\Delta] \le 0 \qquad \text{vs.} \qquad H_1: \mathbb{E}[\Delta] \ge \delta_{\min} > 0.\]Nếu khoảng tin cậy hoặc ngưỡng thực tế không vượt \(\delta_{\min}\), độ phức tạp bổ sung không xứng đáng để đưa vào sản phẩm hay công bố như bước tiến thuật toán. - Tính Đối xứng Tinh chỉnh (
Tune-the-Baseline, Dodge et al. EMNLP 2019): Với \(B\) lượt tìm kiếm siêu tham số ngẫu nhiên trên tập thẩm định có nhiễu \(\sigma\), kỳ vọng giá trị cực đại \(\mathbb{E}[\max_{1 \le b \le B} V_b]\) tăng xấp xỉ \(\sigma\sqrt{2\ln B}\) ngay cả khi không có cải tiến thực sự! Do đó, so sánh một phương pháp mới được chỉnh \(B_{\text{new}} = 15\) lần với baseline giữ tham số mặc định \(B_{\text{base}} = 1\) sẽ tự động sinh ra thiên lệch giả (tuning asymmetry): trong mô phỏngExp 2củaWB-Ch30, chỉ riêng việc chỉnh đều8lượt cho baseline đã nâng điểm cơ sở từ79.82% -> 80.50%, bóc trần+0.72ppảo tưởng từ thiên lệch tinh chỉnh.
1.2 Thống kê Đa Seed Chuẩn rliable, Khoảng tin cậy Bootstrap & Kiểm định Hoán vị#
Trong học sâu và RL, trung bình cộng và độ lệch chuẩn giả định phân phối chuẩn thường sụp đổ khi có hạt giống rơi vào cực tiểu cục bộ hoặc tiệm cận trần 100%. Chuẩn rliable (Agarwal et al., NeurIPS 2021) thay thế bằng bốn thước đo phi tham số vững chắc:
- Trung bình Tứ phân vị Giữa (
Interquartile Mean — IQM): Loại bỏ25%giá trị thấp nhất và25%giá trị cao nhất sau khi sắp xếp tăng dần \(x_{(0)} \le \dots \le x_{(n-1)}\):\[\operatorname{IQM}(\mathbf{x}) = \frac{1}{0.5 n}\sum_{i=0}^{n-1} w_i x_{(i)}, \qquad w_i = \max\!\big(0,\; \min(i + 1, 0.75n) - \max(i, 0.25n)\big).\]Lưu ý sai khác rời rạc khi \(n \bmod 4 \neq 0\): Thư viện gốcgoogle-research/rliablegọiscipy.stats.trim_mean(x, 0.25), tức cắt rời rạcfloor(0.25 * n)phần tử ở mỗi đuôi (ví dụ vớin = 10, bỏ2giá trị đầu và2giá trị cuối rồi lấy trung bình6phần tử giữa), trong khi công thức nội suy tuyến tính liên tục \([0.25n, 0.75n]\) ở trên trùng khớp tuyệt đối vớirliablekhi \(n \bmod 4 = 0\) và mượt theo \(n\) với mọi cỡ mẫu lẻ. Nhờ điểm phá hủy25%,IQMhoàn toàn miễn nhiễm với1hoặc2hạt giống sụp gradient (WB-Ch30Exp 1A: khiseed 2sập về39.5%, trung bình cộng rớt xuống-1.42pptrong khiIQMgiữ nguyên+2.53pp), đồng thời có phương sai nhỏ hơn hẳn trung vị thuần. - Khoảng trống Tối ưu (
Optimality Gap — OG): Đo mức thiếu hụt trung bình so với ngưỡng chuẩn \(\tau\) (ví dụ \(\tau = 100\%\)):\[\operatorname{OG}(\mathbf{x}; \tau) = \frac{1}{n}\sum_{i=1}^n \max(0,\; \tau - x_i).\]ỞExp 1A(n=10), phương pháp mới thu hẹpOptimality Gaptừ20.47xuống18.03. - Xác suất Cải thiện \(\hat{P}(X > Y)\) &
Cohen's d_zGhép cặp:\[\hat{P}(X > Y) = \frac{1}{n^2}\sum_{i=1}^n \sum_{j=1}^n \Big(\mathbf{1}[x_i > y_j] + \tfrac{1}{2}\mathbf{1}[x_i = y_j]\Big), \qquad d_z = \frac{\bar{d}}{s_d}.\] - Bootstrap
95% CI, Permutation Test,Wilcoxon Signed-Rank& Tách biệt Ý nghĩa Hai phía vs. Chiều Cải thiện: Thực hiện tái mẫu có hoàn lại \(R \ge 5{,}000\) lần trên các cặp \((x_i, y_i)\) để lấy phân vị[0.025, 0.975]của hiệu sốIQM. Song song, kiểm định hoán vị ghép cặp (Paired Sign-Flip Permutation Test) đảo dấu ngẫu nhiên \(s_i \in \{-1, +1\}\) qua \(R \ge 5{,}000\) lượt và tính trị số \(p\) chuẩn hữu hạn (Phipson & Smyth, 2010):\[p = \frac{1 + \sum_{r=1}^R \mathbf{1}\!\big(|\bar{d}^{(r)}| \ge |\bar{d}_{\text{obs}}|\big)}{R + 1}.\]Khi phân phối sai phân lệch hoặc phi chuẩn nặng, bổ sung kiểm định phi tham số thứ hạng có dấuWilcoxon Signed-Rank Test(wilcoxon_signed_rank_test, liệt kê chính xác \(2^{n_{\text{nz}}}\) tổ hợp dấu khi \(n_{\text{nz}} \le 14\) hoặc xấp xỉ chuẩn hiệu chỉnh tie \(\sum t(t^2-1)/48\) và liên tục0.5khi \(n_{\text{nz}} > 14\)): trênn = 10,Wilcoxonchop = 0.0039(W = 1.0), còn ở1-Crash, dùWilcoxonkhông bị kéo méo theo độ lớn-42pp, mất một hạng dấu đẩyp = 0.0840— khẳng định giá trị bổ sung củaIQM. Đặc biệt, trong code kiểm định hai phía bắt buộc tách rời cờ ý nghĩa hai phía (is_significant_two_sided = p < alpha) khỏi cờ vượt ngưỡng cải thiện dương (improved_lower_bound = ci_low > 0.0) để một mô hình tệ hơn có ý nghĩa thống kê (ci_high < 0) vẫn được gắn cờ khác biệt thực sự thay vì bị nuốt thành không có ý nghĩa! Cảnh báo Toán học Vền = 3Seed & Dữ liệu Phân cụm (Clustered Prompts): Vớin = 3, toàn bộ không gian đổi dấu chỉ có \(2^3 = 8\) tổ hợp, khiến trị số \(p\) nhỏ nhất có thể của kiểm định hai phía đạt \(2/8 = 0.25 > 0.05\) (p = 0.4953trongExp 1A), cònn = 10seeds khẳng địnhp = 0.0040,95% CI = [+1.66, +3.18],d_z = 1.91,P(X > Y) = 0.860. Đồng thời, khi đánh giá LLM trên hàng nghìn prompt benchmark không độc lập hoàn toàn (non-i.i.d. clustered prompts: nhiều câu hỏi cùng một bài đọc, mã nguồn, hoặc mẫu prompt), tuyệt đối không dùng công thức SE / Student-\(t\) giả định độc lập i.i.d. — nó đánh giá thấp phương sai thực gấp nhiều lần; bắt buộc thay bằng Cluster-Robust Standard Errors (sai số chuẩn vững theo cụm) hoặc Two-Stage Paired Cluster Bootstrap (lấy mẫu lại cấp cụm trước rồi mới lấy mẫu trong cụm)!
1.3 Bùng nổ Dương tính Giả Đa Kiểm định (p-Hacking) & Hiệu chỉnh Holm–Bonferroni / BH-FDR#
Khi nhà nghiên cứu kiểm định đồng thời \(m\) biến thể (tốc độ học, bộ dữ liệu con, trọng số hàm mất mát) dưới \(H_0\) đúng với ngưỡng \(\alpha = 0.05\), Tỷ lệ Sai lầm Toàn họ (Family-Wise Error Rate — FWER) tăng theo hàm mũ:
Ở \(m = 20\) và \(\alpha = 0.05\), \(\operatorname{FWER}(20) = 1 - 0.95^{20} = \mathbf{64.15\%}\) — gần hai phần ba số nghiên cứu hoàn toàn ngẫu nhiên vẫn thu được ít nhất một kết quả p < 0.05! Trong WB-Ch30 (Exp 1B, 2,000 nghiên cứu mô phỏng), FWER thực nghiệm đo được là 64.0%. Hai thuật toán chuẩn quốc tế xử lý triệt để vấn đề này:
- Hiệu chỉnh Bước xuống
Holm–Bonferroni(Khống chế ChặtFWER\(\le \alpha\)): Sắp xếp các trị số \(p\) tăng dần \(p_{(1)} \le p_{(2)} \le \dots \le p_{(m)}\), tính trị số hiệu chỉnh bảo toàn đơn điệu:\[\tilde{p}_{(i)}^{\text{Holm}} = \max_{j \le i} \min\!\big(1,\; (m - j + 1)\, p_{(j)}\big).\]Mạnh hơn hẳn Bonferroni cổ điển (\(m \cdot p_i\)) mà vẫn khóa chặtFWERdưới mọi cấu trúc tương quan (4.95%trên2,000gia đình \(H_0\),0/17dương tính giả trong bảng minh họa20phép thử). Khuyến nghị bắt buộc cho các khẳng định chính (Primary Claims) trong Bảng 1 của bài báo. - Hiệu chỉnh Bước lên
Benjamini–Hochberg(BH, Khống chếFDR\(\le q\)): Tính từ lớn về nhỏ:\[\tilde{q}_{(i)}^{\text{BH}} = \min_{j \ge i} \min\!\big(1,\; \frac{m}{j}\, p_{(j)}\big),\]khống chế Tỷ lệ Phát hiện Sai Kỳ vọng (False Discovery Rate) \(\mathbb{E}[V / \max(R, 1)] \le q\) (5.0%dưới \(H_0\) qua2,000gia đình mô phỏng) đồng thời giữ công suất cao hơnHolmđể tìm trọn3/3hiệu ứng thật trong bước sàng lọc nhiều biến thể (m >= 15).
Trụ cột 2 — Thiết kế Thực nghiệm Sạch, Kiểm toán Rò rỉ, Ngân sách Compute & Nghệ thuật Viết bài A*/Q1#
2.1 Thực nghiệm Loại trừ Trực giao (AOI/LOO) vs Bẫy Biến nhiễu Trộn (Confounders)#
Một bảng ablation chuẩn mực phải cho phép quy kết chính xác một yếu tố cho mỗi bước chuyển đổi trạng thái:
- Thiết kế Cộng thêm Từng phần (
Add-One-In) & Bỏ bớt Từng phần (Leave-One-Out): Mỗi hàng ứng viên trong bảng phải có khoảng cách Hamming bằng đúng1so với baseline hoặc một hàng đã được kiểm chứng gần baseline hơn. Khi bật đồng thời ba công tắc \((0,0,0) \to (1,1,1)\) mà thiếu các hàng trung gian \((1,0,0), (0,1,0), (0,0,1)\), nguyên nhân tăng điểm hoàn toàn bị trộn lẫn (confounded). - Phân rã Tác động Chính & Tương tác Bậc Hai (\(2 \times 2\)): Với hai yếu tố \((F_a, F_b)\) đạt kết quả \(y_{ab}\):
\[\Delta_{\text{main}}(F_a) = \frac{1}{2}\big[(y_{10} - y_{00}) + (y_{11} - y_{01})\big], \qquad \Delta_{\text{int}}(F_a, F_b) = y_{11} - y_{10} - y_{01} + y_{00}.\]Trong
WB-Ch30(Exp 2), tách bảng trực giao đối xứng (8lượt tìm HP đều nhau trên mô phỏng 10 seeds) chứng minharch_gateđóng góp+2.28pp,mixup_augđóng góp+1.40pp, tương tác cộng hưởngarch_gate x mixup_augthêm+0.39pp, trong khicosine_lrgần như vô nghĩa (+0.31pp— nằm trong biên nhiễu95% CI).
2.2 Kiểm toán Bốn Kênh Rò rỉ Chia Tập, Tiền xử lý & Ô nhiễm LLM Benchmark (Contamination Audit)#
Ngay cả khi thống kê rliable hoàn hảo, chỉ một lỗ hổng chia tập dữ liệu hoặc ô nhiễm corpus tiền huấn luyện cũng khiến mô hình học thuộc chữ ký thực thể hoặc đáp án:
Kênh Rò rỉ (Leakage Vector) |
Dấu hiệu Bất biến Kiểm toán (WB-Ch30) |
Hậu quả Trong Exp 3 (960 mẫu / 120 bệnh nhân) |
Biện pháp Khóa Cứng Trong Pipeline |
|---|---|---|---|
1. Trùng ID / Bản sao (ID Overlap) |
train_ids ∩ val_ids ∩ test_ids == ∅ |
Phát hiện 24 mẫu trùng từ train lọt thẳng vào test |
Khử trùng lặp theo hash nội dung trước khi chia tập |
2. Rò rỉ Nhóm (Group Leakage) |
train_groups ∩ val_groups ∩ test_groups == ∅ |
260 nhóm bệnh nhân xuất hiện chéo giữa train và test |
Dùng GroupSplit / băm tất định theo entity_id |
3. Nhìn trộm Tương lai (Temporal Leakage) |
\(\max(t_{\text{train}}) < \min(t_{\text{val}}) \le \max(t_{\text{val}}) < \min(t_{\text{test}})\) | 766 dòng sai thứ tự thời gian (max_train=71.2 vs min_test=0.0) |
Chia tịnh tiến theo cửa sổ thời gian (chronological forward split) |
4. Tiền xử lý Toàn cục (Global Scaler) |
Mọi Scaler / Tokenizer / Imputer chỉ .fit() trên train |
Toàn bộ 216 mẫu test rò rỉ trung bình, phương sai và đích nhóm |
Đóng gói fit_transform(X_train) rồi mới .transform(X_test) |
5. Ô nhiễm Benchmark LLM (SOTA 2025–2026) |
Kiểm tra Min-K% Prob (Shi et al., ICLR 2024) & nhúng Canary GUID Strings |
Đề thi công khai lọt vào pretraining nâng điểm ảo dù không suy luận | Khóa Canary GUID chặn web-crawl + kiểm toán Min-K% Prob trên tập đánh giá mới |
Hệ quả định lượng trong Exp 3: mô hình Ridge tuyến tính trên tập rò rỉ đạt điểm ảo 88.4% accuracy (ROC-AUC 0.968), nhưng khi đưa qua tập chia rời nhóm theo thời gian và fit bộ chuẩn hóa riêng trên tập huấn luyện (360/18/60), độ chính xác thật rơi xuống 68.3% (ROC-AUC 0.868) — lộ rõ +20.09pp ảo ảnh hiệu năng!
2.3 Hoạch định Công suất Student-t (MDE \(\leftrightarrow\) n*) & Ngân sách GPU (Colab vs vast.ai)#
Trước khi thuê GPU, nhà nghiên cứu phải tính ngược số hạt giống tối thiểu \(n^*\) để đạt công suất thống kê \(1 - \beta = 0.80\) tại ngưỡng hiệu ứng kỳ vọng \(\delta\) và độ lệch chuẩn liên-seed \(\sigma_{\text{seed}}\) qua phân phối Student-t phi trung tâm (\(\nu = n - 1\), \(\lambda = \frac{|\delta|\sqrt{n}}{\sigma_{\text{seed}}}\)):
Sau đó, tổng chi phí thực nghiệm được dự toán theo số biến thể \(M\) (baseline + ablations), số lượt chỉnh siêu tham số \(B_{\text{hp}}\), thời lượng mỗi lượt chạy \(h_{\text{run}}\), và hệ số dự phòng ngắt phiên/lưu checkpoint (\(\kappa_{\text{preempt}} \cdot \kappa_{\text{ckpt}}\)):
Với thiết lập chuẩn trong WB-Ch30 (Exp 4: \(\delta = 2.45\text{pp}\), \(\sigma_{\text{seed}} = 1.80\text{pp}\), \(M = 6\), \(B_{\text{hp}} = 4\), \(h_{\text{run}} = 1.5\text{h}\), trần ngân sách $150):
- Đường cong Công suất vs
MDE: Tạin=3, công suất chỉ đạt27.5%(chỉ phát hiện được hiệu ứng khổng lồMDE >= 5.88pp); tạin* = 7seeds, công suất vọt lên84.9%(MDE = 2.29pp); và ởn=10, công suất đạt96.8%(MDE = 1.79pp). -
So sánh Chi phí Đám mây (
66lượt =99.0hGPU thô):vast.ai RTX 4090 Spot($0.34/hr, hệ số1.23x):121.5hhiệu dụng \(\to\) chỉ$41.31(đạt trần$150, rẻ hơn5.4xso vớiOn-Demand A100!).Colab Pro L4($0.55/hr,12hcap):114.4h\(\to\)$62.89(đạt trần$150).vast.ai A100 80GB($1.15/hr):109.1h\(\to\)$125.47(đạt sát trần$150, hợp khi mô hình vượt24GB VRAM).On-Demand A100 80GB($2.20/hr):102.0h\(\to\)$224.38(vượt trần$150!).
2.4 Kỹ nghệ Viết Bài LaTeX booktabs, Cổng Tái lập 8/8 & Chiến lược Phản biện (Rebuttal)#
Một bản thảo đạt chuẩn công bố tại các hội nghị A*/Q1 hay hội nghị quốc tế RIVF (như hai bài báo tham chiếu đã được chấp nhận của FSDS Research Lab tại RIVF 2026: arXiv:2607.24332 và arXiv:2607.24331) tuân thủ nghiêm bốn quy tắc trình bày và phản biện:
- Cấu trúc
IMRaDGắn Ma trận Claim–Evidence: Mở đầu bằng Phễu4đoạn (Bối cảnh \(\to\) Khoảng trống thực chứng \(\to\) Giả thuyết cốt lõi \(\to\)3đóng góp có mã kiểm chứngRQ1..RQ3), kết thúc bằng phần Limitations & Negative Results trung thực — điểm cộng lớn trong phiếu chấmNeurIPS/ICML/RIVF. Đối với đánh giá xếp hạng cặp mô hình sinh hoặcLLM-as-a-Judge, dùng mô hìnhBradley–Terry Maximum Likelihood Estimation (MLE)+Efron / Paired Bootstrap CIsthay cho tỷ lệ thắng thô (raw win-rate) để khử thiên lệch mất cân bằng số trận ghép cặp (LMSYS / Chatbot Arena). - Bảng
LaTeXbooktabsKhông Lừa dối Thị giác: Cấm đường kẻ dọc (|), dùng\toprule,\midrule,\bottomrule, hiển thị đầy đủIQM \pm 95% CI, ghi rõ quy mô seed và ngân sách tinh chỉnh ngay trong\caption{...}, và in đậm đồng hạng (\textbf{...}) mọi mô hình không khác biệt thống kê với hạng nhất. Đoạn mãLaTeXdoWB-Ch30sinh trực tiếp (Exp 2):
\begin{table}[t]
\centering
\caption{Controlled orthogonal ablation under equal 8-trial tuning budget (n=10 seeds, R=5000 bootstrap 95\% CI). Statistically tied winners are bolded.}
\label{tab:controlled_ablation}
\begin{tabular}{lcc}
\toprule
Method & IQM\_Acc (%) & Optimality\_Gap \\
\midrule
Baseline (Untuned Default, 1 trial) & $79.82 \pm 0.90$ & $20.24 \pm 0.90$ \\
Fair-Tuned Baseline (8 trials) & $80.50 \pm 0.93$ & $19.65 \pm 0.93$ \\
+ Arch Gate Only (8 trials) & $82.78 \pm 0.77$ & $17.41 \pm 0.77$ \\
+ Arch Gate + MixUp (8 trials) & \textbf{$84.57 \pm 0.96$} & \textbf{$15.54 \pm 0.96$} \\
Full System (+ CosineLR, 8 trials) & \textbf{$84.67 \pm 0.85$} & \textbf{$15.55 \pm 0.85$} \\
\bottomrule
\end{tabular}
\end{table}
- Cổng Kiểm định Tái lập
8/8Trước Khi Nộp Bài (evaluate_reproducibility_gate): Kiểm tra tự động 8 hạng mục (seeds cố định, khoảng tin cậy CI, hiệu chỉnh đa kiểm định, tinh chỉnh baseline đối xứng, ablation đơn yếu tố, kiểm toán leakage, công bố GPU-hours, mục Limitations). Bản nháp sơ khai ởWB-Ch30chỉ đạt2/8(REJECT_RISK), còn bản hoàn thiện đạt8/8(ACCEPT_READY). -
Chiến lược Phản biện 3 Nhóm (
Rebuttal Triage):- Loại A (Thiếu đối chứng / Thiếu seed / Nghi ngờ biến nhiễu): Chạy thực nghiệm bổ sung ngay trong cửa sổ
rebuttalvà đưa bảng số liệu +95% CIvào phầnTL;DRđầu thư trả lời — không tranh luận suông. - Loại B (Hiểu nhầm ký hiệu hoặc chi tiết thuật toán): Cảm ơn phản biện đã chỉ ra điểm chưa rõ, trích dẫn đúng phương trình và đính kèm đoạn văn bản viết lại cho bản camera-ready.
- Loại C (Yêu cầu vượt quá phạm vi/ngân sách bài báo): Công nhận giá trị của hướng mở rộng, dẫn chứng giới hạn phần cứng đã công bố và bổ sung thảo luận minh bạch vào Limitations / Future Work.
- Loại A (Thiếu đối chứng / Thiếu seed / Nghi ngờ biến nhiễu): Chạy thực nghiệm bổ sung ngay trong cửa sổ
Trụ cột 3 — Mã nguồn Thực thi Độc lập (Standalone NumPy Specimen)#
Đoạn mã dưới đây chạy hoàn toàn độc lập trong .venv (Python 3.12 + NumPy), kiểm chứng trực tiếp ba trụ cột định lượng của Chương 30: (1) sức bền của IQM so với trung bình cộng khi có 1 seed sụp đổ, (2) bùng nổ FWER dưới \(H_0\) ở m=20 so với hiệu chỉnh Holm–Bonferroni, và (3) tính số seed tối thiểu \(n^*\) cùng chi phí vast.ai RTX 4090 Spot:
"""Pillar 3 Executable Specimen: Ch 30 Research Methodology (IQM, FWER vs Holm, Budget)."""
from __future__ import annotations
import json
import math
import numpy as np
def compute_iqm(values: np.ndarray) -> float:
"""25%-75% trimmed Interquartile Mean matching rliable."""
arr = np.sort(np.asarray(values, dtype=np.float64))
n = int(arr.size)
low, high = 0.25 * n, 0.75 * n
w = np.array([max(0.0, min(i + 1, high) - max(i, low)) for i in range(n)])
return float(np.dot(arr, w) / np.sum(w))
def holm_bonferroni(p_vals: np.ndarray) -> np.ndarray:
"""Step-down Holm-Bonferroni FWER adjustment."""
m = p_vals.size
order = np.argsort(p_vals, kind="mergesort")
adj_sorted = np.empty(m, dtype=np.float64)
running_max = 0.0
for rank, orig in enumerate(order):
running_max = max(running_max, min(1.0, float(m - rank) * float(p_vals[orig])))
adj_sorted[rank] = running_max
adj = np.empty(m, dtype=np.float64)
adj[order] = adj_sorted
return adj
def run_ch30_specimen() -> dict[str, float | int | bool]:
"""Verify IQM outlier resistance, m=20 FWER vs Holm containment & RTX 4090 Spot budget."""
rng = np.random.default_rng(42)
# 1. rliable IQM vs Arithmetic Mean under 1 collapsed seed (-42pp outlier)
base = np.array([80.43, 78.54, 81.05, 81.32, 77.27, 78.18, 80.18, 79.56, 79.98, 78.81])
clean_gains = np.array([1.10, -0.45, 2.35, 3.80, 2.95, 2.65, 3.20, 2.15, 3.55, 3.10])
meth = base + clean_gains
meth_crash = meth.copy()
meth_crash[1] = 39.50
clean_diff_iqm = compute_iqm(meth) - compute_iqm(base)
crash_diff_mean = float(np.mean(meth_crash) - np.mean(base))
crash_diff_iqm = compute_iqm(meth_crash) - compute_iqm(base)
# 2. m=20 multiple-testing FWER under global null (1,000 simulated studies, normal approx)
m, n_studies, alpha = 20, 1000, 0.05
z_mat = np.abs(rng.normal(0.0, 1.0, size=(n_studies, m)))
p_mat = np.array([[math.erfc(float(z) / math.sqrt(2.0)) for z in row] for row in z_mat])
raw_fwer = float(np.mean(np.any(p_mat < alpha, axis=1)))
holm_fwer = float(np.mean([np.any(holm_bonferroni(row) < alpha) for row in p_mat]))
# 3. Quick z-approx seed sizing + vast.ai RTX 4090 Spot cost ($0.34/hr, 1.2272x overhead)
delta, sigma = 2.45, 1.80
n_approx = math.ceil(((1.96 + 0.8416) * sigma / delta) ** 2) + 2 # +2 df buffer for small-sample t
total_runs = 6 * (n_approx + 4)
eff_hours = total_runs * 1.5 * 1.18 * 1.04
spot_cost_usd = round(eff_hours * 0.34, 2)
return {
"clean_diff_iqm_pp": round(clean_diff_iqm, 3),
"crash_diff_mean_pp": round(crash_diff_mean, 3),
"crash_diff_iqm_pp": round(crash_diff_iqm, 3),
"theoretical_m20_fwer": round(1.0 - (1.0 - alpha) ** m, 4),
"simulated_raw_fwer": round(raw_fwer, 4),
"simulated_holm_fwer": round(holm_fwer, 4),
"planned_seeds_n": n_approx,
"vast_4090_spot_cost_usd": spot_cost_usd,
"fits_150_usd_cap": spot_cost_usd <= 150.0,
}
if __name__ == "__main__":
print(json.dumps(run_ch30_specimen(), indent=2))
Trụ cột 4 — Phòng thí nghiệm Thực chiến (WB-Ch30: research_methodology_lab) & Rubric Kiểm thử#
4.1 Kiến trúc Mô-đun của WB-Ch30#
Toàn bộ phòng thí nghiệm được đóng gói chuẩn hóa tại labs/ch30-research-methodology-workbench/README.md (100% ngoại tuyến trên Python 3.12 + NumPy + Pydantic v2 + OpenTelemetry, khóa 24 gói bằng uv.lock, 0 # type: ignore, cấm tuyệt đối pickle/joblib):
src/research_methodology_lab/__init__.py: Xuất khẩu toàn bộ API chuẩn của gói thí nghiệm (bao gồmwilcoxon_signed_rank_test,WilcoxonTestResult).src/research_methodology_lab/ablation_and_stats.py: Cài đặtBoundedInMemorySpanExporter, các hàmrliable(interquartile_mean,optimality_gap,probability_of_improvement,cohens_d_paired),stratified_bootstrap_ci,paired_permutation_test(\(R \ge 5{,}000\)),wilcoxon_signed_rank_test(exact\(n_{\text{nz}} \le 14\) &asymptotichiệu chỉnh tie/continuity), tách biệtis_significant_two_sidedkhỏiimproved_lower_bound,holm_bonferroni_adjust,benjamini_hochberg_adjust, mô phỏng bùng nổFWERở \(m = 20\), mô phỏng đa seed kèm tìm HP (run_exp2_ablation_confounder_audit), bộ phát hiện biến nhiễu bảng loại trừanalyze_ablation_tablevà bộ xuấtexport_booktabs_latex_table.src/research_methodology_lab/reproducibility_and_budget.py: Cài đặt kiểm toán bốn kênh rò rỉaudit_split_and_preprocessing_leakage, đối chứng mô hìnhRidgetrên dữ liệu dọc960mẫu (run_exp3_leakage_split_audit), bộ giải công suất phi trung tâmStudent-t(compute_paired_t_power,estimate_required_seeds,solve_minimum_detectable_effect), mô hình chi phíGPU_COMPUTE_CATALOG, bộ chấm cổng tái lập8/8(evaluate_reproducibility_gate), và hàm điều phốirun_full_research_methodology_benchmarkghi nhận5spansOpenTelemetry.scripts/run_lab_demo.py: Bộ chạy dòng lệnh xuất báo cáoartifacts/ch30_wb30_results.jsonkèmworkbench_panels(6KPI,4biểu đồ cột và4bảng chuẩn hóa).tests/test_research_methodology_lab.py: Bộ20bài kiểm thửpytest+ kiểm toán AST + kiểm thử thuộc tínhHypothesis.
4.2 Bảng Kết quả Thực nghiệm Chuẩn hóa (seed=42, artifacts/ch30_wb30_results.json)#
| Thí nghiệm & Hạng mục | Thiết lập Lỗi / Thiếu chuẩn | Thiết lập Chuẩn Nghiên cứu | Chỉ số Đo Thực tế (seed=42) |
|---|---|---|---|
| Exp 1A: Đa Seed & Outlier | n=3 seeds (p=0.4953, Wilcoxon p=0.50, CI [-0.45, +2.35]); 1-Crash Mean (-1.42pp) |
n=10 seeds + rliable IQM + Wilcoxon |
+2.53pp IQM (CI [+1.66, +3.18], perm p=0.0040, Wilcoxon p=0.0039, d=1.91), IQM bất biến khi 1 seed sập |
Exp 1B: Đa Kiểm định (m=20) |
So sánh thô \(\alpha = 0.05\): 64.0% null FWER (3/17 FP) |
Holm–Bonferroni & BH-FDR |
Holm FWER = 4.95% (0/17 FP); BH Null FDR = 5.0% (3/3 tín hiệu thật) |
| Exp 2: Kiểm toán Ablation | Nhảy 3 yếu tố + 1 vs 15 HP (2 lỗi CRITICAL, +4.89pp) |
Mô phỏng 10 seeds trực giao + 8 vs 8 HP |
0 lỗi, hiệu ứng thật +4.17pp (+0.72pp ảo); Arch +2.28pp, MixUp +1.40pp, Int +0.39pp |
Exp 3: Kiểm toán Rò rỉ (Leakage) |
Random + Global Scaler (24 ID, 260 Group, 766 Time): 88.4% (0.968) |
Rời nhóm + Trình tự thời gian + train_only |
Độ chính xác thật 68.3% (AUC 0.868) — bóc trần +20.09pp ảo ảnh |
| Exp 4: Power, GPU & Repro Gate | On-Demand A100 ($224.38, vượt trần); Draft 2/8 (REJECT_RISK) |
n*=7 (84.9% power) trên vast.ai 4090 Spot |
$41.31 (121.5h, rẻ 5.4x); Cổng 8/8 (ACCEPT_READY); 5 spans OTel; 20/20 pytest |
4.3 Hợp đồng 20 Bài kiểm thử Tự động (tests/test_research_methodology_lab.py)#
| STT | Tên Hàm Kiểm thử Pytest |
Bất biến & Ngưỡng Nghiệm thu Bắt buộc |
|---|---|---|
1 |
test_01_ast_no_unsafe_deserializers_and_zero_type_ignore |
Quét AST cấm pickle, joblib, cloudpickle, dill, shelve, marshal, eval/exec và cấm # type: ignore |
2 |
test_02_pydantic_v2_strict_schemas_extra_forbid |
Khóa extra="forbid" trên các schema Pydantic v2 của WB-Ch30 |
3 |
test_03_iqm_outlier_resistance_and_rliable_metrics |
Xác nhận IQM bất biến trước giá trị ngoại lai đầu/cuối và tính đúng Optimality Gap, P(X>Y) |
4 |
test_04_paired_permutation_symmetry_and_resamples_guard |
Kiểm tra đối xứng hai phía \(p(A,B) == p(B,A)\), \(p > 0\) và chặn n_resamples < 5000 |
5 |
test_05_paired_permutation_monotonicity_with_sample_size |
Trị số \(p\) giảm đơn điệu khi tăng cỡ mẫu \(n\) từ 4 -> 12 -> 30 ở hiệu ứng cố định |
6 |
test_06_exp1a_n3_underpowered_vs_n10_and_outlier_resilience |
Chứng minh n=3 thiếu lực (p > 0.20), n=10 đạt (perm/Wilcoxon p < 0.01), tách biệt mô hình suy giảm hai phía & Wilcoxon tiệm cận |
7 |
test_07_multiple_testing_fwer_inflation_and_holm_bh_containment |
Chứng minh m=20 đẩy FWER lên ~64%, còn Holm/BH kéo về <= 6.5% và 0 FP dưới Holm |
8 |
test_08_holm_and_bh_exact_step_adjustments |
Đối chiếu từng bước giải tích của Holm–Bonferroni và Benjamini–Hochberg (p_raw <= q_BH <= p_Holm) |
9 |
test_09_exp2_ablation_confounder_and_tuning_asymmetry_detector |
Bắt confounded_multi_factor + unfair_tuning_asymmetry và tính động main/interaction từ 10 seed mô phỏng |
10 |
test_10_latex_booktabs_table_exporter_and_tied_bolding |
Xác minh bảng LaTeX dùng \toprule/\midrule/\bottomrule, không dùng |, và tự động in đậm đồng hạng thắng từ dữ liệu mô phỏng |
11 |
test_11_exp3_leakage_detection_and_score_inflation |
Phát hiện đủ 4/4 kênh rò rỉ và mức thổi phồng >= +12pp accuracy (+20.09pp) |
12 |
test_12_unit_leakage_auditor_individual_vectors |
Kiểm chứng cô lập từng kênh rò rỉ riêng lẻ (group_leakage = 1) |
13 |
test_13_student_t_power_and_cloud_gpu_budget_matrix |
Kiểm tra đường cong công suất Student-t, n*=7, vast.ai 4090 Spot đạt trần $150 vs On-Demand vượt trần |
14 |
test_14_reproducibility_and_rebuttal_gate_scoring |
Phân biệt REJECT_RISK (2/8), MINOR_REVISION (6/8) và ACCEPT_READY (8/8) |
15 |
test_15_bounded_otel_span_exporter_and_telemetry |
Kiểm tra BoundedInMemorySpanExporter giữ đúng trần maxlen và thu đủ 5 spans thực nghiệm |
16 |
test_16_determinism_seed_42_and_workbench_panels_contract |
Xác minh tất định seed=42 và schema 6 KPI, 4 biểu đồ cột, 4 bảng workbench_panels |
17 |
test_17_cli_subprocess_generates_valid_artifact |
Chạy tiến trình con scripts/run_lab_demo.py --quick, xác minh JSON và telemetry |
18 |
test_18_hypothesis_student_t_power_monotonicity |
Kiểm thử Hypothesis xác minh công suất Student-t tăng theo n, delta và giảm theo std |
19 |
test_19_hypothesis_mde_and_required_seeds_roundtrip |
Kiểm thử Hypothesis xác minh phép giải khép kín solve_minimum_detectable_effect \(\leftrightarrow\) estimate_required_seeds |
20 |
test_20_hypothesis_iqm_and_holm_bh_bounds |
Kiểm thử Hypothesis xác minh tính bất biến dịch chuyển tuyến tính của IQM và tính toán ngân sách |
Trụ cột 5 — Văn liệu Nền tảng, Ôn tập Nhanh & Hệ thống 6 Bài tập Capstone#
5.1 Bảy Văn liệu & Chuẩn mực Nền tảng Về Phương pháp luận Nghiên cứu (1979–2026)#
- Popper, K. (1959/2002). The Logic of Scientific Discovery — tiêu chuẩn khả bác bỏ (falsifiability) làm ranh giới giữa lý thuyết khoa học và kể chuyện hậu nghiệm (
HARKing). - Holm, S. (1979) & Benjamini, Y. & Hochberg, Y. (1995). A Simple Sequentially Rejective Multiple Test Procedure & Controlling the False Discovery Rate — hai thuật toán nền tảng khống chế
FWERvàFDRkhi thử nghiệm nhiều giả thuyết đồng thời. - Kaufman, S., Rosset, S. & Perlich, C. (ACM TKDD, 2012). Leakage in Data Mining: Formulation, Detection, and Avoidance — hệ thống hóa rò rỉ dữ liệu theo thực thể, thời gian và tiền xử lý.
- Sculley, D. et al. (NeurIPS, 2018) & Dodge, J. et al. (EMNLP, 2019). Winner's Curse? On Pace, Progress, and Empirical Rigor & Show Your Work: Improved Reporting of Experimental Results — chứng minh thiên lệch do tinh chỉnh bất đối xứng (tune-the-baseline) và đề xuất báo cáo hiệu năng kỳ vọng theo ngân sách tính toán.
- Agarwal, R. et al. (NeurIPS, 2021). Deep Reinforcement Learning at the Edge of the Statistical Precipice (
rliable) — chuẩn hóaIQM,Optimality Gap,P(X > Y)vàStratified Bootstrap CIthay cho Mean \(\pm\) Std trên số seed ít. - Phipson, B. & Smyth, G. K. (Statistical Applications in Genetics and Molecular Biology, 2010). Permutation P-values Should Never Be Zero — chuẩn công thức \((c + 1)/(R + 1)\) cho kiểm định hoán vị ghép cặp.
NeurIPS/ICML/ICLRReproducibility Checklists (2024–2026) &FSDS Research Lab(RIVF 2026). Bộ tiêu chí chuẩn quốc tế về chia sẻ mã, công bố compute, Limitations và hai công trình đã được chấp nhận công bố tạiRIVF 2026:arXiv:2607.24332vàarXiv:2607.24331.
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(Vì saon=3Seed Thường Bỏ sót Hiệu ứng Thật): Vớin=3cặp, không gian đổi dấu chỉ có \(2^3 = 8\) hoán vị, nênptối thiểu bị kẹp ở0.25 > 0.05(WB-Ch30:n=3chop=0.4953dù hiệu ứng thật+2.44pp), cònn=10đạtp=0.0040(CI [+1.66, +3.18]).Q2(rliable IQMKháng Outlier vs Trung bình Cộng):IQMcắt25%hai đuôi nên vẫn giữ nguyên+2.53ppkhi1seed sụp xuống39.5%, trong khi trung bình cộng bị kéo lật âm xuống-1.42pp.Q3(Bùng nổFWERởm=20& ChọnHolmvsBH): Dưới \(H_0\), thử20lần ở \(\alpha = 0.05\) đẩyFWERlên64.15%(64.0%thực nghiệm).Holm–Bonferronikhóa chặtFWER(4.95%,0FP) cho khẳng định chính;BHkhống chếFDR(5.0%) cho sàng lọc diện rộng.Q4(Nhiễu Trộn Nhiều Yếu tố & Thiên lệchTune-the-Baseline): Thay đổi3công tắc cùng lúc + tìm kiếm15vs1lượt tạo ảo giác+4.89pp(2lỗiCRITICAL); tách bảng trực giao8vs8thu về hiệu ứng thật+4.17pp(+0.72ppthiên lệch ảo).Q5(Bốn Kênh Rò rỉ Dữ liệu Trong Chia Tập & Tiền xử lý): TrùngID(24), rò rỉ nhóm (260), nhìn trộm tương lai (766dòng) và fitScalertrên toàn tập (216mẫu) thổi phồng độ chính xác lên88.4%thay vì68.3%(+20.09ppảo ảnh).Q6(Giải Công suấtStudent-t& Tối ưu Ngân sáchvast.ai): Với \(\delta=2.45\text{pp}, \sigma=1.80\text{pp}\), cần tối thiểun* = 7seeds cho công suất84.9%; chạy66lượt trênvast.ai RTX 4090 Spottốn$41.31(rẻ hơn5.4xso với$224.38củaOn-Demand A100).Q7(ChuẩnLaTeX booktabs& Cổng Tái lập8/8): Bảng chuẩn loại bỏ gạch dọc|, báo cáoIQM \pm CI, và in đậm tất cả phương pháp không khác biệt thống kê với hạng nhất (84.57%và84.67%).Q8(Chiến lược Phản biệnRebuttalChuyển Điểm5 -> 7): Khi phản biện nghi ngờ thiếu baseline hoặc phương sai seed (Loại A), chạy bổ sung ngay thí nghiệm đối chứng đa seed và trình bày bảng số liệu kèmCIngay trongTL;DR.
5.3 Sáu Bài tập Capstone Nghiên cứu & Thang chấm Rubric (ex1..ex6)#
- Bài tập 1 (
15%) — Soạn Thảo Giả thuyết Khả bác bỏ & Kế hoạch Tiền đăng ký: Chọn một hướng đề tài (từChương 28hoặcChương 29), viết cặp giả thuyết \(H_0 / H_1\), xác địnhMDE\(\delta_{\min}\), ranh giới bác bỏ tường minh và hợp đồng tinh chỉnh đối xứngB_new == B_base. - Bài tập 2 (
20%) — Kiểm chứng Thống kê Đa Seedrliable& Hiệu chỉnhHolm/BH: Phân tích chuỗi10seed có1outlier trongWB-Ch30(Exp 1A–1B), chứng minh vì saon=3thất bại (perm p=0.4953,Wilcoxon p=0.50), tính tay phép điều chỉnhHolm–Bonferronicho4trị số \(p\), và giải thích sự khác biệt giữaFWERvàFDRở \(m = 20\). - Bài tập 3 (
15%) — Gỡ lỗi Bảng Ablation Trộn Yếu tố & Phân rã Tương tác \(2 \times 2\): Chạyanalyze_ablation_tableđể bắt hai lỗi ở bảng lỗi+4.89pp, tính tay \(\Delta_{\text{main}}\) và \(\Delta_{\text{int}}\) từ bảng sạch6hàng (Exp 2:Arch +2.28pp,MixUp +1.40pp,Int +0.39pp), và quyết định có nên giữcosine_lr(+0.31pp) trong mô hình cuối hay không. - Bài tập 4 (
15%) — Kiểm toán Bốn Kênh Rò rỉ Dữ liệu Trên Bài toán Dọc Thời gian: Dùngaudit_split_and_preprocessing_leakage(Exp 3) giải thích cơ chế từng kênh rò rỉ tạo nên+20.09ppảo ảnh và viết lại đoạn pipeline chia tập theogroup_id+timestamp+train_only. - Bài tập 5 (
15%) — Lập Đề xuất Công suấtStudent-t& Ngân sách Đám mây$150: Cho đề tài cần phát hiện mức cải thiện \(\delta = 2.0\text{pp}\) với \(\sigma_{\text{seed}} = 1.8\text{pp}\), dùngestimate_required_seedsvàplan_compute_budgetđể chọn GPU phù hợp nhất giữaColab Pro L4,vast.ai RTX 4090 SpotvàA100(tính cả hệ số ngắt Spot). - Bài tập 6 (
20%) — Hoàn thiện BảngLaTeX booktabs, Thư Phản biện & Nghiệm thuWB-Ch30: Chạyuv lock --check,ruff check,mypy --strict(0# type: ignore),scripts/run_lab_demo.py, vượt qua20/20 pytest(5spansOpenTelemetry+workbench_panels6/4/4), viết bảngbooktabscho một thực nghiệm của bạn và soạn phản hồiLoại Amẫu theo chuẩn hội nghịRIVF/A*.
| Tiêu chí Rubric | Đạt (Pass, 60–74%) |
Khá (Merit, 75–84%) |
Xuất sắc (Distinction, 85–100%) |
|---|---|---|---|
Giả thuyết & Thống kê (ex1, ex2) |
Viết được giả thuyết \(H_0/H_1\) và tính đúng IQM, FWER |
Giải thích được giới hạn \(2^n\) ở n=3, tính đúng bước Holm/BH |
Chứng minh sâu sắc sự đánh đổi FWER vs FDR, IQM vs trung bình và thiết lập đối chứng Tune-the-Baseline |
Ablation, Rò rỉ & Ngân sách (ex3, ex4, ex5) |
Bắt đúng lỗi trộn yếu tố và 4 kênh rò rỉ |
Tính đúng \(\Delta_{\text{main}}, \Delta_{\text{int}}\), phân tích +20.09pp rò rỉ và tính n* |
Thiết kế hoàn chỉnh pipeline không rò rỉ + ma trận chi phí vast.ai tối ưu theo MDE và dự phòng Spot |
Bài báo LaTeX & WB-Ch30 (ex6) |
Vượt qua 20/20 pytest, xuất đúng JSON và bảng booktabs |
Đạt 0 lỗi ruff/mypy, 0 # type: ignore, khóa uv.lock |
Đạt cổng tái lập 8/8, 5 spans OTel, in đậm đồng hạng chuẩn xác và viết thư Rebuttal thuyết phục theo dữ liệu |
Exp 1A: Mean vs rliable IQM Gain (pp) Across n=3, n=10 & 1-Outlier Crash
Exp 1B: m=20 Simultaneous Null Tests Error Rate (%)
Exp 3: Leaked Random/Global-Scaler vs Clean Group-Chronological Score (%)
Exp 4: Full Study Cloud Cost (USD) at Power >= 80% (n*=7..10 Seeds)
Experiment 1A: Multi-Seed Power (n=3 vs n=10) & rliable Outlier Resilience
| Evaluation Regime | Mean Diff / IQM Diff | 95% Bootstrap CI | Permutation p & Cohen d |
|---|---|---|---|
| ProposedMethod (n=3 seeds) | +1.00pp / +1.05pp | [-0.45, +2.35] | p=0.4953 | d=0.71 | sig=False (imp=False) |
| ProposedMethod (n=10 seeds) | +2.44pp / +2.53pp | [+1.66, +3.18] | p=0.0040 | d=1.91 | sig=True (imp=True) |
| ProposedMethod (1 Outlier Crash) | -1.42pp / +2.53pp | [-2.00, +3.18] | p=1.0000 | d=-0.11 | sig=False (imp=False) |
Experiment 1B: Multiple-Testing Control Over m=20 Simultaneous Comparisons
| Testing Procedure | Null FWER / FDR (1,000 studies) | Single Study Rejections (of 20) | False Positives (of 17 True Nulls) |
|---|---|---|---|
| Uncorrected (alpha = 0.05) | FWER = 64.0% (Theory 64.15%) | 6 / 20 | 3 / 17 |
| Holm-Bonferroni (FWER <= 0.05) | FWER = 5.0% | 2 / 20 | 0 / 17 |
| Benjamini-Hochberg (FDR <= 0.05) | Null FDR = 5.0% | 5 / 20 | 2 / 17 |
Experiments 2 & 3: Controlled Ablation Confounders & Split Leakage Audits
| Audit Subject | Status & Critical Findings | Primary Metric Summary | Engineering / Attribution Takeaway |
|---|---|---|---|
| Flawed Confounded & Asymmetric Table | PASSED=False (2 flaws) | Claimed +4.89pp (1 vs 15 trials) | Multi-factor jump + tuning asymmetry invalidates attribution |
| Clean Orthogonal 1-Factor & Symmetric Table | PASSED=True (0 flaws, 8 vs 8 trials) | Fair +4.17pp (Arch +2.28pp) | MixUp +1.40pp, CosineLR +0.31pp, Int +0.39pp |
| Leaked Naive Random Split + Global Scaler | LEAKAGE_FREE=False (4/4 vectors leaked) | Acc 88.4% | AUC 0.968 | +20.09pp artificial mirage from ID/group/time/scaler leaks |
| Clean Chronological Group-Disjoint Split | LEAKAGE_FREE=True (0 overlaps) | Acc 68.3% | AUC 0.868 | Chronological group-disjoint split + train-only scaler |
Experiment 4: Power-Sized Cloud GPU Budget Matrix (delta=2.45pp, std=1.80pp, Power>=80%)
| Cloud / Notebook Tier | Hourly Rate & Preemption Factor | Required Seeds n* & Runs | Effective GPU-Hrs & Cost ($150 Cap) |
|---|---|---|---|
| Colab Free T4 (16GB, 4h cap) | $0.00/hr (1.46x) | n*=7 (pwr=0.849) | 66 runs | 144.3h | $0.00 (fits=True) |
| Colab Pro L4 (24GB, 12h cap) | $0.55/hr (1.16x) | n*=7 (pwr=0.849) | 66 runs | 114.3h | $62.89 (fits=True) |
| vast.ai RTX 4090 Spot (24GB) | $0.34/hr (1.23x) | n*=7 (pwr=0.849) | 66 runs | 121.5h | $41.31 (fits=True) |
| vast.ai A100-SXM 80GB | $1.15/hr (1.10x) | n*=7 (pwr=0.849) | 66 runs | 109.1h | $125.47 (fits=True) |
| Cloud On-Demand A100 80GB | $2.20/hr (1.03x) | n*=7 (pwr=0.849) | 66 runs | 102.0h | $224.38 (fits=False) |
02-track-1-data-science-and-ai/part-07-frontier-world-models-robotics/labs/ch30-research-methodology-workbench
[build-system]
requires = ["setuptools>=68.0"]
build-backend = "setuptools.build_meta"
[project]
name = "research-methodology-lab"
version = "0.1.0"
description = "WB-Ch30: End-to-End Research Methodology & Paper Capstone — rliable Multi-Seed Stats, Permutation Tests, Holm/BH FWER Control, Controlled Ablation Confounder & Leakage Audits, GPU Compute/Power Budgeting & LaTeX Booktabs Exporter for T1-P7-U03."
readme = "README.md"
requires-python = ">=3.12"
dependencies = [
"numpy>=1.26",
"opentelemetry-sdk>=1.28",
"pydantic>=2.0",
]
[project.optional-dependencies]
dev = [
"hypothesis>=6.100",
"mypy>=1.11",
"pytest>=8.0",
"ruff>=0.6",
]
[project.scripts]
fsds-wb-ch30-research = "research_methodology_lab.reproducibility_and_budget:main"
[tool.setuptools]
package-dir = {"" = "src"}
[tool.setuptools.packages.find]
where = ["src"]
[tool.ruff]
target-version = "py312"
line-length = 105
[tool.ruff.lint]
select = ["E", "F", "I", "UP", "B", "RUF"]
[tool.mypy]
python_version = "3.12"
mypy_path = ["$MYPY_CONFIG_FILE_DIR/src", "$MYPY_CONFIG_FILE_DIR"]
strict = true
warn_return_any = true
warn_unused_configs = true
disallow_untyped_defs = true
warn_unused_ignores = true
[[tool.mypy.overrides]]
module = [
"hypothesis",
"hypothesis.*",
]
ignore_missing_imports = true
[tool.pytest.ini_options]
testpaths = ["tests"]
pythonpath = ["src", "."]
addopts = "-v"
"""WB-Ch30: Research Methodology & A*/Q1 Paper Capstone Workbench (`research_methodology_lab`)."""
from research_methodology_lab.ablation_and_stats import (
AblationAuditReport,
AblationConfounderFinding,
AblationRunRow,
BoundedInMemorySpanExporter,
MultipleTestingSummary,
MultiSeedComparisonResult,
WilcoxonTestResult,
analyze_ablation_table,
benjamini_hochberg_adjust,
cohens_d_paired,
compare_methods_multiseed,
create_in_memory_otel_tracer,
export_booktabs_latex_table,
holm_bonferroni_adjust,
interquartile_mean,
optimality_gap,
paired_permutation_test,
probability_of_improvement,
run_exp1_multiseed_and_fwer,
run_exp2_ablation_confounder_audit,
simulate_multiple_testing_inflation,
stratified_bootstrap_ci,
wilcoxon_signed_rank_test,
)
from research_methodology_lab.reproducibility_and_budget import (
GPU_COMPUTE_CATALOG,
GPUComputeTier,
LeakageAuditFinding,
LeakageAuditReport,
PowerBudgetPlan,
ReproducibilityChecklistInput,
ReproducibilityGateReport,
audit_split_and_preprocessing_leakage,
compute_paired_t_power,
estimate_required_seeds,
evaluate_reproducibility_gate,
plan_compute_budget,
run_exp3_leakage_split_audit,
run_exp4_compute_budget_and_repro_audit,
run_full_research_methodology_benchmark,
solve_minimum_detectable_effect,
)
__all__ = [
"GPU_COMPUTE_CATALOG",
"AblationAuditReport",
"AblationConfounderFinding",
"AblationRunRow",
"BoundedInMemorySpanExporter",
"GPUComputeTier",
"LeakageAuditFinding",
"LeakageAuditReport",
"MultiSeedComparisonResult",
"MultipleTestingSummary",
"PowerBudgetPlan",
"ReproducibilityChecklistInput",
"ReproducibilityGateReport",
"WilcoxonTestResult",
"analyze_ablation_table",
"audit_split_and_preprocessing_leakage",
"benjamini_hochberg_adjust",
"cohens_d_paired",
"compare_methods_multiseed",
"compute_paired_t_power",
"create_in_memory_otel_tracer",
"estimate_required_seeds",
"evaluate_reproducibility_gate",
"export_booktabs_latex_table",
"holm_bonferroni_adjust",
"interquartile_mean",
"optimality_gap",
"paired_permutation_test",
"plan_compute_budget",
"probability_of_improvement",
"run_exp1_multiseed_and_fwer",
"run_exp2_ablation_confounder_audit",
"run_exp3_leakage_split_audit",
"run_exp4_compute_budget_and_repro_audit",
"run_full_research_methodology_benchmark",
"simulate_multiple_testing_inflation",
"solve_minimum_detectable_effect",
"stratified_bootstrap_ci",
"wilcoxon_signed_rank_test",
]
"""Multi-seed rliable statistics, permutation tests, FWER/FDR control, ablation & LaTeX."""
from __future__ import annotations
import math
import threading
from collections import deque
from collections.abc import Sequence
from typing import Any, Literal
import numpy as np
from numpy.typing import NDArray
from opentelemetry.sdk.trace import ReadableSpan, TracerProvider
from opentelemetry.sdk.trace.export import SimpleSpanProcessor, SpanExporter, SpanExportResult
from opentelemetry.trace import Tracer
from pydantic import BaseModel, ConfigDict, Field
# ---------------------------------------------------------------------------
# Thread-Safe Bounded OpenTelemetry Exporter (Zero Global State Leaks)
# ---------------------------------------------------------------------------
class BoundedInMemorySpanExporter(SpanExporter):
"""Thread-safe bounded in-memory OpenTelemetry span exporter using a fixed-capacity deque."""
def __init__(self, max_spans: int = 512) -> None:
if max_spans < 1:
raise ValueError("max_spans must be >= 1")
self._max_spans = max_spans
self._spans: deque[ReadableSpan] = deque(maxlen=max_spans)
self._lock = threading.Lock()
self._stopped = False
def export(self, spans: Sequence[ReadableSpan]) -> SpanExportResult:
if self._stopped:
return SpanExportResult.FAILURE
with self._lock:
self._spans.extend(spans)
return SpanExportResult.SUCCESS
def get_finished_spans(self) -> tuple[ReadableSpan, ...]:
with self._lock:
return tuple(self._spans)
def clear(self) -> None:
with self._lock:
self._spans.clear()
def shutdown(self) -> None:
self._stopped = True
def force_flush(self, timeout_millis: int = 30000) -> bool:
_ = timeout_millis
return True
def create_in_memory_otel_tracer(
instrumentation_name: str = "research_methodology_lab",
max_spans: int = 512,
) -> tuple[TracerProvider, BoundedInMemorySpanExporter, Tracer]:
"""Create an isolated TracerProvider + BoundedInMemorySpanExporter for deterministic tests."""
exporter = BoundedInMemorySpanExporter(max_spans=max_spans)
provider = TracerProvider()
provider.add_span_processor(SimpleSpanProcessor(exporter))
tracer = provider.get_tracer(instrumentation_name)
return provider, exporter, tracer
# ---------------------------------------------------------------------------
# Strict Pydantic v2 Schemas
# ---------------------------------------------------------------------------
class MultiSeedComparisonResult(BaseModel):
"""Paired multi-seed rliable and permutation comparison between method and baseline."""
model_config = ConfigDict(extra="forbid")
method_name: str
baseline_name: str
n_seeds: int = Field(ge=2)
method_mean: float
baseline_mean: float
method_iqm: float
baseline_iqm: float
diff_mean: float
diff_iqm: float
ci_low: float
ci_high: float
ci_half_width: float = Field(ge=0.0)
cohens_d: float
prob_improvement: float = Field(ge=0.0, le=1.0)
optimality_gap_method: float = Field(ge=0.0)
optimality_gap_baseline: float = Field(ge=0.0)
permutation_p_value: float = Field(gt=0.0, le=1.0)
is_significant_two_sided: bool
improved_lower_bound: bool
class WilcoxonTestResult(BaseModel):
"""Exact/asymptotic two-sided Wilcoxon signed-rank paired test result."""
model_config = ConfigDict(extra="forbid")
n_pairs: int = Field(ge=1)
n_nonzero: int = Field(ge=0)
w_plus: float = Field(ge=0.0)
w_minus: float = Field(ge=0.0)
w_statistic: float = Field(ge=0.0)
p_value: float = Field(ge=0.0, le=1.0)
method: Literal["exact", "asymptotic"]
class MultipleTestingSummary(BaseModel):
"""FWER inflation under global null and Holm-Bonferroni / BH-FDR control metrics."""
model_config = ConfigDict(extra="forbid")
m_comparisons: int = Field(ge=1)
n_null_families: int = Field(ge=10)
alpha: float = Field(gt=0.0, lt=1.0)
theoretical_null_fwer: float = Field(ge=0.0, le=1.0)
empirical_null_fwer: float = Field(ge=0.0, le=1.0)
holm_empirical_null_fwer: float = Field(ge=0.0, le=1.0)
bh_empirical_null_fdr: float = Field(ge=0.0, le=1.0)
study_true_nulls: int = Field(ge=0)
study_true_alternatives: int = Field(ge=0)
study_raw_rejections: int = Field(ge=0)
study_raw_false_positives: int = Field(ge=0)
study_holm_rejections: int = Field(ge=0)
study_holm_false_positives: int = Field(ge=0)
study_bh_rejections: int = Field(ge=0)
study_bh_false_positives: int = Field(ge=0)
raw_p_values: list[float]
holm_adjusted_p_values: list[float]
bh_adjusted_p_values: list[float]
class AblationRunRow(BaseModel):
"""Single experimental configuration row in an ablation table."""
model_config = ConfigDict(extra="forbid")
run_id: str
factors: dict[str, bool | str]
tuning_trials: int = Field(ge=1)
metric_score: float
ci_half_width: float = Field(default=0.0, ge=0.0)
class AblationConfounderFinding(BaseModel):
"""Detected scientific confounder or baseline tuning asymmetry in an ablation table."""
model_config = ConfigDict(extra="forbid")
issue_type: Literal[
"confounded_multi_factor",
"unfair_tuning_asymmetry",
"missing_baseline_control",
]
severity: Literal["CRITICAL", "WARNING"]
run_ids: list[str]
description: str
class AblationAuditReport(BaseModel):
"""Programmatic audit of controlled single-factor vs confounded ablation designs."""
model_config = ConfigDict(extra="forbid")
table_label: str
total_runs: int = Field(ge=1)
clean_single_factor_transitions: int = Field(ge=0)
confounders: list[AblationConfounderFinding]
tuning_asymmetry_detected: bool
baseline_tuning_trials: int = Field(ge=1)
max_method_tuning_trials: int = Field(ge=1)
main_effects: dict[str, float]
interaction_effects: dict[str, float]
audit_passed: bool
# ---------------------------------------------------------------------------
# rliable Metrics & Hypothesis Testing Primitives
# ---------------------------------------------------------------------------
def _as_float_array(values: Sequence[float] | NDArray[np.float64], name: str) -> NDArray[np.float64]:
arr = np.asarray(values, dtype=np.float64)
if arr.ndim != 1 or arr.size == 0:
raise ValueError(f"{name} must be a non-empty 1D sequence")
if not np.all(np.isfinite(arr)):
raise ValueError(f"{name} contains non-finite values")
return arr
def interquartile_mean(values: Sequence[float] | NDArray[np.float64]) -> float:
"""Compute rliable 25%-75% trimmed Interquartile Mean (IQM) with exact boundary weights."""
arr = np.sort(_as_float_array(values, "values"))
n = int(arr.size)
if n == 1:
return float(arr[0])
if n == 2:
return float(np.mean(arr))
low = 0.25 * n
high = 0.75 * n
total_mass = 0.0
weighted_sum = 0.0
for idx in range(n):
seg_low = max(float(idx), low)
seg_high = min(float(idx + 1), high)
weight = max(0.0, seg_high - seg_low)
if weight > 0.0:
weighted_sum += weight * float(arr[idx])
total_mass += weight
return float(weighted_sum / total_mass)
def optimality_gap(
scores: Sequence[float] | NDArray[np.float64],
threshold: float = 1.0,
) -> float:
"""Compute rliable Optimality Gap: mean shortfall below ideal threshold."""
arr = _as_float_array(scores, "scores")
shortfalls = np.maximum(0.0, float(threshold) - arr)
return float(np.mean(shortfalls))
def cohens_d_paired(
method_scores: Sequence[float] | NDArray[np.float64],
baseline_scores: Sequence[float] | NDArray[np.float64],
) -> float:
"""Compute paired Cohen's d_z = mean(diff) / std(diff, ddof=1)."""
m_arr = _as_float_array(method_scores, "method_scores")
b_arr = _as_float_array(baseline_scores, "baseline_scores")
if m_arr.size != b_arr.size or m_arr.size < 2:
raise ValueError("Paired comparison requires equal-length arrays with n >= 2")
diff = m_arr - b_arr
sd = float(np.std(diff, ddof=1))
mean_diff = float(np.mean(diff))
if sd <= 1e-12:
if abs(mean_diff) <= 1e-12:
return 0.0
return 1e6 if mean_diff > 0.0 else -1e6
return float(mean_diff / sd)
def probability_of_improvement(
method_scores: Sequence[float] | NDArray[np.float64],
baseline_scores: Sequence[float] | NDArray[np.float64],
) -> float:
"""Compute rliable pairwise Mann-Whitney probability of improvement P(X > Y)."""
m_arr = _as_float_array(method_scores, "method_scores")
b_arr = _as_float_array(baseline_scores, "baseline_scores")
diff_matrix = m_arr[:, None] - b_arr[None, :]
wins = float(np.sum(diff_matrix > 0.0))
ties = 0.5 * float(np.sum(diff_matrix == 0.0))
return float((wins + ties) / float(m_arr.size * b_arr.size))
def stratified_bootstrap_ci(
method_scores: Sequence[float] | NDArray[np.float64],
baseline_scores: Sequence[float] | NDArray[np.float64],
n_resamples: int = 5000,
alpha: float = 0.05,
seed: int = 42,
use_iqm: bool = True,
) -> tuple[float, float, float]:
"""Compute paired stratified bootstrap estimate and (1 - alpha) percentile CI."""
if n_resamples < 5000:
raise ValueError("n_resamples must be >= 5000 for publication-grade bootstrap CIs")
if not (0.0 < alpha < 1.0):
raise ValueError("alpha must lie strictly in (0, 1)")
m_arr = _as_float_array(method_scores, "method_scores")
b_arr = _as_float_array(baseline_scores, "baseline_scores")
if m_arr.size != b_arr.size or m_arr.size < 2:
raise ValueError("Paired bootstrap requires equal-length arrays with n >= 2")
n = int(m_arr.size)
rng = np.random.default_rng(seed)
idx = rng.integers(0, n, size=(n_resamples, n))
boot_m = m_arr[idx]
boot_b = b_arr[idx]
if use_iqm:
point_est = interquartile_mean(m_arr) - interquartile_mean(b_arr)
boot_diffs = _vectorized_iqm(boot_m) - _vectorized_iqm(boot_b)
else:
point_est = float(np.mean(m_arr - b_arr))
boot_diffs = np.mean(boot_m - boot_b, axis=1)
low_q = float(np.quantile(boot_diffs, alpha / 2.0))
high_q = float(np.quantile(boot_diffs, 1.0 - alpha / 2.0))
return float(point_est), low_q, high_q
def _vectorized_iqm(matrix: NDArray[np.float64]) -> NDArray[np.float64]:
"""Compute exact weighted IQM across axis=1 for a 2D array of shape (R, n)."""
sorted_m = np.sort(matrix, axis=1)
n = sorted_m.shape[1]
if n == 1:
return sorted_m[:, 0].astype(np.float64)
if n == 2:
return np.mean(sorted_m, axis=1).astype(np.float64)
low = 0.25 * n
high = 0.75 * n
weights = np.array(
[max(0.0, min(float(idx + 1), high) - max(float(idx), low)) for idx in range(n)],
dtype=np.float64,
)
weights /= float(np.sum(weights))
return (sorted_m @ weights).astype(np.float64)
def paired_permutation_test(
method_scores: Sequence[float] | NDArray[np.float64],
baseline_scores: Sequence[float] | NDArray[np.float64],
n_resamples: int = 5000,
seed: int = 42,
alternative: Literal["two-sided", "greater"] = "two-sided",
) -> float:
"""Deterministic paired sign-flip permutation test (Phipson-Smyth finite-sample p-value)."""
if n_resamples < 5000:
raise ValueError("n_resamples must be >= 5000 for stable permutation p-values")
m_arr = _as_float_array(method_scores, "method_scores")
b_arr = _as_float_array(baseline_scores, "baseline_scores")
if m_arr.size != b_arr.size or m_arr.size < 2:
raise ValueError("Paired permutation test requires equal-length arrays with n >= 2")
diff = m_arr - b_arr
obs_mean = float(np.mean(diff))
if np.all(np.abs(diff) <= 1e-15):
return 1.0
rng = np.random.default_rng(seed)
signs = rng.choice(np.array([-1.0, 1.0], dtype=np.float64), size=(n_resamples, diff.size))
perm_means = (signs @ diff) / float(diff.size)
if alternative == "two-sided":
extreme = int(np.sum(np.abs(perm_means) >= abs(obs_mean) - 1e-12))
else:
extreme = int(np.sum(perm_means >= obs_mean - 1e-12))
return float((extreme + 1) / (n_resamples + 1))
def wilcoxon_signed_rank_test(
method_scores: Sequence[float] | NDArray[np.float64],
baseline_scores: Sequence[float] | NDArray[np.float64],
) -> WilcoxonTestResult:
"""Compute exact (n<=14) or tie/continuity-corrected asymptotic two-sided Wilcoxon test."""
m_arr = _as_float_array(method_scores, "method_scores")
b_arr = _as_float_array(baseline_scores, "baseline_scores")
if m_arr.size != b_arr.size or m_arr.size < 1:
raise ValueError("Paired Wilcoxon test requires equal-length arrays with n >= 1")
diffs = m_arr - b_arr
nonzero_mask = np.abs(diffs) > 1e-12
d = diffs[nonzero_mask]
n_nz = int(d.size)
if n_nz == 0:
return WilcoxonTestResult(
n_pairs=int(m_arr.size),
n_nonzero=0,
w_plus=0.0,
w_minus=0.0,
w_statistic=0.0,
p_value=1.0,
method="exact",
)
abs_d = np.abs(d)
order = np.argsort(abs_d, kind="mergesort")
sorted_abs = abs_d[order]
ranks = np.empty(n_nz, dtype=np.float64)
tie_counts: list[int] = []
idx = 0
while idx < n_nz:
end = idx + 1
while end < n_nz and abs(float(sorted_abs[end] - sorted_abs[idx])) <= 1e-12:
end += 1
avg_rank = 0.5 * float((idx + 1) + end)
ranks[order[idx:end]] = avg_rank
if end - idx > 1:
tie_counts.append(end - idx)
idx = end
w_plus = float(np.sum(ranks[d > 0.0]))
w_minus = float(np.sum(ranks[d < 0.0]))
w_stat = min(w_plus, w_minus)
if n_nz <= 14:
bit_indices = np.arange(n_nz, dtype=np.int64)[None, :]
masks = (np.arange(1 << n_nz, dtype=np.int64)[:, None] >> bit_indices) & 1
w_plus_dist = masks.astype(np.float64) @ ranks
total_rank = float(np.sum(ranks))
w_stat_dist = np.minimum(w_plus_dist, total_rank - w_plus_dist)
p_val = float(np.mean(w_stat_dist <= w_stat + 1e-12))
method_used: Literal["exact", "asymptotic"] = "exact"
else:
mean_w = float(n_nz * (n_nz + 1)) / 4.0
tie_term = sum(t * (t * t - 1) for t in tie_counts)
var_w = (float(n_nz * (n_nz + 1) * (2 * n_nz + 1)) / 24.0) - (float(tie_term) / 48.0)
if var_w <= 1e-12:
p_val = 1.0
else:
z_stat = max(0.0, abs(w_plus - mean_w) - 0.5) / math.sqrt(var_w)
p_val = float(min(1.0, math.erfc(z_stat / math.sqrt(2.0))))
method_used = "asymptotic"
return WilcoxonTestResult(
n_pairs=int(m_arr.size),
n_nonzero=n_nz,
w_plus=round(w_plus, 4),
w_minus=round(w_minus, 4),
w_statistic=round(w_stat, 4),
p_value=round(p_val, 6),
method=method_used,
)
def holm_bonferroni_adjust(p_values: Sequence[float]) -> list[float]:
"""Step-down Holm-Bonferroni adjusted p-values strictly controlling FWER."""
p_arr = _as_float_array(p_values, "p_values")
if np.any((p_arr < 0.0) | (p_arr > 1.0)):
raise ValueError("All p-values must lie in [0, 1]")
m = int(p_arr.size)
order = np.argsort(p_arr, kind="mergesort")
adjusted_sorted = np.empty(m, dtype=np.float64)
running_max = 0.0
for rank_idx in range(m):
orig_idx = int(order[rank_idx])
candidate = min(1.0, float(m - rank_idx) * float(p_arr[orig_idx]))
running_max = max(running_max, candidate)
adjusted_sorted[rank_idx] = running_max
adjusted = np.empty(m, dtype=np.float64)
adjusted[order] = adjusted_sorted
return [float(x) for x in adjusted]
def benjamini_hochberg_adjust(p_values: Sequence[float]) -> list[float]:
"""Step-up Benjamini-Hochberg adjusted q-values controlling False Discovery Rate (FDR)."""
p_arr = _as_float_array(p_values, "p_values")
if np.any((p_arr < 0.0) | (p_arr > 1.0)):
raise ValueError("All p-values must lie in [0, 1]")
m = int(p_arr.size)
order = np.argsort(p_arr, kind="mergesort")
adjusted_sorted = np.empty(m, dtype=np.float64)
running_min = 1.0
for rank_idx in range(m - 1, -1, -1):
orig_idx = int(order[rank_idx])
candidate = min(1.0, (float(m) / float(rank_idx + 1)) * float(p_arr[orig_idx]))
running_min = min(running_min, candidate)
adjusted_sorted[rank_idx] = running_min
adjusted = np.empty(m, dtype=np.float64)
adjusted[order] = adjusted_sorted
return [float(x) for x in adjusted]
def compare_methods_multiseed(
method_name: str,
baseline_name: str,
method_scores: Sequence[float],
baseline_scores: Sequence[float],
optimality_threshold: float = 100.0,
n_resamples: int = 5000,
alpha: float = 0.05,
seed: int = 42,
) -> MultiSeedComparisonResult:
"""Run full rliable + bootstrap CI + paired permutation audit on multi-seed runs."""
m_arr = _as_float_array(method_scores, "method_scores")
b_arr = _as_float_array(baseline_scores, "baseline_scores")
if m_arr.size != b_arr.size or m_arr.size < 2:
raise ValueError("Paired multi-seed evaluation requires equal lengths >= 2")
diff_iqm, ci_low, ci_high = stratified_bootstrap_ci(
m_arr,
b_arr,
n_resamples=n_resamples,
alpha=alpha,
seed=seed,
use_iqm=True,
)
p_val = paired_permutation_test(
m_arr,
b_arr,
n_resamples=n_resamples,
seed=seed,
alternative="two-sided",
)
m_mean = float(np.mean(m_arr))
b_mean = float(np.mean(b_arr))
m_iqm = interquartile_mean(m_arr)
b_iqm = interquartile_mean(b_arr)
d_val = cohens_d_paired(m_arr, b_arr)
p_imp = probability_of_improvement(m_arr, b_arr)
og_m = optimality_gap(m_arr, threshold=optimality_threshold)
og_b = optimality_gap(b_arr, threshold=optimality_threshold)
return MultiSeedComparisonResult(
method_name=method_name,
baseline_name=baseline_name,
n_seeds=int(m_arr.size),
method_mean=round(m_mean, 4),
baseline_mean=round(b_mean, 4),
method_iqm=round(m_iqm, 4),
baseline_iqm=round(b_iqm, 4),
diff_mean=round(m_mean - b_mean, 4),
diff_iqm=round(diff_iqm, 4),
ci_low=round(ci_low, 4),
ci_high=round(ci_high, 4),
ci_half_width=round(0.5 * (ci_high - ci_low), 4),
cohens_d=round(d_val, 4),
prob_improvement=round(p_imp, 4),
optimality_gap_method=round(og_m, 4),
optimality_gap_baseline=round(og_b, 4),
permutation_p_value=round(p_val, 6),
is_significant_two_sided=(p_val < alpha),
improved_lower_bound=(ci_low > 0.0),
)
def simulate_multiple_testing_inflation(
m_comparisons: int = 20,
n_null_families: int = 1000,
n_seeds_per_exp: int = 10,
alpha: float = 0.05,
seed: int = 42,
) -> MultipleTestingSummary:
"""Quantify FWER inflation under H0 across m comparisons vs Holm-Bonferroni & BH-FDR."""
if m_comparisons < 2:
raise ValueError("m_comparisons must be >= 2")
rng = np.random.default_rng(seed)
# Vectorized simulation of n_null_families studies, each testing m null hypotheses
# via paired Gaussian diffs (t-test calibrated exactly with normal CDF / exact t-crit)
diffs = rng.normal(loc=0.0, scale=1.0, size=(n_null_families, m_comparisons, n_seeds_per_exp))
means = np.mean(diffs, axis=2)
stds = np.std(diffs, axis=2, ddof=1)
t_stats = np.abs(means) / np.maximum(stds / math.sqrt(n_seeds_per_exp), 1e-12)
# Exact two-sided Student-t p-values via numerical survival integration for df = n_seeds - 1
df = n_seeds_per_exp - 1
p_matrix = _student_t_two_sided_p_matrix(t_stats, df=df)
raw_fwer_hits = 0
holm_fwer_hits = 0
bh_fdr_sum = 0.0
for fam_idx in range(n_null_families):
row_p = [float(x) for x in p_matrix[fam_idx]]
if any(p < alpha for p in row_p):
raw_fwer_hits += 1
holm_p = holm_bonferroni_adjust(row_p)
if any(p < alpha for p in holm_p):
holm_fwer_hits += 1
bh_p = benjamini_hochberg_adjust(row_p)
if any(q < alpha for q in bh_p):
bh_fdr_sum += 1.0 # Under global null, FDP = 1 whenever >= 1 rejection, else 0
# Concrete single-study showcase (m=20: first 17 are true nulls, last 3 have real gains)
n_true_alt = min(3, max(1, m_comparisons // 6))
n_true_null = m_comparisons - n_true_alt
study_p_vals: list[float] = []
for cmp_idx in range(m_comparisons):
base_s = rng.normal(loc=80.0, scale=1.5, size=n_seeds_per_exp)
true_gain = 0.0 if cmp_idx < n_true_null else (2.4 + 0.5 * (cmp_idx - n_true_null))
meth_s = base_s + rng.normal(loc=true_gain, scale=1.4, size=n_seeds_per_exp)
p_val = paired_permutation_test(
meth_s,
base_s,
n_resamples=5000,
seed=seed + 100 + cmp_idx,
alternative="two-sided",
)
study_p_vals.append(round(p_val, 6))
holm_study = [round(x, 6) for x in holm_bonferroni_adjust(study_p_vals)]
bh_study = [round(x, 6) for x in benjamini_hochberg_adjust(study_p_vals)]
raw_rej = [i for i, p in enumerate(study_p_vals) if p < alpha]
holm_rej = [i for i, p in enumerate(holm_study) if p < alpha]
bh_rej = [i for i, q in enumerate(bh_study) if q < alpha]
return MultipleTestingSummary(
m_comparisons=m_comparisons,
n_null_families=n_null_families,
alpha=alpha,
theoretical_null_fwer=round(1.0 - (1.0 - alpha) ** m_comparisons, 4),
empirical_null_fwer=round(raw_fwer_hits / float(n_null_families), 4),
holm_empirical_null_fwer=round(holm_fwer_hits / float(n_null_families), 4),
bh_empirical_null_fdr=round(bh_fdr_sum / float(n_null_families), 4),
study_true_nulls=n_true_null,
study_true_alternatives=n_true_alt,
study_raw_rejections=len(raw_rej),
study_raw_false_positives=sum(1 for idx in raw_rej if idx < n_true_null),
study_holm_rejections=len(holm_rej),
study_holm_false_positives=sum(1 for idx in holm_rej if idx < n_true_null),
study_bh_rejections=len(bh_rej),
study_bh_false_positives=sum(1 for idx in bh_rej if idx < n_true_null),
raw_p_values=study_p_vals,
holm_adjusted_p_values=holm_study,
bh_adjusted_p_values=bh_study,
)
def chi_mixture_grid(df: int, n_points: int = 320) -> tuple[NDArray[np.float64], NDArray[np.float64]]:
"""Return quadrature scales sqrt(V/df) and weights for V ~ chi2(df) using s = sqrt(V)."""
s_max = max(8.5, math.sqrt(float(df)) + 7.5)
edges = np.linspace(0.0, s_max, n_points + 1, dtype=np.float64)
s_mid = 0.5 * (edges[:-1] + edges[1:])
ds = float(edges[1] - edges[0])
half_df = 0.5 * float(df)
# f_chi(s) = s^(df-1) * exp(-s^2 / 2) / (2^(df/2 - 1) * Gamma(df/2))
log_pdf = (
(float(df) - 1.0) * np.log(s_mid)
- 0.5 * (s_mid**2)
- (half_df - 1.0) * math.log(2.0)
- math.lgamma(half_df)
)
# Shift by max(log_pdf) for overflow safety at large df
log_pdf -= float(np.max(log_pdf))
weights = np.exp(log_pdf) * ds
weights /= float(np.sum(weights))
scales = s_mid / math.sqrt(float(df))
return scales, weights
def _student_t_two_sided_p_matrix(t_abs: NDArray[np.float64], df: int) -> NDArray[np.float64]:
"""Compute exact two-sided Student-t p-values via chi mixture quadrature."""
scales, weights = chi_mixture_grid(df=df, n_points=320)
flat_t = t_abs.ravel()
z_mat = flat_t[:, None] * scales[None, :]
inv_sqrt2 = 1.0 / math.sqrt(2.0)
z_scaled = z_mat * inv_sqrt2
p_flat = np.empty(flat_t.size, dtype=np.float64)
for idx in range(flat_t.size):
row = z_scaled[idx]
probs = np.array([math.erfc(float(val)) for val in row], dtype=np.float64)
p_flat[idx] = float(np.dot(probs, weights))
return np.clip(p_flat.reshape(t_abs.shape), 1e-12, 1.0).astype(np.float64)
# ---------------------------------------------------------------------------
# Controlled Ablation Confounder Detector & LaTeX Booktabs Exporter
# ---------------------------------------------------------------------------
def _hamming_distance(a: dict[str, bool | str], b: dict[str, bool | str]) -> list[str]:
keys = sorted(set(a.keys()) | set(b.keys()))
return [k for k in keys if a.get(k) != b.get(k)]
def analyze_ablation_table(
table_label: str,
runs: Sequence[AblationRunRow],
baseline_run_id: str,
) -> AblationAuditReport:
"""Audit ablation table for multi-factor confounders and tuning budget asymmetry."""
if not runs:
raise ValueError("Ablation table cannot be empty")
by_id = {r.run_id: r for r in runs}
if baseline_run_id not in by_id:
raise ValueError(f"baseline_run_id {baseline_run_id!r} not found in runs")
baseline = by_id[baseline_run_id]
findings: list[AblationConfounderFinding] = []
clean_transitions = 0
for row in runs:
if row.run_id == baseline_run_id:
continue
# Check if there exists at least one OTHER row in the table at Hamming distance == 1
# that is closer (or equal) in distance from baseline, forming a connected 1-factor path.
dist_from_base = len(_hamming_distance(row.factors, baseline.factors))
single_step_neighbors = [
other
for other in runs
if other.run_id != row.run_id
and len(_hamming_distance(row.factors, other.factors)) == 1
and len(_hamming_distance(other.factors, baseline.factors)) < dist_from_base
]
if dist_from_base == 1 or len(single_step_neighbors) >= 1:
clean_transitions += 1
else:
changed = _hamming_distance(row.factors, baseline.factors)
findings.append(
AblationConfounderFinding(
issue_type="confounded_multi_factor",
severity="CRITICAL",
run_ids=[baseline_run_id, row.run_id],
description=(
f"Row '{row.run_id}' alters {len(changed)} factors simultaneously "
f"({', '.join(changed)}) without an intervening single-factor ablation."
),
)
)
max_trials = max(r.tuning_trials for r in runs)
asymmetry = max_trials > baseline.tuning_trials and (
max_trials >= 3 * baseline.tuning_trials or baseline.tuning_trials == 1
)
if asymmetry:
asym_ids = [r.run_id for r in runs if r.tuning_trials > baseline.tuning_trials]
findings.append(
AblationConfounderFinding(
issue_type="unfair_tuning_asymmetry",
severity="CRITICAL",
run_ids=[baseline_run_id, *asym_ids],
description=(
f"Tune-the-baseline violation: baseline '{baseline_run_id}' received "
f"{baseline.tuning_trials} trial(s) while candidate runs received up to "
f"{max_trials} trials."
),
)
)
# Extract clean single-factor main effects (1-factor diff from baseline) and 2-way interactions
main_effects: dict[str, float] = {}
single_factor_runs: dict[str, AblationRunRow] = {}
for row in runs:
if row.run_id == baseline_run_id:
continue
changed = _hamming_distance(row.factors, baseline.factors)
if len(changed) == 1:
fkey = changed[0]
main_effects[fkey] = round(row.metric_score - baseline.metric_score, 4)
single_factor_runs[fkey] = row
interaction_effects: dict[str, float] = {}
for row in runs:
if row.run_id == baseline_run_id:
continue
changed = _hamming_distance(row.factors, baseline.factors)
if len(changed) == 2:
fa, fb = changed[0], changed[1]
if fa in single_factor_runs and fb in single_factor_runs:
ra = single_factor_runs[fa]
rb = single_factor_runs[fb]
if (
row.factors.get(fa) == ra.factors.get(fa)
and row.factors.get(fb) == rb.factors.get(fb)
):
inter = (
row.metric_score
- ra.metric_score
- rb.metric_score
+ baseline.metric_score
)
interaction_effects[f"{fa} x {fb}"] = round(inter, 4)
return AblationAuditReport(
table_label=table_label,
total_runs=len(runs),
clean_single_factor_transitions=clean_transitions,
confounders=findings,
tuning_asymmetry_detected=asymmetry,
baseline_tuning_trials=baseline.tuning_trials,
max_method_tuning_trials=max_trials,
main_effects=main_effects,
interaction_effects=interaction_effects,
audit_passed=(len(findings) == 0),
)
def export_booktabs_latex_table(
caption: str,
label: str,
metric_names: Sequence[str],
rows: Sequence[dict[str, Any]],
higher_is_better: Sequence[bool] | None = None,
) -> str:
"""Export publication-grade LaTeX booktabs table bolding statistically tied winners."""
if not metric_names or not rows:
raise ValueError("metric_names and rows must be non-empty")
hib = list(higher_is_better) if higher_is_better is not None else [True] * len(metric_names)
if len(hib) != len(metric_names):
raise ValueError("higher_is_better length must match metric_names")
# Determine column winners and statistically indistinguishable ties (overlapping 95% CI)
bold_mask: list[list[bool]] = [[False] * len(metric_names) for _ in rows]
for m_idx, m_name in enumerate(metric_names):
means = [float(r["metrics"][m_name]["mean"]) for r in rows]
cis = [float(r["metrics"][m_name]["ci"]) for r in rows]
best_idx = int(np.argmax(means) if hib[m_idx] else np.argmin(means))
best_mean = means[best_idx]
best_ci = cis[best_idx]
for r_idx, (val, ci_hw) in enumerate(zip(means, cis, strict=True)):
# Statistically indistinguishable if point difference <= combined half-width proxy
# or intervals overlap when comparing paired uncertainty.
if hib[m_idx]:
tied = (best_mean - val) <= max(best_ci, ci_hw)
else:
tied = (val - best_mean) <= max(best_ci, ci_hw)
bold_mask[r_idx][m_idx] = tied
col_spec = "l" + "c" * len(metric_names)
header_cells = ["Method", *[m.replace("_", r"\_") for m in metric_names]]
lines = [
r"\begin{table}[t]",
r"\centering",
rf"\caption{{{caption}}}",
rf"\label{{{label}}}",
rf"\begin{{tabular}}{{{col_spec}}}",
r"\toprule",
" & ".join(header_cells) + r" \\",
r"\midrule",
]
for r_idx, row in enumerate(rows):
cells = [str(row["method"])]
for m_idx, m_name in enumerate(metric_names):
m_data = row["metrics"][m_name]
val_str = f"{float(m_data['mean']):.2f} \\pm {float(m_data['ci']):.2f}"
if bold_mask[r_idx][m_idx]:
cells.append(rf"\textbf{{${val_str}$}}")
else:
cells.append(rf"${val_str}$")
lines.append(" & ".join(cells) + r" \\")
lines.extend([r"\bottomrule", r"\end{tabular}", r"\end{table}"])
return "\n".join(lines)
# ---------------------------------------------------------------------------
# Built-In Experiments 1 & 2 (Multi-Seed Power, FWER, Confounder Audit)
# ---------------------------------------------------------------------------
def run_exp1_multiseed_and_fwer(
seed: int = 42,
n_resamples: int = 5000,
quick: bool = False,
) -> dict[str, Any]:
"""Run Exp 1: n=3 vs n=10 underpowering, IQM outlier resistance, and m=20 FWER inflation."""
rng = np.random.default_rng(seed)
# True effect: +2.45pp gain over strong baseline (~80.0), paired std ~1.75pp across 10 seeds
n_full = 10
baseline_10 = np.round(rng.normal(loc=80.0, scale=1.4, size=n_full), 3)
paired_gains_10 = np.array(
[1.10, -0.45, 2.35, 3.80, 2.95, 2.65, 3.20, 2.15, 3.55, 3.10],
dtype=np.float64,
)
method_10 = np.round(baseline_10 + paired_gains_10, 3)
# First 3 seeds alone (n=3) underpower the exact permutation test (2^3 = 8 flips -> min p >= 0.25)
underpowered_n3 = compare_methods_multiseed(
method_name="ProposedMethod (n=3 seeds)",
baseline_name="FairBaseline (n=3 seeds)",
method_scores=[float(x) for x in method_10[:3]],
baseline_scores=[float(x) for x in baseline_10[:3]],
optimality_threshold=100.0,
n_resamples=n_resamples,
seed=seed,
)
rigorous_n10 = compare_methods_multiseed(
method_name="ProposedMethod (n=10 seeds)",
baseline_name="FairBaseline (n=10 seeds)",
method_scores=[float(x) for x in method_10],
baseline_scores=[float(x) for x in baseline_10],
optimality_threshold=100.0,
n_resamples=n_resamples,
seed=seed,
)
# Outlier seed corruption: 1 crashed seed (-42.0pp) flips arithmetic mean negative while IQM holds
method_outlier = method_10.copy()
method_outlier[1] = 39.5
outlier_resistance = compare_methods_multiseed(
method_name="ProposedMethod (1 Outlier Crash)",
baseline_name="FairBaseline",
method_scores=[float(x) for x in method_outlier],
baseline_scores=[float(x) for x in baseline_10],
optimality_threshold=100.0,
n_resamples=n_resamples,
seed=seed,
)
# Exp 1B: m=20 simultaneous null tests p-hacking vs Holm-Bonferroni & Benjamini-Hochberg
n_fam = 400 if quick else 2000
fwer_summary = simulate_multiple_testing_inflation(
m_comparisons=20,
n_null_families=n_fam,
n_seeds_per_exp=10,
alpha=0.05,
seed=seed,
)
wilcoxon_n3 = wilcoxon_signed_rank_test(method_10[:3], baseline_10[:3])
wilcoxon_n10 = wilcoxon_signed_rank_test(method_10, baseline_10)
wilcoxon_outlier = wilcoxon_signed_rank_test(method_outlier, baseline_10)
return {
"underpowered_n3": underpowered_n3.model_dump(),
"rigorous_n10": rigorous_n10.model_dump(),
"outlier_iqm_vs_mean": outlier_resistance.model_dump(),
"wilcoxon_n3": wilcoxon_n3.model_dump(),
"wilcoxon_n10": wilcoxon_n10.model_dump(),
"wilcoxon_outlier": wilcoxon_outlier.model_dump(),
"multiple_testing_m20": fwer_summary.model_dump(),
"baseline_10_scores": [float(x) for x in baseline_10],
"method_10_scores": [float(x) for x in method_10],
"method_outlier_scores": [float(x) for x in method_outlier],
}
def _simulate_ablation_config(
rng: np.random.Generator,
seed_base_scores: NDArray[np.float64],
arch_gate: bool,
cosine_lr: bool,
mixup_aug: bool,
tuning_trials: int,
boot_seed: int,
) -> tuple[list[float], float, float, float]:
"""Simulate n=10 seeds under B validation HP trials; compute IQM, OG & bootstrap CI."""
true_gain = (
(2.20 if arch_gate else 0.0)
+ (1.35 if mixup_aug else 0.0)
+ (0.15 if cosine_lr else 0.0)
+ (0.50 if (arch_gate and mixup_aug) else 0.0)
)
hp_curve = 1.25 * (1.0 - np.exp(-np.linspace(0.32, 2.25, tuning_trials)))
val_scores = hp_curve + rng.normal(0.0, 0.36, size=tuning_trials)
best_hp = int(np.argmax(val_scores))
hp_lift = float(hp_curve[best_hp])
seed_noise = rng.normal(0.0, 0.25, size=seed_base_scores.size)
scores = np.round(seed_base_scores + true_gain + hp_lift + seed_noise, 3)
iqm_val = interquartile_mean(scores)
og_val = optimality_gap(scores, threshold=100.0)
boot_rng = np.random.default_rng(boot_seed)
boot_idx = boot_rng.integers(0, scores.size, size=(5000, scores.size))
boot_iqms = _vectorized_iqm(scores[boot_idx])
ci_hw = 0.5 * (float(np.quantile(boot_iqms, 0.975)) - float(np.quantile(boot_iqms, 0.025)))
return [float(x) for x in scores], round(iqm_val, 2), round(ci_hw, 2), round(og_val, 2)
def run_exp2_ablation_confounder_audit(seed: int = 42) -> dict[str, Any]:
"""Run Exp 2: Simulated confounded/asymmetric table vs clean 2x2 table + LaTeX export."""
rng = np.random.default_rng(seed + 202)
base_seeds = rng.normal(loc=78.75, scale=1.25, size=10)
specs: list[tuple[str, str, bool, bool, bool, int]] = [
("baseline_default", "Baseline (Untuned Default, 1 trial)", False, False, False, 1),
("our_method_full", "Our Method (15-Trial Asymmetric)", True, True, True, 15),
("fair_baseline", "Fair-Tuned Baseline (8 trials)", False, False, False, 8),
("add_arch_gate", "+ Arch Gate Only (8 trials)", True, False, False, 8),
("add_cosine_lr", "+ CosineLR Only (8 trials)", False, True, False, 8),
("add_mixup_aug", "+ MixUp Only (8 trials)", False, False, True, 8),
("arch_plus_mixup", "+ Arch Gate + MixUp (8 trials)", True, False, True, 8),
("full_system", "Full System (+ CosineLR, 8 trials)", True, True, True, 8),
]
sim_rows: dict[str, AblationRunRow] = {}
sim_labels: dict[str, str] = {}
sim_ogs: dict[str, float] = {}
sim_seed_scores: dict[str, list[float]] = {}
for idx, (rid, lbl, arch, cos_lr, mixup, trials) in enumerate(specs):
scores, iqm_sc, ci_hw, og_sc = _simulate_ablation_config(
rng=rng,
seed_base_scores=base_seeds,
arch_gate=arch,
cosine_lr=cos_lr,
mixup_aug=mixup,
tuning_trials=trials,
boot_seed=seed + 300 + idx,
)
sim_seed_scores[rid] = scores
sim_labels[rid] = lbl
sim_ogs[rid] = og_sc
sim_rows[rid] = AblationRunRow(
run_id=rid,
factors={"arch_gate": arch, "cosine_lr": cos_lr, "mixup_aug": mixup},
tuning_trials=trials,
metric_score=iqm_sc,
ci_half_width=ci_hw,
)
flawed_audit = analyze_ablation_table(
table_label="Flawed Confounded & Asymmetric Table",
runs=[sim_rows["baseline_default"], sim_rows["our_method_full"]],
baseline_run_id="baseline_default",
)
clean_ids = [
"fair_baseline",
"add_arch_gate",
"add_cosine_lr",
"add_mixup_aug",
"arch_plus_mixup",
"full_system",
]
clean_audit = analyze_ablation_table(
table_label="Clean Orthogonal 1-Factor & Symmetric Table",
runs=[sim_rows[k] for k in clean_ids],
baseline_run_id="fair_baseline",
)
latex_ids = [
"baseline_default",
"fair_baseline",
"add_arch_gate",
"arch_plus_mixup",
"full_system",
]
latex_rows: list[dict[str, Any]] = [
{
"method": sim_labels[rid],
"metrics": {
"IQM_Acc (%)": {
"mean": sim_rows[rid].metric_score,
"ci": sim_rows[rid].ci_half_width,
},
"Optimality_Gap": {
"mean": sim_ogs[rid],
"ci": sim_rows[rid].ci_half_width,
},
},
}
for rid in latex_ids
]
latex_table = export_booktabs_latex_table(
caption=(
"Controlled orthogonal ablation under equal 8-trial tuning budget "
"(n=10 seeds, R=5000 bootstrap 95\\% CI). Statistically tied winners are bolded."
),
label="tab:controlled_ablation",
metric_names=["IQM_Acc (%)", "Optimality_Gap"],
rows=latex_rows,
higher_is_better=[True, False],
)
flawed_gain = sim_rows["our_method_full"].metric_score - sim_rows["baseline_default"].metric_score
fair_gain = sim_rows["full_system"].metric_score - sim_rows["fair_baseline"].metric_score
return {
"flawed_audit": flawed_audit.model_dump(),
"clean_audit": clean_audit.model_dump(),
"flawed_claimed_gain_pp": round(flawed_gain, 2),
"fair_true_gain_pp": round(fair_gain, 2),
"tuning_bias_inflation_pp": round(flawed_gain - fair_gain, 2),
"simulated_seed_scores": sim_seed_scores,
"latex_booktabs_table": latex_table,
}
"""Split/leakage auditing, Student-t seed power/MDE planning, GPU budgeting & OTel orchestration."""
from __future__ import annotations
import argparse
import json
import math
from collections.abc import Sequence
from typing import Any, Literal
import numpy as np
from numpy.typing import NDArray
from pydantic import BaseModel, ConfigDict, Field
from research_methodology_lab.ablation_and_stats import (
chi_mixture_grid,
create_in_memory_otel_tracer,
run_exp1_multiseed_and_fwer,
run_exp2_ablation_confounder_audit,
)
# ---------------------------------------------------------------------------
# Strict Pydantic v2 Schemas
# ---------------------------------------------------------------------------
class LeakageAuditFinding(BaseModel):
"""Individual data split or preprocessing leakage check finding."""
model_config = ConfigDict(extra="forbid")
check_name: Literal[
"id_overlap",
"group_leakage",
"temporal_leakage",
"preprocessing_leakage",
]
leaked: bool
severity: Literal["CRITICAL", "INFO"]
overlap_count: int = Field(ge=0)
details: str
class LeakageAuditReport(BaseModel):
"""Full audit report comparing leaked vs clean evaluation performance."""
model_config = ConfigDict(extra="forbid")
scenario_name: str
n_train: int = Field(ge=1)
n_val: int = Field(ge=1)
n_test: int = Field(ge=1)
findings: list[LeakageAuditFinding]
leakage_free: bool
eval_accuracy: float = Field(ge=0.0, le=1.0)
eval_roc_auc: float = Field(ge=0.0, le=1.0)
class GPUComputeTier(BaseModel):
"""Cloud/notebook GPU hardware tier pricing and preemption overhead model."""
model_config = ConfigDict(extra="forbid")
tier_id: str
label: str
hourly_usd: float = Field(ge=0.0)
effective_opportunity_usd_hr: float = Field(ge=0.0)
vram_gb: int = Field(ge=4)
tflops_bf16: float = Field(gt=0.0)
preemption_overhead_factor: float = Field(ge=1.0)
checkpoint_overhead_factor: float = Field(ge=1.0)
max_session_hours: float = Field(gt=0.0)
class PowerBudgetPlan(BaseModel):
"""Joint Student-t seed power sizing and cloud GPU cost estimation."""
model_config = ConfigDict(extra="forbid")
tier_id: str
tier_label: str
effect_size_delta: float = Field(gt=0.0)
seed_std: float = Field(gt=0.0)
alpha: float = Field(gt=0.0, lt=1.0)
target_power: float = Field(gt=0.5, lt=1.0)
required_seeds_n: int = Field(ge=2)
achieved_power: float = Field(ge=0.0, le=1.0)
minimum_detectable_effect: float = Field(gt=0.0)
n_methods_and_ablations: int = Field(ge=1)
hp_trials_per_method: int = Field(ge=1)
hours_per_run: float = Field(gt=0.0)
total_runs: int = Field(ge=1)
raw_gpu_hours: float = Field(gt=0.0)
effective_gpu_hours: float = Field(gt=0.0)
total_cost_usd: float = Field(ge=0.0)
budget_cap_usd: float = Field(gt=0.0)
fits_budget: bool
class ReproducibilityChecklistInput(BaseModel):
"""Input checklist for NeurIPS/ICML/RIVF reproducibility and rebuttal readiness."""
model_config = ConfigDict(extra="forbid")
submission_name: str
fixed_seeds_logged: bool
confidence_intervals_reported: bool
multiple_testing_corrected: bool
equal_baseline_tuning_budget: bool
single_factor_ablations_complete: bool
leakage_audit_passed: bool
compute_hours_and_hardware_disclosed: bool
limitations_and_negative_results_included: bool
class ReproducibilityGateReport(BaseModel):
"""Structured audit score and rebuttal decision for a paper submission."""
model_config = ConfigDict(extra="forbid")
submission_name: str
artifact_score: int = Field(ge=0, le=8)
max_score: int = 8
passed_checks: list[str]
failed_checks: list[str]
rebuttal_readiness: Literal["ACCEPT_READY", "MINOR_REVISION", "REJECT_RISK"]
recommendation: str
# ---------------------------------------------------------------------------
# GPU Tier Catalog (2025-2026 Colab vs vast.ai Spot vs On-Demand)
# ---------------------------------------------------------------------------
GPU_COMPUTE_CATALOG: dict[str, GPUComputeTier] = {
"colab_free_t4": GPUComputeTier(
tier_id="colab_free_t4",
label="Colab Free T4 (16GB, 4h cap)",
hourly_usd=0.0,
effective_opportunity_usd_hr=0.18,
vram_gb=16,
tflops_bf16=65.0,
preemption_overhead_factor=1.35,
checkpoint_overhead_factor=1.08,
max_session_hours=4.0,
),
"colab_pro_l4": GPUComputeTier(
tier_id="colab_pro_l4",
label="Colab Pro L4 (24GB, 12h cap)",
hourly_usd=0.55,
effective_opportunity_usd_hr=0.55,
vram_gb=24,
tflops_bf16=121.0,
preemption_overhead_factor=1.10,
checkpoint_overhead_factor=1.05,
max_session_hours=12.0,
),
"vast_rtx_4090_spot": GPUComputeTier(
tier_id="vast_rtx_4090_spot",
label="vast.ai RTX 4090 Spot (24GB)",
hourly_usd=0.34,
effective_opportunity_usd_hr=0.34,
vram_gb=24,
tflops_bf16=165.0,
preemption_overhead_factor=1.18,
checkpoint_overhead_factor=1.04,
max_session_hours=72.0,
),
"vast_a100_80gb": GPUComputeTier(
tier_id="vast_a100_80gb",
label="vast.ai A100-SXM 80GB",
hourly_usd=1.15,
effective_opportunity_usd_hr=1.15,
vram_gb=80,
tflops_bf16=312.0,
preemption_overhead_factor=1.07,
checkpoint_overhead_factor=1.03,
max_session_hours=168.0,
),
"ondemand_a100_80gb": GPUComputeTier(
tier_id="ondemand_a100_80gb",
label="Cloud On-Demand A100 80GB",
hourly_usd=2.20,
effective_opportunity_usd_hr=2.20,
vram_gb=80,
tflops_bf16=312.0,
preemption_overhead_factor=1.01,
checkpoint_overhead_factor=1.02,
max_session_hours=720.0,
),
}
# ---------------------------------------------------------------------------
# Leakage & Split Integrity Auditor + Quantitative Score Inflation Demo
# ---------------------------------------------------------------------------
def audit_split_and_preprocessing_leakage(
scenario_name: str,
train_ids: Sequence[str],
val_ids: Sequence[str],
test_ids: Sequence[str],
train_groups: Sequence[str],
val_groups: Sequence[str],
test_groups: Sequence[str],
train_timestamps: Sequence[float],
val_timestamps: Sequence[float],
test_timestamps: Sequence[float],
scaler_fitted_on: Literal["train_only", "full_dataset"],
eval_accuracy: float,
eval_roc_auc: float,
) -> LeakageAuditReport:
"""Verify ID disjointness, group separation, chronological ordering & scaler fit scope."""
t_ids, v_ids, te_ids = set(train_ids), set(val_ids), set(test_ids)
id_overlap = len(t_ids & v_ids) + len(t_ids & te_ids) + len(v_ids & te_ids)
t_grp, v_grp, te_grp = set(train_groups), set(val_groups), set(test_groups)
grp_overlap = len(t_grp & v_grp) + len(t_grp & te_grp) + len(v_grp & te_grp)
max_train_ts = max(train_timestamps)
min_val_ts = min(val_timestamps)
max_val_ts = max(val_timestamps)
min_test_ts = min(test_timestamps)
temporal_violations = (
sum(1 for ts in train_timestamps if ts >= min_val_ts or ts >= min_test_ts)
+ sum(1 for ts in val_timestamps if ts >= min_test_ts)
)
temporal_leaked = (
max_train_ts >= min_val_ts or max_train_ts >= min_test_ts or max_val_ts >= min_test_ts
)
prep_leaked = scaler_fitted_on != "train_only"
findings = [
LeakageAuditFinding(
check_name="id_overlap",
leaked=id_overlap > 0,
severity="CRITICAL" if id_overlap > 0 else "INFO",
overlap_count=id_overlap,
details=(
f"Found {id_overlap} shared sample ID(s) across train/val/test."
if id_overlap > 0
else "Zero sample ID overlaps across splits."
),
),
LeakageAuditFinding(
check_name="group_leakage",
leaked=grp_overlap > 0,
severity="CRITICAL" if grp_overlap > 0 else "INFO",
overlap_count=grp_overlap,
details=(
f"Found {grp_overlap} entity/patient group(s) leaking across splits."
if grp_overlap > 0
else "All entity groups strictly disjoint across splits."
),
),
LeakageAuditFinding(
check_name="temporal_leakage",
leaked=temporal_leaked,
severity="CRITICAL" if temporal_leaked else "INFO",
overlap_count=temporal_violations,
details=(
f"Chronological violation: max(t_train)={max_train_ts:.1f} vs "
f"min(t_test)={min_test_ts:.1f} ({temporal_violations} out-of-order rows)."
if temporal_leaked
else (
f"Strict forward temporal order: t_train <= {max_train_ts:.1f} < "
f"t_val [{min_val_ts:.1f}..{max_val_ts:.1f}] < t_test >= {min_test_ts:.1f}."
)
),
),
LeakageAuditFinding(
check_name="preprocessing_leakage",
leaked=prep_leaked,
severity="CRITICAL" if prep_leaked else "INFO",
overlap_count=len(test_ids) if prep_leaked else 0,
details=(
"Scaler/encoder fitted on full dataset before splitting (test stats leaked)."
if prep_leaked
else "All scalers/encoders fitted exclusively on training split."
),
),
]
leakage_free = all(not f.leaked for f in findings)
return LeakageAuditReport(
scenario_name=scenario_name,
n_train=len(train_ids),
n_val=len(val_ids),
n_test=len(test_ids),
findings=findings,
leakage_free=leakage_free,
eval_accuracy=round(eval_accuracy, 4),
eval_roc_auc=round(eval_roc_auc, 4),
)
def _compute_roc_auc(y_true: NDArray[np.int64], y_prob: NDArray[np.float64]) -> float:
"""Exact rank-based ROC-AUC in pure NumPy without external ML dependencies."""
pos_mask = y_true == 1
neg_mask = y_true == 0
n_pos = int(np.sum(pos_mask))
n_neg = int(np.sum(neg_mask))
if n_pos == 0 or n_neg == 0:
return 0.5
pos_scores = y_prob[pos_mask]
neg_scores = y_prob[neg_mask]
diff = pos_scores[:, None] - neg_scores[None, :]
auc = (float(np.sum(diff > 0.0)) + 0.5 * float(np.sum(diff == 0.0))) / float(n_pos * n_neg)
return float(auc)
def _fit_and_eval_linear_model(
x_train: NDArray[np.float64],
y_train: NDArray[np.int64],
x_test: NDArray[np.float64],
y_test: NDArray[np.int64],
l2_reg: float = 5.0,
) -> tuple[float, float]:
"""Fit deterministic Ridge binary classifier in pure NumPy and return (accuracy, roc_auc)."""
n_tr, d = x_train.shape
x_aug_tr = np.hstack([x_train, np.ones((n_tr, 1), dtype=np.float64)])
x_aug_te = np.hstack([x_test, np.ones((x_test.shape[0], 1), dtype=np.float64)])
reg_mat = np.eye(d + 1, dtype=np.float64) * l2_reg
reg_mat[-1, -1] = 1e-6
y_signed = 2.0 * y_train.astype(np.float64) - 1.0
w = np.linalg.solve(x_aug_tr.T @ x_aug_tr + reg_mat, x_aug_tr.T @ y_signed)
logits = x_aug_te @ w
probs = 1.0 / (1.0 + np.exp(-np.clip(logits, -20.0, 20.0)))
preds = (logits >= 0.0).astype(np.int64)
acc = float(np.mean(preds == y_test))
auc = _compute_roc_auc(y_test, probs)
return acc, auc
def run_exp3_leakage_split_audit(seed: int = 42) -> dict[str, Any]:
"""Compare leaked (random split + global scaler + ID dup) vs clean chronological group split."""
rng = np.random.default_rng(seed)
n_groups = 120
steps_per_group = 8 # 960 longitudinal observations
n_total = n_groups * steps_per_group
n_features = 14
sample_ids: list[str] = []
group_ids: list[str] = []
timestamps: list[float] = []
x_rows = np.zeros((n_total, n_features), dtype=np.float64)
y_labels = np.zeros(n_total, dtype=np.int64)
# Group latent signature + subtle true physical features + temporal drift
group_signatures = rng.normal(0.0, 2.0, size=(n_groups, 4))
group_bias_y = rng.normal(0.0, 1.8, size=n_groups)
row_idx = 0
for g_idx in range(n_groups):
for t_step in range(steps_per_group):
sample_ids.append(f"sample_{g_idx:03d}_{t_step}")
group_ids.append(f"patient_{g_idx:03d}")
ts = float(t_step * 10) + 0.01 * float(g_idx)
timestamps.append(ts)
true_signal = rng.normal(0.0, 1.0, size=4)
noise_feats = rng.normal(0.0, 1.0, size=4)
time_regime = float(t_step) / float(steps_per_group - 1)
x_rows[row_idx, :4] = true_signal
x_rows[row_idx, 4:8] = group_signatures[g_idx] + rng.normal(0.0, 0.15, size=4)
x_rows[row_idx, 8:10] = np.array([time_regime * 1.5, -time_regime * 1.2]) + rng.normal(
0.0, 0.25, size=2
)
x_rows[row_idx, 10:] = noise_feats
# True signal contributes moderate predictive power (~74% clean ceiling),
# while entity-level susceptibility + late-period shift create leakage inflation.
logit = (
0.70 * true_signal[0]
- 0.55 * true_signal[1]
+ 0.35 * true_signal[2]
+ 1.60 * group_bias_y[g_idx]
+ (1.40 if t_step >= 6 else -0.35)
+ rng.normal(0.0, 0.50)
)
x_rows[row_idx, 4] += 1.25 * group_bias_y[g_idx]
y_labels[row_idx] = 1 if logit >= 0.0 else 0
row_idx += 1
# --- 1. LEAKED PIPELINE: Global scaler + random split + target encoding + duplicate rows ---
global_mean = np.mean(x_rows, axis=0)
global_std = np.maximum(np.std(x_rows, axis=0), 1e-6)
x_global_scaled = (x_rows - global_mean) / global_std
group_mean_y = np.zeros(n_total, dtype=np.float64)
for g_idx in range(n_groups):
mask = np.array([g == f"patient_{g_idx:03d}" for g in group_ids], dtype=bool)
group_mean_y[mask] = float(np.mean(y_labels[mask]))
x_leaked = np.column_stack([x_global_scaled, group_mean_y])
perm = rng.permutation(n_total)
n_tr_l = int(0.65 * n_total)
n_va_l = int(0.15 * n_total)
tr_idx_l = perm[:n_tr_l]
va_idx_l = perm[n_tr_l : n_tr_l + n_va_l]
te_idx_l = perm[n_tr_l + n_va_l :]
dup_ids = tr_idx_l[:24]
te_idx_l = np.concatenate([te_idx_l, dup_ids])
leaked_acc, leaked_auc = _fit_and_eval_linear_model(
x_leaked[tr_idx_l],
y_labels[tr_idx_l],
x_leaked[te_idx_l],
y_labels[te_idx_l],
l2_reg=2.0,
)
leaked_report = audit_split_and_preprocessing_leakage(
scenario_name="Leaked Naive Random Split + Global Scaler",
train_ids=[sample_ids[i] for i in tr_idx_l],
val_ids=[sample_ids[i] for i in va_idx_l],
test_ids=[sample_ids[i] for i in te_idx_l],
train_groups=[group_ids[i] for i in tr_idx_l],
val_groups=[group_ids[i] for i in va_idx_l],
test_groups=[group_ids[i] for i in te_idx_l],
train_timestamps=[timestamps[i] for i in tr_idx_l],
val_timestamps=[timestamps[i] for i in va_idx_l],
test_timestamps=[timestamps[i] for i in te_idx_l],
scaler_fitted_on="full_dataset",
eval_accuracy=leaked_acc,
eval_roc_auc=leaked_auc,
)
# --- 2. CLEAN PIPELINE: Disjoint patient groups + strict chronological split + train-only fit ---
group_perm = rng.permutation(n_groups)
tr_groups = set(group_perm[:72])
va_groups = set(group_perm[72:90])
te_groups = set(group_perm[90:])
tr_idx_c = np.array(
[
i
for i in range(n_total)
if (i // steps_per_group) in tr_groups and (i % steps_per_group) <= 4
],
dtype=np.int64,
)
va_idx_c = np.array(
[
i
for i in range(n_total)
if (i // steps_per_group) in va_groups and (i % steps_per_group) == 5
],
dtype=np.int64,
)
te_idx_c = np.array(
[
i
for i in range(n_total)
if (i // steps_per_group) in te_groups and (i % steps_per_group) >= 6
],
dtype=np.int64,
)
tr_mean = np.mean(x_rows[tr_idx_c], axis=0)
tr_std = np.maximum(np.std(x_rows[tr_idx_c], axis=0), 1e-6)
x_tr_clean = (x_rows[tr_idx_c] - tr_mean) / tr_std
x_te_clean = (x_rows[te_idx_c] - tr_mean) / tr_std
clean_acc, clean_auc = _fit_and_eval_linear_model(
x_tr_clean,
y_labels[tr_idx_c],
x_te_clean,
y_labels[te_idx_c],
l2_reg=8.0,
)
clean_report = audit_split_and_preprocessing_leakage(
scenario_name="Clean Chronological Group-Disjoint Split",
train_ids=[sample_ids[i] for i in tr_idx_c],
val_ids=[sample_ids[i] for i in va_idx_c],
test_ids=[sample_ids[i] for i in te_idx_c],
train_groups=[group_ids[i] for i in tr_idx_c],
val_groups=[group_ids[i] for i in va_idx_c],
test_groups=[group_ids[i] for i in te_idx_c],
train_timestamps=[timestamps[i] for i in tr_idx_c],
val_timestamps=[timestamps[i] for i in va_idx_c],
test_timestamps=[timestamps[i] for i in te_idx_c],
scaler_fitted_on="train_only",
eval_accuracy=clean_acc,
eval_roc_auc=clean_auc,
)
return {
"leaked_audit": leaked_report.model_dump(),
"clean_audit": clean_report.model_dump(),
"accuracy_inflation_pp": round((leaked_acc - clean_acc) * 100.0, 2),
"roc_auc_inflation": round(leaked_auc - clean_auc, 4),
}
# ---------------------------------------------------------------------------
# Student-t Power / MDE Solver, Cloud GPU Budget Planner & Rebuttal Gate
# ---------------------------------------------------------------------------
def _student_t_critical(df: int, alpha: float) -> float:
"""Find exact two-sided Student-t critical value t_{1-alpha/2, df} via bisection."""
scales, weights = chi_mixture_grid(df=df, n_points=320)
inv_sqrt2 = 1.0 / math.sqrt(2.0)
def two_sided_tail(t_val: float) -> float:
probs = np.array([math.erfc(float(t_val * s * inv_sqrt2)) for s in scales], dtype=np.float64)
return float(np.dot(probs, weights))
lo, hi = 0.0, 60.0
for _ in range(44):
mid = 0.5 * (lo + hi)
if two_sided_tail(mid) > alpha:
lo = mid
else:
hi = mid
return 0.5 * (lo + hi)
def compute_paired_t_power(
n_seeds: int,
effect_size_delta: float,
seed_std: float,
alpha: float = 0.05,
) -> float:
"""Compute exact two-sided paired noncentral Student-t statistical power."""
if n_seeds < 2:
raise ValueError("n_seeds must be >= 2")
if seed_std <= 0.0:
raise ValueError("seed_std must be > 0")
if not (0.0 < alpha < 1.0):
raise ValueError("alpha must lie in (0, 1)")
df = n_seeds - 1
t_crit = _student_t_critical(df=df, alpha=alpha)
ncp = abs(effect_size_delta) * math.sqrt(float(n_seeds)) / seed_std
scales, weights = chi_mixture_grid(df=df, n_points=320)
inv_sqrt2 = 1.0 / math.sqrt(2.0)
# Power = E_V[ Phi(ncp - t_crit * scale) + Phi(-ncp - t_crit * scale) ]
# where Phi(z) = 0.5 * erfc(-z / sqrt(2))
upper_args = (ncp - t_crit * scales) * inv_sqrt2
lower_args = (-ncp - t_crit * scales) * inv_sqrt2
probs = np.array(
[
0.5 * math.erfc(-float(u)) + 0.5 * math.erfc(-float(l_arg))
for u, l_arg in zip(upper_args, lower_args, strict=True)
],
dtype=np.float64,
)
return float(np.clip(np.dot(probs, weights), 0.0, 1.0))
def estimate_required_seeds(
effect_size_delta: float,
seed_std: float,
alpha: float = 0.05,
target_power: float = 0.80,
max_seeds: int = 250,
) -> tuple[int, float]:
"""Find minimum integer seed count n* achieving target statistical power."""
if effect_size_delta <= 0.0:
raise ValueError("effect_size_delta must be > 0")
if not (0.5 < target_power < 1.0):
raise ValueError("target_power must lie in (0.5, 1.0)")
for n in range(2, max_seeds + 1):
pwr = compute_paired_t_power(
n_seeds=n,
effect_size_delta=effect_size_delta,
seed_std=seed_std,
alpha=alpha,
)
if pwr >= target_power:
return n, pwr
return max_seeds, compute_paired_t_power(
n_seeds=max_seeds,
effect_size_delta=effect_size_delta,
seed_std=seed_std,
alpha=alpha,
)
def solve_minimum_detectable_effect(
n_seeds: int,
seed_std: float,
alpha: float = 0.05,
target_power: float = 0.80,
) -> float:
"""Solve Minimum Detectable Effect (MDE) given fixed seed budget n_seeds and seed_std."""
if n_seeds < 2:
raise ValueError("n_seeds must be >= 2")
lo, hi = 1e-4, 15.0 * seed_std
for _ in range(40):
mid = 0.5 * (lo + hi)
pwr = compute_paired_t_power(
n_seeds=n_seeds,
effect_size_delta=mid,
seed_std=seed_std,
alpha=alpha,
)
if pwr >= target_power:
hi = mid
else:
lo = mid
return float(hi)
def plan_compute_budget(
tier_id: str,
effect_size_delta: float,
seed_std: float,
n_methods_and_ablations: int = 6,
hp_trials_per_method: int = 4,
hours_per_run: float = 1.2,
alpha: float = 0.05,
target_power: float = 0.80,
budget_cap_usd: float = 150.0,
) -> PowerBudgetPlan:
"""Jointly compute statistical seed requirement n*, GPU-hours, and USD budget feasibility."""
if tier_id not in GPU_COMPUTE_CATALOG:
raise ValueError(f"Unknown GPU tier {tier_id!r}")
tier = GPU_COMPUTE_CATALOG[tier_id]
n_req, achieved_pwr = estimate_required_seeds(
effect_size_delta=effect_size_delta,
seed_std=seed_std,
alpha=alpha,
target_power=target_power,
)
mde_at_n = solve_minimum_detectable_effect(
n_seeds=n_req,
seed_std=seed_std,
alpha=alpha,
target_power=target_power,
)
# Full multi-seed runs for each method/ablation + single-seed equal-budget HP tuning trials
total_runs = n_methods_and_ablations * (n_req + hp_trials_per_method)
raw_hours = float(total_runs) * hours_per_run
effective_hours = raw_hours * tier.preemption_overhead_factor * tier.checkpoint_overhead_factor
total_cost = effective_hours * tier.hourly_usd
return PowerBudgetPlan(
tier_id=tier.tier_id,
tier_label=tier.label,
effect_size_delta=round(effect_size_delta, 4),
seed_std=round(seed_std, 4),
alpha=alpha,
target_power=target_power,
required_seeds_n=n_req,
achieved_power=round(achieved_pwr, 4),
minimum_detectable_effect=round(mde_at_n, 4),
n_methods_and_ablations=n_methods_and_ablations,
hp_trials_per_method=hp_trials_per_method,
hours_per_run=hours_per_run,
total_runs=total_runs,
raw_gpu_hours=round(raw_hours, 2),
effective_gpu_hours=round(effective_hours, 2),
total_cost_usd=round(total_cost, 2),
budget_cap_usd=budget_cap_usd,
fits_budget=(total_cost <= budget_cap_usd),
)
def evaluate_reproducibility_gate(
checklist: ReproducibilityChecklistInput,
) -> ReproducibilityGateReport:
"""Score submission artifact against 8 A*/Q1 reproducibility and rebuttal gates."""
checks: list[tuple[str, bool]] = [
("fixed_seeds_logged", checklist.fixed_seeds_logged),
("confidence_intervals_reported", checklist.confidence_intervals_reported),
("multiple_testing_corrected", checklist.multiple_testing_corrected),
("equal_baseline_tuning_budget", checklist.equal_baseline_tuning_budget),
("single_factor_ablations_complete", checklist.single_factor_ablations_complete),
("leakage_audit_passed", checklist.leakage_audit_passed),
("compute_hours_and_hardware_disclosed", checklist.compute_hours_and_hardware_disclosed),
(
"limitations_and_negative_results_included",
checklist.limitations_and_negative_results_included,
),
]
passed = [name for name, ok in checks if ok]
failed = [name for name, ok in checks if not ok]
score = len(passed)
if score == 8:
readiness: Literal["ACCEPT_READY", "MINOR_REVISION", "REJECT_RISK"] = "ACCEPT_READY"
rec = (
"All 8 A*/Q1 reproducibility and statistical rigor gates satisfied; "
"ready for camera-ready or rebuttal evidence submission."
)
elif score >= 6:
readiness = "MINOR_REVISION"
rec = f"Address remaining {len(failed)} gap(s) ({', '.join(failed)}) before camera-ready."
else:
readiness = "REJECT_RISK"
rec = (
f"High desk/peer rejection risk ({score}/8). Resolve critical gaps: "
f"{', '.join(failed)}."
)
return ReproducibilityGateReport(
submission_name=checklist.submission_name,
artifact_score=score,
passed_checks=passed,
failed_checks=failed,
rebuttal_readiness=readiness,
recommendation=rec,
)
def run_exp4_compute_budget_and_repro_audit() -> dict[str, Any]:
"""Run Exp 4: Seed power vs MDE sweep, Colab vs vast.ai cost matrix & reproducibility gate."""
# Power curve at n=3, 5, 10, 15, 20 for delta=2.45pp, seed_std=1.80pp
power_sweep: list[dict[str, float | int]] = []
for n_val in (3, 5, 10, 15, 20):
pwr = compute_paired_t_power(n_seeds=n_val, effect_size_delta=2.45, seed_std=1.80)
mde = solve_minimum_detectable_effect(n_seeds=n_val, seed_std=1.80)
power_sweep.append(
{
"n_seeds": n_val,
"power_at_245pp": round(pwr, 4),
"mde_80pct_power_pp": round(mde, 4),
}
)
# Compare 5 cloud GPU tiers on the identical 6-variant x (n* + 4 HP) research matrix
tier_plans = [
plan_compute_budget(
tier_id=tid,
effect_size_delta=2.45,
seed_std=1.80,
n_methods_and_ablations=6,
hp_trials_per_method=4,
hours_per_run=1.5,
budget_cap_usd=150.0,
).model_dump()
for tid in (
"colab_free_t4",
"colab_pro_l4",
"vast_rtx_4090_spot",
"vast_a100_80gb",
"ondemand_a100_80gb",
)
]
draft_gate = evaluate_reproducibility_gate(
ReproducibilityChecklistInput(
submission_name="Initial Draft (n=3 seeds, Confounded, Leaked)",
fixed_seeds_logged=True,
confidence_intervals_reported=False,
multiple_testing_corrected=False,
equal_baseline_tuning_budget=False,
single_factor_ablations_complete=False,
leakage_audit_passed=False,
compute_hours_and_hardware_disclosed=True,
limitations_and_negative_results_included=False,
)
)
final_gate = evaluate_reproducibility_gate(
ReproducibilityChecklistInput(
submission_name="FSDS Capstone Camera-Ready (n=10 seeds, Audited)",
fixed_seeds_logged=True,
confidence_intervals_reported=True,
multiple_testing_corrected=True,
equal_baseline_tuning_budget=True,
single_factor_ablations_complete=True,
leakage_audit_passed=True,
compute_hours_and_hardware_disclosed=True,
limitations_and_negative_results_included=True,
)
)
return {
"power_sweep": power_sweep,
"tier_plans": tier_plans,
"draft_repro_gate": draft_gate.model_dump(),
"final_repro_gate": final_gate.model_dump(),
}
# ---------------------------------------------------------------------------
# Full End-to-End Orchestrator with Bounded OpenTelemetry Telemetry
# ---------------------------------------------------------------------------
def run_full_research_methodology_benchmark(
seed: int = 42,
quick: bool = False,
) -> dict[str, Any]:
"""Run all 4 research methodology experiments under 5 bounded OpenTelemetry spans."""
provider, exporter, tracer = create_in_memory_otel_tracer(
instrumentation_name="research_methodology_lab",
max_spans=128,
)
n_resamples = 5000
with tracer.start_as_current_span("stats.multiseed_eval") as span1:
exp1_full = run_exp1_multiseed_and_fwer(
seed=seed,
n_resamples=n_resamples,
quick=quick,
)
span1.set_attribute("exp1.n10_diff_iqm", exp1_full["rigorous_n10"]["diff_iqm"])
span1.set_attribute("exp1.n3_p_value", exp1_full["underpowered_n3"]["permutation_p_value"])
span1.set_attribute("exp1.n10_p_value", exp1_full["rigorous_n10"]["permutation_p_value"])
with tracer.start_as_current_span("stats.multiple_testing_fwer") as span2:
fwer = exp1_full["multiple_testing_m20"]
span2.set_attribute("exp1b.m_comparisons", fwer["m_comparisons"])
span2.set_attribute("exp1b.empirical_null_fwer", fwer["empirical_null_fwer"])
span2.set_attribute("exp1b.holm_null_fwer", fwer["holm_empirical_null_fwer"])
with tracer.start_as_current_span("ablation.confounder_audit") as span3:
exp2 = run_exp2_ablation_confounder_audit()
span3.set_attribute("exp2.flawed_passed", exp2["flawed_audit"]["audit_passed"])
span3.set_attribute("exp2.clean_passed", exp2["clean_audit"]["audit_passed"])
span3.set_attribute("exp2.tuning_inflation_pp", exp2["tuning_bias_inflation_pp"])
with tracer.start_as_current_span("leakage.split_audit") as span4:
exp3 = run_exp3_leakage_split_audit(seed=seed)
span4.set_attribute("exp3.leaked_acc", exp3["leaked_audit"]["eval_accuracy"])
span4.set_attribute("exp3.clean_acc", exp3["clean_audit"]["eval_accuracy"])
span4.set_attribute("exp3.inflation_pp", exp3["accuracy_inflation_pp"])
with tracer.start_as_current_span("budget.power_and_cost") as span5:
exp4 = run_exp4_compute_budget_and_repro_audit()
vast_plan = next(
p for p in exp4["tier_plans"] if p["tier_id"] == "vast_rtx_4090_spot"
)
span5.set_attribute("exp4.required_seeds_n", vast_plan["required_seeds_n"])
span5.set_attribute("exp4.vast_4090_cost_usd", vast_plan["total_cost_usd"])
span5.set_attribute(
"exp4.final_repro_score",
exp4["final_repro_gate"]["artifact_score"],
)
provider.force_flush()
finished = exporter.get_finished_spans()
span_names = [s.name for s in finished]
provider.shutdown()
return {
"seed": seed,
"quick_mode": quick,
"exp1_multiseed_and_fwer": exp1_full,
"exp2_ablation_confounders": exp2,
"exp3_leakage_audit": exp3,
"exp4_budget_and_repro": exp4,
"otel_telemetry": {
"total_spans_recorded": len(finished),
"distinct_span_names": span_names,
"bounded_max_spans": 128,
},
}
def main() -> None:
"""CLI entrypoint printing concise research methodology benchmark summary."""
parser = argparse.ArgumentParser(
description="Run WB-Ch30 Research Methodology & Paper Capstone benchmark."
)
parser.add_argument("--seed", type=int, default=42)
parser.add_argument("--quick", action="store_true")
args = parser.parse_args()
summary = run_full_research_methodology_benchmark(seed=args.seed, quick=args.quick)
print(json.dumps(summary["otel_telemetry"], indent=2))
"""CLI Benchmark & Artifact Generator for WB-Ch30 (T1-P7-U03: Research Methodology)."""
from __future__ import annotations
import argparse
import json
import sys
from pathlib import Path
from typing import Any
_LAB_ROOT = Path(__file__).resolve().parents[1]
_SRC_DIR = str(_LAB_ROOT / "src")
if _SRC_DIR not in sys.path:
sys.path.insert(0, _SRC_DIR)
from research_methodology_lab.reproducibility_and_budget import ( # noqa: E402
run_full_research_methodology_benchmark,
)
def run_wb_ch30_benchmark(seed: int = 42, quick: bool = False) -> dict[str, Any]:
"""Execute WB-Ch30 benchmark and assemble 6 KPIs, 4 bar charts, and 4 workbench tables."""
bench = run_full_research_methodology_benchmark(seed=seed, quick=quick)
exp1 = bench["exp1_multiseed_and_fwer"]
exp2 = bench["exp2_ablation_confounders"]
exp3 = bench["exp3_leakage_audit"]
exp4 = bench["exp4_budget_and_repro"]
otel = bench["otel_telemetry"]
n3 = exp1["underpowered_n3"]
n10 = exp1["rigorous_n10"]
out = exp1["outlier_iqm_vs_mean"]
fwer = exp1["multiple_testing_m20"]
flawed_ab = exp2["flawed_audit"]
clean_ab = exp2["clean_audit"]
leaked_sp = exp3["leaked_audit"]
clean_sp = exp3["clean_audit"]
vast_4090 = next(p for p in exp4["tier_plans"] if p["tier_id"] == "vast_rtx_4090_spot")
ondemand_a100 = next(p for p in exp4["tier_plans"] if p["tier_id"] == "ondemand_a100_80gb")
final_gate = exp4["final_repro_gate"]
workbench_panels: dict[str, Any] = {
"kpis": [
{
"id": "kpi_multiseed_iqm_gain",
"label": "n=10 Seeds IQM Gain & Permutation p",
"value": f"+{n10['diff_iqm']:.2f}pp",
"unit": (
f"(95% CI [{n10['ci_low']:.2f}, {n10['ci_high']:.2f}], "
f"p={n10['permutation_p_value']:.4f} vs n=3 p={n3['permutation_p_value']:.4f})"
),
"status": "ok",
"detail": (
f"n=3 underpowered (p={n3['permutation_p_value']:.4f}, not significant) "
f"vs n=10 Cohen's d={n10['cohens_d']:.2f}, "
f"P(X>Y)={n10['prob_improvement']:.3f}."
),
},
{
"id": "kpi_fwer_p_hacking_control",
"label": "m=20 Multiple-Testing Null FWER",
"value": (
f"{fwer['empirical_null_fwer'] * 100:.1f}% -> "
f"{fwer['holm_empirical_null_fwer'] * 100:.1f}%"
),
"unit": (
f"(Theory {fwer['theoretical_null_fwer'] * 100:.2f}% | "
f"BH Null FDR {fwer['bh_empirical_null_fdr'] * 100:.1f}%)"
),
"status": "ok",
"detail": (
f"Across {fwer['n_null_families']} null studies (m=20), uncorrected FWER "
f"hits {fwer['empirical_null_fwer'] * 100:.1f}%; Holm-Bonferroni restores "
f"FWER={fwer['holm_empirical_null_fwer'] * 100:.1f}%."
),
},
{
"id": "kpi_iqm_outlier_resilience",
"label": "IQM vs Mean Under 1-Seed Crash",
"value": f"IQM +{out['diff_iqm']:.2f}pp",
"unit": f"(vs Arithmetic Mean {out['diff_mean']:+.2f}pp)",
"status": "ok",
"detail": (
"A single collapsed seed (-38pp) flips arithmetic mean gain negative "
f"({out['diff_mean']:+.2f}pp), while 25%-trimmed IQM stays at "
f"+{out['diff_iqm']:.2f}pp."
),
},
{
"id": "kpi_ablation_confounder_gate",
"label": "Ablation Confounder & Tuning Audit",
"value": f"0 vs {len(flawed_ab['confounders'])} flaws",
"unit": (
f"(Fair +{exp2['fair_true_gain_pp']:.2f}pp vs "
f"Inflated +{exp2['flawed_claimed_gain_pp']:.2f}pp)"
),
"status": "ok",
"detail": (
f"Detects multi-factor jump + 15x tuning bias "
f"(+{exp2['tuning_bias_inflation_pp']:.2f}pp phantom gain); "
f"clean 2x2 attributes Arch +{clean_ab['main_effects']['arch_gate']:.2f}pp."
),
},
{
"id": "kpi_leakage_audit_inflation",
"label": "Split & Scaler Leakage Inflation",
"value": f"+{exp3['accuracy_inflation_pp']:.2f}pp mirage",
"unit": (
f"(Leaked {leaked_sp['eval_accuracy'] * 100:.1f}% vs "
f"Clean {clean_sp['eval_accuracy'] * 100:.1f}%)"
),
"status": "ok",
"detail": (
f"Random + group + temporal + global-scaler leakage inflates ROC-AUC "
f"from {clean_sp['eval_roc_auc']:.3f} to {leaked_sp['eval_roc_auc']:.3f}."
),
},
{
"id": "kpi_compute_budget_and_repro",
"label": "vast.ai RTX 4090 Budget & OTel Gate",
"value": f"${vast_4090['total_cost_usd']:.2f}",
"unit": (
f"(n*={vast_4090['required_seeds_n']} seeds, "
f"{vast_4090['effective_gpu_hours']:.1f}h | "
f"{final_gate['artifact_score']}/8 Gate | "
f"{otel['total_spans_recorded']} spans)"
),
"status": "ok",
"detail": (
f"Fits $150 cap vs On-Demand A100 ${ondemand_a100['total_cost_usd']:.2f}; "
f"BoundedInMemorySpanExporter captured {otel['total_spans_recorded']} spans."
),
},
],
"bars": [
{
"id": "bar_multiseed_iqm_vs_mean",
"title": "Exp 1A: Mean vs rliable IQM Gain (pp) Across n=3, n=10 & 1-Outlier Crash",
"metric_label": "Gain vs Baseline (pp)",
"items": [
{
"label": "n3_iqm",
"value": round(n3["diff_iqm"], 3),
"display": (
f"n=3 IQM: +{n3['diff_iqm']:.2f}pp "
f"(p={n3['permutation_p_value']:.3f} NS)"
),
"css_class": "is-mid",
},
{
"label": "n10_mean",
"value": round(n10["diff_mean"], 3),
"display": f"n=10 Mean: +{n10['diff_mean']:.2f}pp",
"css_class": "is-fast",
},
{
"label": "n10_iqm",
"value": round(n10["diff_iqm"], 3),
"display": (
f"n=10 IQM: +{n10['diff_iqm']:.2f}pp "
f"(p={n10['permutation_p_value']:.4f})"
),
"css_class": "is-fast",
},
{
"label": "outlier_mean",
"value": round(out["diff_mean"], 3),
"display": f"1-Crash Mean: {out['diff_mean']:+.2f}pp (CORRUPTED)",
"css_class": "is-slow",
},
{
"label": "outlier_iqm",
"value": round(out["diff_iqm"], 3),
"display": f"1-Crash IQM: +{out['diff_iqm']:.2f}pp (RESILIENT)",
"css_class": "is-fast",
},
],
},
{
"id": "bar_fwer_multiple_testing",
"title": "Exp 1B: m=20 Simultaneous Null Tests Error Rate (%)",
"metric_label": "False Discovery / FWER (%)",
"items": [
{
"label": "theoretical_fwer",
"value": round(fwer["theoretical_null_fwer"] * 100.0, 2),
"display": (
f"Theory 1-(1-0.05)^20: "
f"{fwer['theoretical_null_fwer'] * 100:.2f}%"
),
"css_class": "is-slow",
},
{
"label": "empirical_uncorrected_fwer",
"value": round(fwer["empirical_null_fwer"] * 100.0, 2),
"display": (
f"Uncorrected Empirical FWER: "
f"{fwer['empirical_null_fwer'] * 100:.1f}%"
),
"css_class": "is-slow",
},
{
"label": "holm_bonferroni_fwer",
"value": round(fwer["holm_empirical_null_fwer"] * 100.0, 2),
"display": (
f"Holm-Bonferroni FWER: "
f"{fwer['holm_empirical_null_fwer'] * 100:.1f}%"
),
"css_class": "is-fast",
},
{
"label": "bh_fdr_null",
"value": round(fwer["bh_empirical_null_fdr"] * 100.0, 2),
"display": (
f"Benjamini-Hochberg Null FDR: "
f"{fwer['bh_empirical_null_fdr'] * 100:.1f}%"
),
"css_class": "is-fast",
},
],
},
{
"id": "bar_leakage_eval_inflation",
"title": "Exp 3: Leaked Random/Global-Scaler vs Clean Group-Chronological Score (%)",
"metric_label": "Accuracy / ROC-AUC (%)",
"items": [
{
"label": "leaked_acc",
"value": round(leaked_sp["eval_accuracy"] * 100.0, 2),
"display": f"Leaked Split Accuracy: {leaked_sp['eval_accuracy'] * 100:.1f}%",
"css_class": "is-slow",
},
{
"label": "clean_acc",
"value": round(clean_sp["eval_accuracy"] * 100.0, 2),
"display": f"Clean Split Accuracy: {clean_sp['eval_accuracy'] * 100:.1f}%",
"css_class": "is-fast",
},
{
"label": "leaked_auc",
"value": round(leaked_sp["eval_roc_auc"] * 100.0, 2),
"display": f"Leaked Split ROC-AUC: {leaked_sp['eval_roc_auc'] * 100:.1f}%",
"css_class": "is-slow",
},
{
"label": "clean_auc",
"value": round(clean_sp["eval_roc_auc"] * 100.0, 2),
"display": f"Clean Split ROC-AUC: {clean_sp['eval_roc_auc'] * 100:.1f}%",
"css_class": "is-fast",
},
],
},
{
"id": "bar_cloud_gpu_budget",
"title": "Exp 4: Full Study Cloud Cost (USD) at Power >= 80% (n*=7..10 Seeds)",
"metric_label": "Total Cost (USD)",
"items": [
{
"label": p["tier_id"],
"value": p["total_cost_usd"],
"display": (
f"{p['tier_label']}: ${p['total_cost_usd']:.2f} "
f"({'FITS $150' if p['fits_budget'] else 'OVER CAP'})"
),
"css_class": (
"is-fast"
if p["fits_budget"] and p["tier_id"] == "vast_rtx_4090_spot"
else ("is-mid" if p["fits_budget"] else "is-slow")
),
}
for p in exp4["tier_plans"]
],
},
],
"tables": [
{
"id": "tbl_exp1_multiseed_rliable",
"title": "Experiment 1A: Multi-Seed Power (n=3 vs n=10) & rliable Outlier Resilience",
"columns": [
"Evaluation Regime",
"Mean Diff / IQM Diff",
"95% Bootstrap CI",
"Permutation p & Cohen d",
],
"rows": [
[
r["method_name"],
f"{r['diff_mean']:+.2f}pp / {r['diff_iqm']:+.2f}pp",
f"[{r['ci_low']:+.2f}, {r['ci_high']:+.2f}]",
(
f"p={r['permutation_p_value']:.4f} | "
f"d={r['cohens_d']:.2f} | "
f"sig={r['is_significant_two_sided']} (imp={r['improved_lower_bound']})"
),
]
for r in (n3, n10, out)
],
},
{
"id": "tbl_exp1b_fwer_control",
"title": "Experiment 1B: Multiple-Testing Control Over m=20 Simultaneous Comparisons",
"columns": [
"Testing Procedure",
"Null FWER / FDR (1,000 studies)",
"Single Study Rejections (of 20)",
"False Positives (of 17 True Nulls)",
],
"rows": [
[
"Uncorrected (alpha = 0.05)",
(
f"FWER = {fwer['empirical_null_fwer'] * 100:.1f}% "
f"(Theory {fwer['theoretical_null_fwer'] * 100:.2f}%)"
),
f"{fwer['study_raw_rejections']} / {fwer['m_comparisons']}",
f"{fwer['study_raw_false_positives']} / {fwer['study_true_nulls']}",
],
[
"Holm-Bonferroni (FWER <= 0.05)",
f"FWER = {fwer['holm_empirical_null_fwer'] * 100:.1f}%",
f"{fwer['study_holm_rejections']} / {fwer['m_comparisons']}",
f"{fwer['study_holm_false_positives']} / {fwer['study_true_nulls']}",
],
[
"Benjamini-Hochberg (FDR <= 0.05)",
f"Null FDR = {fwer['bh_empirical_null_fdr'] * 100:.1f}%",
f"{fwer['study_bh_rejections']} / {fwer['m_comparisons']}",
f"{fwer['study_bh_false_positives']} / {fwer['study_true_nulls']}",
],
],
},
{
"id": "tbl_exp2_exp3_audits",
"title": "Experiments 2 & 3: Controlled Ablation Confounders & Split Leakage Audits",
"columns": [
"Audit Subject",
"Status & Critical Findings",
"Primary Metric Summary",
"Engineering / Attribution Takeaway",
],
"rows": [
[
flawed_ab["table_label"],
f"PASSED={flawed_ab['audit_passed']} ({len(flawed_ab['confounders'])} flaws)",
f"Claimed +{exp2['flawed_claimed_gain_pp']:.2f}pp (1 vs 15 trials)",
"Multi-factor jump + tuning asymmetry invalidates attribution",
],
[
clean_ab["table_label"],
f"PASSED={clean_ab['audit_passed']} (0 flaws, 8 vs 8 trials)",
(
f"Fair +{exp2['fair_true_gain_pp']:.2f}pp "
f"(Arch +{clean_ab['main_effects']['arch_gate']:.2f}pp)"
),
(
f"MixUp +{clean_ab['main_effects']['mixup_aug']:.2f}pp, "
f"CosineLR +{clean_ab['main_effects']['cosine_lr']:.2f}pp, "
f"Int +{clean_ab['interaction_effects']['arch_gate x mixup_aug']:.2f}pp"
),
],
[
leaked_sp["scenario_name"],
f"LEAKAGE_FREE={leaked_sp['leakage_free']} (4/4 vectors leaked)",
(
f"Acc {leaked_sp['eval_accuracy'] * 100:.1f}% | "
f"AUC {leaked_sp['eval_roc_auc']:.3f}"
),
(
f"+{exp3['accuracy_inflation_pp']:.2f}pp artificial mirage "
f"from ID/group/time/scaler leaks"
),
],
[
clean_sp["scenario_name"],
f"LEAKAGE_FREE={clean_sp['leakage_free']} (0 overlaps)",
(
f"Acc {clean_sp['eval_accuracy'] * 100:.1f}% | "
f"AUC {clean_sp['eval_roc_auc']:.3f}"
),
"Chronological group-disjoint split + train-only scaler",
],
],
},
{
"id": "tbl_exp4_gpu_budget_matrix",
"title": (
"Experiment 4: Power-Sized Cloud GPU Budget Matrix "
"(delta=2.45pp, std=1.80pp, Power>=80%)"
),
"columns": [
"Cloud / Notebook Tier",
"Hourly Rate & Preemption Factor",
"Required Seeds n* & Runs",
"Effective GPU-Hrs & Cost ($150 Cap)",
],
"rows": [
[
p["tier_label"],
(
f"${GPU_PRICE_MAP[p['tier_id']]:.2f}/hr "
f"({GPU_PREEMPT_MAP[p['tier_id']]:.2f}x)"
),
(
f"n*={p['required_seeds_n']} "
f"(pwr={p['achieved_power']:.3f}) | {p['total_runs']} runs"
),
(
f"{p['effective_gpu_hours']:.1f}h | "
f"${p['total_cost_usd']:.2f} (fits={p['fits_budget']})"
),
]
for p in exp4["tier_plans"]
],
},
],
}
return {**bench, "workbench_panels": workbench_panels}
GPU_PRICE_MAP: dict[str, float] = {
"colab_free_t4": 0.0,
"colab_pro_l4": 0.55,
"vast_rtx_4090_spot": 0.34,
"vast_a100_80gb": 1.15,
"ondemand_a100_80gb": 2.20,
}
GPU_PREEMPT_MAP: dict[str, float] = {
"colab_free_t4": 1.35 * 1.08,
"colab_pro_l4": 1.10 * 1.05,
"vast_rtx_4090_spot": 1.18 * 1.04,
"vast_a100_80gb": 1.07 * 1.03,
"ondemand_a100_80gb": 1.01 * 1.02,
}
def main() -> None:
parser = argparse.ArgumentParser(
description="Run WB-Ch30 Research Methodology & Paper Capstone benchmark."
)
parser.add_argument("--seed", type=int, default=42)
parser.add_argument("--quick", action="store_true")
parser.add_argument(
"--output",
type=Path,
default=_LAB_ROOT / "artifacts" / "ch30_wb30_results.json",
)
args = parser.parse_args()
result = run_wb_ch30_benchmark(seed=args.seed, quick=args.quick)
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(json.dumps(result, indent=2), encoding="utf-8")
print(f"Wrote WB-Ch30 artifact to {args.output}")
if __name__ == "__main__":
main()
"""Comprehensive automated test suite (20 tests + AST + Hypothesis + OTel) for WB-Ch30."""
from __future__ import annotations
import ast
import json
import math
import subprocess
import sys
from pathlib import Path
from typing import Any
import numpy as np
import pytest
from hypothesis import given, settings
from hypothesis import strategies as st
from pydantic import ValidationError
from research_methodology_lab.ablation_and_stats import (
AblationRunRow,
MultiSeedComparisonResult,
WilcoxonTestResult,
benjamini_hochberg_adjust,
cohens_d_paired,
compare_methods_multiseed,
create_in_memory_otel_tracer,
holm_bonferroni_adjust,
interquartile_mean,
optimality_gap,
paired_permutation_test,
probability_of_improvement,
run_exp1_multiseed_and_fwer,
run_exp2_ablation_confounder_audit,
simulate_multiple_testing_inflation,
stratified_bootstrap_ci,
wilcoxon_signed_rank_test,
)
from research_methodology_lab.reproducibility_and_budget import (
GPU_COMPUTE_CATALOG,
ReproducibilityChecklistInput,
audit_split_and_preprocessing_leakage,
compute_paired_t_power,
estimate_required_seeds,
evaluate_reproducibility_gate,
plan_compute_budget,
run_exp3_leakage_split_audit,
run_exp4_compute_budget_and_repro_audit,
run_full_research_methodology_benchmark,
solve_minimum_detectable_effect,
)
LAB_ROOT = Path(__file__).resolve().parents[1]
def test_01_ast_no_unsafe_deserializers_and_zero_type_ignore() -> None:
"""AST security gate: forbid unsafe deserializers/exec and type-suppression pragmas."""
forbidden_modules = {"pickle", "cPickle", "joblib", "cloudpickle", "dill", "shelve", "marshal"}
forbidden_calls = {"eval", "exec"}
forbidden_pragma = "type:" + " ignore"
checked = 0
for folder in ("src", "scripts", "tests"):
for py_file in sorted((LAB_ROOT / folder).rglob("*.py")):
text = py_file.read_text(encoding="utf-8")
assert forbidden_pragma not in text, f"Forbidden type suppression in {py_file}"
tree = ast.parse(text, filename=str(py_file))
checked += 1
for node in ast.walk(tree):
if isinstance(node, ast.Import):
for alias in node.names:
assert alias.name.split(".")[0] not in forbidden_modules, (
f"Forbidden import {alias.name} in {py_file}"
)
elif isinstance(node, ast.ImportFrom) and node.module is not None:
assert node.module.split(".")[0] not in forbidden_modules, (
f"Forbidden import-from {node.module} in {py_file}"
)
elif isinstance(node, ast.Call) and isinstance(node.func, ast.Name):
assert node.func.id not in forbidden_calls, (
f"Forbidden call {node.func.id} in {py_file}"
)
assert checked >= 4
def test_02_pydantic_v2_strict_schemas_extra_forbid() -> None:
"""Ensure Pydantic v2 schemas reject unknown fields via extra='forbid'."""
with pytest.raises(ValidationError):
AblationRunRow.model_validate(
{
"run_id": "bad_row",
"factors": {"a": True},
"tuning_trials": 4,
"metric_score": 80.0,
"unknown_extra_field": 123,
}
)
with pytest.raises(ValidationError):
ReproducibilityChecklistInput.model_validate(
{
"submission_name": "bad",
"fixed_seeds_logged": True,
"confidence_intervals_reported": True,
"multiple_testing_corrected": True,
"equal_baseline_tuning_budget": True,
"single_factor_ablations_complete": True,
"leakage_audit_passed": True,
"compute_hours_and_hardware_disclosed": True,
"limitations_and_negative_results_included": True,
"extra_flag": True,
}
)
def test_03_iqm_outlier_resistance_and_rliable_metrics() -> None:
"""Verify IQM trims top/bottom 25% outliers while mean shifts drastically."""
clean = [80.0, 80.5, 81.0, 81.2, 81.5, 81.8, 82.0, 82.3, 82.6, 83.0]
corrupted = [10.0, 80.5, 81.0, 81.2, 81.5, 81.8, 82.0, 82.3, 82.6, 150.0]
assert abs(interquartile_mean(clean) - interquartile_mean(corrupted)) < 1e-12
assert abs(np.mean(clean) - np.mean(corrupted)) > 0.2
assert abs(optimality_gap([90.0, 100.0, 105.0], threshold=100.0) - (10.0 / 3.0)) < 1e-9
assert probability_of_improvement([85.0, 86.0], [80.0, 81.0]) == 1.0
assert probability_of_improvement([80.0, 81.0], [80.0, 81.0]) == 0.5
def test_04_paired_permutation_symmetry_and_resamples_guard() -> None:
"""Verify paired permutation symmetry, p>0, and enforcement of n_resamples >= 5000."""
a = [81.5, 82.1, 83.4, 80.9, 84.2, 82.8, 83.0, 81.9, 82.7, 83.6]
b = [79.1, 80.0, 80.8, 79.5, 80.2, 79.9, 80.4, 79.3, 80.1, 80.3]
p_ab = paired_permutation_test(a, b, n_resamples=5000, seed=42, alternative="two-sided")
p_ba = paired_permutation_test(b, a, n_resamples=5000, seed=42, alternative="two-sided")
assert abs(p_ab - p_ba) < 1e-12
assert 0.0 < p_ab < 0.01
with pytest.raises(ValueError, match="5000"):
paired_permutation_test(a, b, n_resamples=1000)
with pytest.raises(ValueError, match="5000"):
stratified_bootstrap_ci(a, b, n_resamples=1000)
def test_05_paired_permutation_monotonicity_with_sample_size() -> None:
"""Increasing sample size n at fixed effect size and variance lowers permutation p-value."""
rng = np.random.default_rng(77)
base_large = rng.normal(80.0, 1.0, size=30)
meth_large = base_large + rng.normal(1.2, 1.4, size=30)
p_n4 = paired_permutation_test(meth_large[:4], base_large[:4], n_resamples=5000, seed=42)
p_n12 = paired_permutation_test(meth_large[:12], base_large[:12], n_resamples=5000, seed=42)
p_n30 = paired_permutation_test(meth_large, base_large, n_resamples=5000, seed=42)
assert p_n4 >= p_n12 >= p_n30
assert p_n30 < 0.01
def test_06_exp1a_n3_underpowered_vs_n10_and_outlier_resilience() -> None:
"""Confirm Exp 1A: n=3 fails significance, n=10 passes, 1-outlier breaks mean; Wilcoxon checks."""
exp1 = run_exp1_multiseed_and_fwer(seed=42, n_resamples=5000, quick=True)
n3 = MultiSeedComparisonResult.model_validate(exp1["underpowered_n3"])
n10 = MultiSeedComparisonResult.model_validate(exp1["rigorous_n10"])
out = MultiSeedComparisonResult.model_validate(exp1["outlier_iqm_vs_mean"])
w3 = WilcoxonTestResult.model_validate(exp1["wilcoxon_n3"])
w10 = WilcoxonTestResult.model_validate(exp1["wilcoxon_n10"])
w_out = WilcoxonTestResult.model_validate(exp1["wilcoxon_outlier"])
assert n3.is_significant_two_sided is False
assert n3.improved_lower_bound is False
assert n3.permutation_p_value > 0.20
assert n10.is_significant_two_sided is True
assert n10.improved_lower_bound is True
assert n10.diff_iqm > 2.0
assert n10.ci_low > 1.0
assert n10.permutation_p_value < 0.01
assert out.diff_mean < 0.0
assert abs(out.diff_iqm - n10.diff_iqm) < 1e-4
assert w3.method == "exact"
assert w3.p_value >= 0.25
assert w10.method == "exact"
assert w10.p_value < 0.01
assert w_out.w_minus > w10.w_minus
# Verify two-sided significance is cleanly decoupled from directional CI improvement
base_good = [80.0, 81.2, 79.8, 82.0, 80.5, 81.0, 80.9, 82.4, 79.9, 81.6]
degraded = [b - 4.0 for b in base_good]
degraded_cmp = compare_methods_multiseed(
method_name="DegradedModel",
baseline_name="Baseline",
method_scores=degraded,
baseline_scores=base_good,
n_resamples=5000,
seed=42,
)
assert degraded_cmp.ci_high < 0.0
assert degraded_cmp.is_significant_two_sided is True
assert degraded_cmp.improved_lower_bound is False
# Verify asymptotic branch & tie/zero handling in wilcoxon_signed_rank_test
asym_res = wilcoxon_signed_rank_test(
[10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0, 20.0, 21.0, 22.0, 23.0, 24.0, 25.0],
[10.0, 10.0, 11.0, 11.5, 12.5, 13.5, 14.5, 15.5, 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5],
)
assert asym_res.method == "asymptotic"
assert asym_res.n_nonzero == 15
assert asym_res.p_value < 0.01
def test_07_multiple_testing_fwer_inflation_and_holm_bh_containment() -> None:
"""Confirm m=20 null tests inflate FWER to ~64% while Holm/BH restore <= ~5% control."""
summary = simulate_multiple_testing_inflation(
m_comparisons=20,
n_null_families=1000,
n_seeds_per_exp=10,
alpha=0.05,
seed=42,
)
assert abs(summary.theoretical_null_fwer - 0.6415) < 1e-3
assert 0.58 <= summary.empirical_null_fwer <= 0.70
assert summary.holm_empirical_null_fwer <= 0.065
assert summary.bh_empirical_null_fdr <= 0.065
assert summary.study_holm_false_positives == 0
assert summary.study_raw_false_positives >= summary.study_holm_false_positives
def test_08_holm_and_bh_exact_step_adjustments() -> None:
"""Verify monotonicity and exact boundary formulas for Holm-Bonferroni and BH adjustments."""
raw = [0.001, 0.015, 0.04, 0.20]
holm = holm_bonferroni_adjust(raw)
bh = benjamini_hochberg_adjust(raw)
assert pytest.approx(holm, abs=1e-9) == [0.004, 0.045, 0.08, 0.20]
assert pytest.approx(bh, abs=1e-9) == [0.004, 0.03, 0.0533333333, 0.20]
for h_val, b_val, r_val in zip(holm, bh, raw, strict=True):
assert r_val <= b_val <= h_val <= 1.0
def test_09_exp2_ablation_confounder_and_tuning_asymmetry_detector() -> None:
"""Verify confounded multi-factor jump + tuning asymmetry fails while simulated 2x2 passes."""
exp2 = run_exp2_ablation_confounder_audit()
flawed = exp2["flawed_audit"]
clean = exp2["clean_audit"]
assert flawed["audit_passed"] is False
issue_types = {f["issue_type"] for f in flawed["confounders"]}
assert "confounded_multi_factor" in issue_types
assert "unfair_tuning_asymmetry" in issue_types
assert clean["audit_passed"] is True
assert clean["confounders"] == []
assert clean["tuning_asymmetry_detected"] is False
assert clean["main_effects"]["arch_gate"] > 1.5
assert clean["main_effects"]["mixup_aug"] > 0.8
assert abs(clean["main_effects"]["cosine_lr"]) < 0.8
assert clean["main_effects"]["arch_gate"] > clean["main_effects"]["mixup_aug"]
assert clean["interaction_effects"]["arch_gate x mixup_aug"] > 0.1
assert exp2["flawed_claimed_gain_pp"] > exp2["fair_true_gain_pp"]
assert exp2["tuning_bias_inflation_pp"] > 0.5
assert len(exp2["simulated_seed_scores"]["full_system"]) == 10
def test_10_latex_booktabs_table_exporter_and_tied_bolding() -> None:
"""Verify generated LaTeX uses booktabs and bolds statistically tied winners dynamically."""
exp2 = run_exp2_ablation_confounder_audit()
tex = str(exp2["latex_booktabs_table"])
for token in (
r"\begin{table}[t]",
r"\toprule",
r"\midrule",
r"\bottomrule",
r"\end{tabular}",
r"\pm",
r"\textbf{$",
"+ Arch Gate + MixUp (8 trials)",
"Full System (+ CosineLR, 8 trials)",
):
assert token in tex
assert "|" not in tex
def test_11_exp3_leakage_detection_and_score_inflation() -> None:
"""Verify all 4 leakage vectors are detected and inflate accuracy/AUC over clean split."""
exp3 = run_exp3_leakage_split_audit(seed=42)
leaked = exp3["leaked_audit"]
clean = exp3["clean_audit"]
assert leaked["leakage_free"] is False
assert all(f["leaked"] is True for f in leaked["findings"])
assert clean["leakage_free"] is True
assert all(f["leaked"] is False for f in clean["findings"])
assert exp3["accuracy_inflation_pp"] >= 12.0
assert exp3["roc_auc_inflation"] >= 0.05
def test_12_unit_leakage_auditor_individual_vectors() -> None:
"""Verify individual leakage checks trigger accurately when only one vector is violated."""
report = audit_split_and_preprocessing_leakage(
scenario_name="SingleGroupLeak",
train_ids=["a", "b"],
val_ids=["c"],
test_ids=["d"],
train_groups=["g1", "g2"],
val_groups=["g3"],
test_groups=["g2"], # g2 leaks!
train_timestamps=[1.0, 2.0],
val_timestamps=[3.0],
test_timestamps=[4.0],
scaler_fitted_on="train_only",
eval_accuracy=0.80,
eval_roc_auc=0.85,
)
assert report.leakage_free is False
by_name = {f.check_name: f for f in report.findings}
assert by_name["id_overlap"].leaked is False
assert by_name["group_leakage"].leaked is True
assert by_name["group_leakage"].overlap_count == 1
assert by_name["temporal_leakage"].leaked is False
assert by_name["preprocessing_leakage"].leaked is False
def test_13_student_t_power_and_cloud_gpu_budget_matrix() -> None:
"""Verify Student-t power curve, required seeds n*, and vast.ai vs On-Demand budget fit."""
exp4 = run_exp4_compute_budget_and_repro_audit()
sweep = {row["n_seeds"]: row for row in exp4["power_sweep"]}
assert sweep[3]["power_at_245pp"] < 0.40
assert sweep[10]["power_at_245pp"] > 0.90
assert sweep[3]["mde_80pct_power_pp"] > sweep[10]["mde_80pct_power_pp"]
vast = next(p for p in exp4["tier_plans"] if p["tier_id"] == "vast_rtx_4090_spot")
ondemand = next(p for p in exp4["tier_plans"] if p["tier_id"] == "ondemand_a100_80gb")
assert vast["required_seeds_n"] == 7
assert vast["fits_budget"] is True
assert ondemand["fits_budget"] is False
assert vast["total_cost_usd"] < ondemand["total_cost_usd"]
assert "vast_rtx_4090_spot" in GPU_COMPUTE_CATALOG
def test_14_reproducibility_and_rebuttal_gate_scoring() -> None:
"""Verify reproducibility checklist distinguishes REJECT_RISK draft from ACCEPT_READY artifact."""
exp4 = run_exp4_compute_budget_and_repro_audit()
draft = exp4["draft_repro_gate"]
final = exp4["final_repro_gate"]
assert draft["artifact_score"] == 2
assert draft["rebuttal_readiness"] == "REJECT_RISK"
assert final["artifact_score"] == 8
assert final["rebuttal_readiness"] == "ACCEPT_READY"
minor = evaluate_reproducibility_gate(
ReproducibilityChecklistInput(
submission_name="MinorRev",
fixed_seeds_logged=True,
confidence_intervals_reported=True,
multiple_testing_corrected=True,
equal_baseline_tuning_budget=True,
single_factor_ablations_complete=True,
leakage_audit_passed=True,
compute_hours_and_hardware_disclosed=False,
limitations_and_negative_results_included=False,
)
)
assert minor.artifact_score == 6
assert minor.rebuttal_readiness == "MINOR_REVISION"
def test_15_bounded_otel_span_exporter_and_telemetry() -> None:
"""Verify BoundedInMemorySpanExporter enforces max_spans and records all 5 benchmark spans."""
provider, exporter, tracer = create_in_memory_otel_tracer(max_spans=3)
for i in range(5):
with tracer.start_as_current_span(f"span_{i}"):
pass
provider.force_flush()
spans = exporter.get_finished_spans()
assert len(spans) == 3
assert [s.name for s in spans] == ["span_2", "span_3", "span_4"]
provider.shutdown()
bench = run_full_research_methodology_benchmark(seed=42, quick=True)
otel = bench["otel_telemetry"]
assert otel["total_spans_recorded"] == 5
assert otel["distinct_span_names"] == [
"stats.multiseed_eval",
"stats.multiple_testing_fwer",
"ablation.confounder_audit",
"leakage.split_audit",
"budget.power_and_cost",
]
def test_16_determinism_seed_42_and_workbench_panels_contract() -> None:
"""Verify identical outputs for seed=42 and strict workbench_panels (6 KPI, 4 bar, 4 table)."""
from scripts.run_lab_demo import run_wb_ch30_benchmark
r1 = run_wb_ch30_benchmark(seed=42, quick=True)
r2 = run_wb_ch30_benchmark(seed=42, quick=True)
assert r1["exp1_multiseed_and_fwer"] == r2["exp1_multiseed_and_fwer"]
assert r1["exp3_leakage_audit"] == r2["exp3_leakage_audit"]
panels: dict[str, Any] = r1["workbench_panels"]
assert len(panels["kpis"]) == 6
assert len(panels["bars"]) == 4
assert len(panels["tables"]) == 4
for bar in panels["bars"]:
assert len(bar["items"]) >= 4
for tbl in panels["tables"]:
assert len(tbl["columns"]) == 4
assert len(tbl["rows"]) >= 3
def test_17_cli_subprocess_generates_valid_artifact(tmp_path: Path) -> None:
"""Verify scripts/run_lab_demo.py executes cleanly via subprocess and writes valid JSON."""
out_file = tmp_path / "wb30_out.json"
proc = subprocess.run(
[
sys.executable,
str(LAB_ROOT / "scripts" / "run_lab_demo.py"),
"--seed",
"42",
"--quick",
"--output",
str(out_file),
],
cwd=str(LAB_ROOT),
capture_output=True,
text=True,
check=True,
)
assert "Wrote WB-Ch30 artifact" in proc.stdout
payload = json.loads(out_file.read_text(encoding="utf-8"))
assert len(payload["workbench_panels"]["kpis"]) == 6
assert payload["otel_telemetry"]["total_spans_recorded"] == 5
@given(
n_seeds=st.integers(min_value=3, max_value=40),
delta=st.floats(min_value=0.3, max_value=6.0, allow_nan=False, allow_infinity=False),
std=st.floats(min_value=0.5, max_value=4.0, allow_nan=False, allow_infinity=False),
)
@settings(max_examples=25, deadline=None)
def test_18_hypothesis_student_t_power_monotonicity(
n_seeds: int,
delta: float,
std: float,
) -> None:
"""Property test: Student-t power strictly increases with n and delta and decreases with std."""
p_base = compute_paired_t_power(n_seeds=n_seeds, effect_size_delta=delta, seed_std=std)
p_more_n = compute_paired_t_power(n_seeds=n_seeds + 2, effect_size_delta=delta, seed_std=std)
p_larger_d = compute_paired_t_power(
n_seeds=n_seeds,
effect_size_delta=delta + 0.5,
seed_std=std,
)
p_higher_std = compute_paired_t_power(
n_seeds=n_seeds,
effect_size_delta=delta,
seed_std=std + 0.5,
)
assert 0.05 <= p_base <= 1.0
assert p_more_n >= p_base - 1e-6
assert p_larger_d >= p_base - 1e-6
assert p_higher_std <= p_base + 1e-6
@given(
seed_budget=st.integers(min_value=4, max_value=30),
seed_std=st.floats(min_value=0.6, max_value=4.0, allow_nan=False, allow_infinity=False),
)
@settings(max_examples=20, deadline=None)
def test_19_hypothesis_mde_and_required_seeds_roundtrip(
seed_budget: int,
seed_std: float,
) -> None:
"""Property test: solving MDE at n seeds yields achieved power >= 0.80 and roundtrips n*."""
mde = solve_minimum_detectable_effect(
n_seeds=seed_budget,
seed_std=seed_std,
alpha=0.05,
target_power=0.80,
)
pwr = compute_paired_t_power(
n_seeds=seed_budget,
effect_size_delta=mde,
seed_std=seed_std,
alpha=0.05,
)
assert pwr >= 0.799
n_req, _ = estimate_required_seeds(
effect_size_delta=mde,
seed_std=seed_std,
alpha=0.05,
target_power=0.80,
)
assert n_req <= seed_budget
@given(
vals=st.lists(
st.floats(min_value=-50.0, max_value=150.0, allow_nan=False, allow_infinity=False),
min_size=4,
max_size=24,
),
)
@settings(max_examples=25, deadline=None)
def test_20_hypothesis_iqm_and_holm_bh_bounds(vals: list[float]) -> None:
"""Property test: IQM stays bounded inside [min, max] and scales affinely; cohens_d finite."""
iqm_val = interquartile_mean(vals)
assert min(vals) - 1e-9 <= iqm_val <= max(vals) + 1e-9
shifted = [v + 12.5 for v in vals]
assert abs(interquartile_mean(shifted) - (iqm_val + 12.5)) < 1e-7
# Also verify paired Cohen's d sign matches mean difference sign
half = len(vals) // 2
if half >= 2:
a = vals[:half]
b = [x - 1.0 for x in a]
d_val = cohens_d_paired(a, b)
assert math.isfinite(d_val)
assert d_val > 0.0
# Budget planner sanity check
plan = plan_compute_budget("vast_rtx_4090_spot", effect_size_delta=2.45, seed_std=1.80)
assert plan.required_seeds_n == 7
WB-Ch30 (Test 06, hiệu ứng thật +2.44pp), vì sao đánh giá với n = 3 hạt giống (seeds) thu được p = 0.4953 (95% CI [-0.45, +2.35]), còn n = 10 hạt giống lại khẳng định ý nghĩa thống kê (p = 0.0040, CI [+1.66, +3.18])?1 trong 10 hạt giống bị sụp gradient xuống 39.5% (WB-Ch30, Exp 1A), thước đo rliable Interquartile Mean (IQM) phản ứng như thế nào so với trung bình cộng số học?m = 20 phép so sánh ở \(\alpha = 0.05\), 2,000 nghiên cứu mô phỏng dưới \(H_0\)), phát biểu nào ĐÚNG về FWER thô và hai phương pháp hiệu chỉnh Holm–Bonferroni vs Benjamini–Hochberg (BH)?WB-Ch30 (Test 09), tại sao bảng ablation gốc tuyên bố cải thiện +4.89pp (79.82% -> 84.71%) bị bộ kiểm toán gắn 2 lỗi CRITICAL?960 mẫu dọc theo 120 bệnh nhân, Test 11), điều gì xảy ra khi thay chia ngẫu nhiên + StandardScaler toàn cục bằng chia rời nhóm theo trình tự thời gian và fit bộ chuẩn hóa riêng trên train?6 biến thể \(\times (n^* + 4\text{ HP}) \times 1.5\text{h}\) dưới trần ngân sách USD 150 (WB-Ch30, Exp 4, Test 13), phương án nào tối ưu nhất?export_booktabs_latex_table của WB-Ch30 (Exp 2, Test 10), nguyên tắc trình bày và in đậm (\textbf{...}) nào phản ánh đúng chuẩn công bố A*/Q1?A*/RIVF đặt câu hỏi thuộc nhóm Type A (nghi ngờ thiếu baseline được tinh chỉnh công bằng hoặc thiếu kiểm định đa seed), cách xử lý nào mang lại xác suất chuyển điểm 5 -> 7 cao nhất?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 — Soạn Thảo Giả thuyết Khả bác bỏ và Kế hoạch Tiền đăng ký 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Xác định rõ cặp H0/H1 định hướng, ngưỡng MDE delta_min có ý nghĩa khoa học và điều kiện buộc bác bỏ giả thuyết để tránh HARKing.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Gắn kèm hợp đồng Tune-the-Baseline: cố định B_new == B_base, cùng chia tập và quy tắc dừng sớm.
Tiêu chí Đáp án & Số đối chứng
Giả thuyết chuẩn phải nêu cơ chế nhân quả cụ thể (ví dụ từ Chương 28/29), kỳ vọng H1: E[Delta] >= delta_min > 0, ngưỡng bác bỏ tường minh (nếu IQM gain < delta_min hoặc p_Holm >= 0.05 thì bác bỏ), và bắt buộc chạy B_base = B_new = 8 lượt tìm kiếm siêu tham số cho cả baseline lẫn phương pháp mới.
Bài tập 2 — Kiểm chứng Thống kê Đa Seed rliable và Hiệu chỉnh Holm-Bonferroni / BH 20%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Giải thích vì sao không gian đổi dấu 2^3 = 8 chặn p nhỏ nhất của n=3 ở 0.25, đối chiếu wilcoxon_signed_rank_test và sai khác rời rạc rliable floor(0.25*n) khi n % 4 != 0.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Áp dụng công thức bước xuống Holm max_{j<=i} min(1, (m-j+1) p_(j)) cho m=20 và so sánh FWER=4.95% vs FWER thô 64.0%.
Tiêu chí Đáp án & Số đối chứng
Trong Exp 1A, n=3 thiếu công suất (perm p=0.4953, Wilcoxon p=0.500, CI [-0.45, +2.35]), còn n=10 đạt +2.53pp IQM (CI [+1.66, +3.18], perm p=0.0040, Wilcoxon exact p=0.0039 W=1.0, d=1.91). Khi 1 seed crash xuống 39.5%, mean đảo âm -1.42pp còn IQM (rliable trim_mean cắt floor(0.25*n) ở hai đuôi) giữ +2.53pp bất chấp Wilcoxon p=0.0840. Với m=20, FWER thô đạt 64.0% (lý thuyết 64.15%), còn Holm giảm về 4.95% (0/17 FP) và BH giữ FDR 5.0%.
Bài tập 3 — Gỡ lỗi Bảng Ablation Trộn Yếu tố và Phân rã Tương tác 2x2 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Chạy analyze_ablation_table lên bảng lỗi (+4.89pp từ 79.82% -> 84.71%) và bảng sạch (+4.17pp từ 80.50% -> 84.67%) trong Exp 2 để xác định khoảng cách Hamming giữa các hàng.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Dùng công thức Delta_int = y11 - y10 - y01 + y00 cho cặp (arch_gate, mixup_aug) và kiểm tra đóng góp của cosine_lr.
Tiêu chí Đáp án & Số đối chứng
Bảng lỗi vi phạm cả confounded_multi_factor (nhảy 3 yếu tố) lẫn unfair_tuning_asymmetry (1 vs 15 trials, thổi phồng +4.89pp với +0.72pp thiên lệch ảo). Bảng sạch (8 vs 8 lượt) đo chuẩn hiệu ứng thật +4.17pp (80.50% -> 84.67%): arch_gate = +2.28pp, mixup_aug = +1.40pp, tương tác arch_gate x mixup_aug = +0.39pp, còn cosine_lr chỉ thêm +0.31pp (nhỏ hơn nhiều so với 95% CI +-0.85pp nên có thể lược bỏ để giữ mô hình gọn).
Bài tập 4 — Kiểm toán Bốn Kênh Rò rỉ Dữ liệu Trên Bài toán Dọc Thời gian 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Kiểm tra cả 4 điều kiện bất biến: ID disjoint, Group disjoint, max(t_train) < min(t_val) < min(t_test), và StandardScaler chỉ fit trên train.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Đối chiếu số lượng vi phạm và mức giảm Accuracy/ROC-AUC trong Exp 3 (leaked_audit vs clean_audit).
Tiêu chí Đáp án & Số đối chứng
Chia ngẫu nhiên + global scaler để lọt 24 ID trùng, 260 nhóm chéo, 766 dòng sai thứ tự thời gian và 216 mẫu rò rỉ thống kê, đẩy điểm ảo lên 88.4% (AUC 0.968). Khi tách nhóm bệnh nhân theo trình tự thời gian và chuẩn hóa train-only (360/18/60), hiệu năng thật còn 68.3% (AUC 0.868), bóc trần +20.09pp ảo ảnh.
Bài tập 5 — Lập Đề xuất Công suất Student-t và Ngân sách Đám mây USD 150 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Gọi estimate_required_seeds(effect_size_delta=2.0, seed_std=1.8, target_power=0.80) để tìm số seed tối thiểu n*.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Đưa n* vào plan_compute_budget cho từng tier trong GPU_COMPUTE_CATALOG và lưu ý hệ số Spot preemption_overhead_factor * checkpoint_overhead_factor.
Tiêu chí Đáp án & Số đối chứng
Khi MDE giảm xuống delta=2.0pp (std=1.8pp), số seed tối thiểu tăng từ n=7 lên n=9 (power 83.04%). Nhân 6 biến thể x (9 + 4 HP) = 78 lượt x 1.5h = 117h thô (143.58h hiệu dụng Spot); trên vast.ai RTX 4090 Spot ($0.34/h) tổng chi phí là $48.82 (nằm gọn dưới trần $150), trong khi On-Demand A100 ($265.17) vượt trần nghiêm trọng.
Bài tập 6 — Hoàn thiện Bảng LaTeX booktabs, Thư Phản biện và Nghiệm thu WB-Ch30 20%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Chạy uv lock --check, ruff check src scripts tests, mypy src tests (0 type: ignore), scripts/run_lab_demo.py --seed 42 và pytest -p no:cacheprovider -v.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Xác minh artifacts/ch30_wb30_results.json có đủ 5 spans OpenTelemetry và workbench_panels (6 KPI, 4 bar, 4 bảng), đồng thời xuất bảng booktabs in đậm đồng hạng.
Tiêu chí Đáp án & Số đối chứng
Toàn bộ 20/20 pytest (gồm AST gate cấm pickle/type-ignore, Hypothesis và BoundedInMemorySpanExporter 5 spans), ruff/mypy --strict (0 lỗi), uv.lock (24 gói) đạt 100%; bảng booktabs không dùng đường dọc, in đậm đồng hạng (84.57% +- 0.96 và 84.67% +- 0.85) và đạt cổng tái lập 8/8 chuẩn RIVF 2026 / A*.