Chương 16 — Thị giác Máy tính, Tích chập (CNN), Bền vững Đối kháng & Giải thích Thị giác (Computer Vision, CNN & Robustness)
Từ YCbCr/CLAHE (std 0.177 vs 0.288), HOG (98.3%) & RF=26/DW-Sep (6.33x params, 5.21x MACs, Roofline OI 2.10 vs 25.41) đến FGSM/PGD-10 (100%->0%->99.2% AdvTrain), Randomized Smoothing (R=0.212, 100% Cert) & Grad-CAM/IG Deletion AUC (0.110/0.138 vs 0.688) + Adebayo PASS.
Đơn vị học phần (
Unit ID):T1-P3-U03(Phần 3: Nền tảng Học Sâu, Thị giác Máy tính Hiện đại & Nhận thức Đa phương thức — Mục lục Phần 3)
Phòng thí nghiệm Thực chiến: Lab 08 — Xử lý Ảnh 101, Số học Tích chập (CNN), Bền vững Đối kháng & Giải thích Thị giác (cv_cnn_robustness_lab)
Truy xuất nguồn & kế thừa: Chương 02 — Đại số Tuyến tính & Giải tích Ma trận (chuẩn \(L_p\), gradient ma trận), Chương 07 — Đánh giá Chống Rò rỉ & Hiệu chuẩn (ECE, phân tách theo nhóm), Chương 14 — Mạng Nơ-ron & Nội tại PyTorch 2.x (autograd,BatchNorm), Chương 15 — Autoencoder, Lưu trữ An toàn & Nén Biên (safetensors,ONNX dynamo=False), Chương trình gốc DSAI (R43,R44& LabE43:E45), và Đề cương SOTA 2026 (Chương 16). Chương tiếp theo trong lộ trình làChương 17.
Bốn Ca Thất bại Thực chiến Mở màn: Từ Răng cưa Ảnh & Sụp đổ Đối kháng đến Ảo giác Giải thích Thị giác#
Một mô hình phân loại ảnh đạt độ chính xác 100% trên tập kiểm thử sạch trong phòng thí nghiệm có thể sụp đổ hoàn toàn ngay ngày đầu triển khai xuống dây chuyền kiểm tra quang học tự động (PCB AOI), camera xe tự hành hay hệ thống chẩn đoán y tế vì bốn cạm bẫy kinh điển sau:
-
Ca 1 — Lệch Màu & Nhiễu Đèn Xưởng do Tiền xử lý Ngây thơ trên
RGB(Lab 08,Test 02–03):Cân bằng biểu đồ tần suất toàn cục (
Global Histogram Equalization) trực tiếp trên từng kênhR, G, Bkhi ánh sáng LED nhà xưởng trôi±16%vừa làm biến dạng sắc độ của pad mạ vàng và cầu thiếc, vừa khuếch đại nhiễu nền sợi thủy tinh lên gấp đôi (gray std: 0.135 -> 0.288). Chuyển sang phân tách độ chói–sắc độYCbCr(hoặcHSV) và áp dụngCLAHEcục bộ trên kênh chói \(Y\) (grid 4×4, clip 2.5) giữ cân bằng tương phản mượt (std = 0.177) mà không làm cháy sáng chân hàn. Đồng thời, hạ phân giải không qua lọc thông thấp Gaussian gây răng cưa không gian (spatial aliasing theo định lý Nyquist–Shannon 2D). -
Ca 2 — Nghịch lý Roofline của Tích chập Phân tách Chiều sâu (
Depthwise-Separable Conv) (Lab 08,Test 06 & 08):Trên bài toán kiểm tra
4trạng thái vi mạch PCB (Lab 08), thay thế các tầng tích chập3×3đặc củaStandardCNN(39,196tham số,5,087,488MACs) bằngDepthwiseSeparableCNNcắt giảm6.33xtham số (6,196) và5.21xMACs (975,616) mà vẫn giữ nguyên độ chính xác100.0%, đạt tốc độ suy luận0.319 ms/ảnhtrênONNX Runtime CPU(safetensors diff = 0.00e+00,ORT diff = 2.38e-06). Tuy nhiên, trên khối48 -> 64(8×8), dù tầngDepthwise-Separablegiảm7.89xMACs (khớp tuyệt đối lý thuyết \(1/64 + 1/9 = 0.1267\)), cường độ số học (Operational Intensity) của riêng bướcDepthwise 3×3rơi từ25.41xuống chỉ còn2.10FLOPs/byte — biến nó thành nút cổ chai băng thông bộ nhớ (memory-bandwidth bound) nếu không gộp toán tử (kernel fusion) khi chạy trên GPU! -
Ca 3 — Sụp đổ Tuyệt đối từ
100.0% -> 0.0%dưới Tấn công Đối khángPGD-10(\(\epsilon = 0.06\)) (Lab 08,Test 10–12):Trong
Lab 08, mạngStandardCNNđạt100.0%trên ảnh PCB sạch, nhưng chỉ cần cộng nhiễu đối kháng \(L_\infty\) biên độ \(\epsilon = 0.06\) (nhỏ hơn16/255mức xám 8-bit, gần như vô hình bằng mắt thường), độ chính xác rơi thẳng xuống20.0%dướiFGSMvà sụp về0.0%dướiPGD-10. Ngược lại, Huấn luyện Đối kháng Điểm yên ngựa (PGD Adversarial Training— Madry et al. 2018) giải cứu độ bềnPGD-10lên99.2%(+99.2điểm phần trăm) mà vẫn giữ100.0%trên ảnh sạch; kết hợp Làm mịn Ngẫu nhiên (Randomized Smoothing, Cohen et al. 2019) tại \(\sigma_{\text{rs}} = 0.10, \alpha_{\text{conf}} = 0.001\) cấp chứng chỉ toán học chắc chắn \(L_2\) với bán kính trung bìnhR = 0.212(Certified Acc = 100%,0/16từ chối) và cơ chếABSTAINan toàn khi \(\underline{p_A} \le 0.5\). -
Ca 4 — Ảo giác Bản đồ Nhiệt & Học Đường tắt (
Shortcut Learning) trongVisual XAI(Lab 08,Test 13–15):Nhiều hệ thống XAI công nghiệp chỉ trưng ra vài hình minh họa đẹp mắt (
Guided Backprop) mà bỏ qua kiểm định trung thực — dù Adebayo et al. (2018) đã chứng minhGuided Backpropthực chất chỉ là bộ lọc cạnh Sobel bất biến với trọng số mạng! TrongLab 08, việc kết hợpGrad-CAM(forward/backward hooks trên tầng tích chập cuối) vàIntegrated Gradients(kiểm chứng tiên đề Completeness với sai số tối đa2.61e-02, trung bình8.68e-03) chứng minh tính trung thực định lượng:Deletion AUCrơi thẳng xuống0.110(IG) và0.138(Grad-CAM) so với0.688(xóa ngẫu nhiên), trong khiInsertion AUCvọt lên0.963(IG) và0.946(Grad-CAM) so với0.682(chèn ngẫu nhiên), đồng thời cả hai đều vượt qua kiểm định ngẫu nhiên hóa trọng số Adebayo (|r| = 0.304vớiGrad-CAM,0.596vớiIG).
Mục tiêu Học tập (Learning Objectives)#
Sau khi hoàn tất Chương 16 và vượt qua 16/16 bài kiểm thử tự động của Lab 08, học viên nắm vững ở trình độ chuyên sâu thạc sĩ (UCL MSc Distinction):
- Vật lý Hình thành Ảnh, Không gian Màu & Tiền xử lý Cổ điển: Nắm chắc định lý lấy mẫu Nyquist–Shannon 2D chống răng cưa, chuyển đổi giải tích
RGB <-> HSV / YCbCr / CIELAB, cơ chế cắt đỉnh nội suy song tuyến tính củaCLAHE, lọc tách được Gaussian, đạo hàmSobel/Laplacian/Canny(NMS+ nối biên trễ), hình thái học (Opening/Closing), và bộ mô tảHOGchuẩn hóa khốiL2-HyscùngSIFTkhông gian tỷ lệDoG. - Số học Tích chập, Trường Tiếp nhận & Hiệu quả Phần cứng Roofline: Tính chính xác kích thước đầu ra \(O\) và công thức đệ quy trường tiếp nhận \(r_l\) cho cả tích chập giãn (\(D > 1\)), phân tích định lượng tỷ lệ cắt giảm
MACsvà tham số \(1/C_{\text{out}} + 1/K^2\) của Tích chập Phân tách Chiều sâu (MobileNet) lẫn Tích chập Nhóm (1/G), và giải thích bẫy cường độ số học Roofline trên phần cứng hiện đại. - Chiến lược Tăng cường Dữ liệu SOTA (
2020–2026): Hiểu sâu cơ chế toán học và tác động lên biên quyết định/hiệu chuẩn củaRandAugment,Albumentations,MixUp,CutMix,MosaicvàCopy-Paste. - Lý thuyết Tấn công, Phòng thủ & Chứng nhận Đối kháng: Phân biệt mô hình đe dọa \(L_\infty, L_2\), hộp trắng/hộp đen; tự tay cài đặt
FGSM,PGD, vạch trần bẫy che khuất gradient (obfuscated gradients) và vai trò củaAutoAttack; dẫn xuất bài toán điểm yên ngựa Min–MaxPGD Adversarial Trainingvà định lý Neyman–Pearson choRandomized Smoothing(Clopper–Pearson +ABSTAIN). - Giải thích Thị giác Trung thực (
Visual XAI Faithfulness): Dẫn xuất và cài đặtGrad-CAM,Integrated Gradients(4 tiên đề, đặc biệt Completeness và bẫy chọn baseline),RISEhộp đen; kiểm toán định lượng bằng Deletion / Insertion AUC và Adebayo Weight-Randomization Sanity Check.
Truy xuất Nguồn (Syllabus & Raw Curriculum Traceability)#
Thành phần Chương trình Nguồn (R43, R44 & E43:E45) |
Nội dung Chuyên sâu trong Chương 16 | Sơ đồ / Mô phỏng Tương tác | Thực thi trong Lab 08 (cv_cnn_robustness_lab) |
|---|---|---|---|
Nền tảng Ảnh & Không gian Màu (R43) |
Mô hình Pinhole, Nyquist 2D chống răng cưa, RGB, HSV, YCbCr, CIELAB |
Mermaid 1 |
color_and_filters.py: generate_aoi_pcb_dataset, rgb_to_hsv, rgb_to_ycbcr, array_to_pil_and_back (Test 02) |
Tiền xử lý & Hình thái học (R43) |
HistEq vs CLAHE, Conv2D, Gaussian, Sobel, Laplacian, Canny (NMS + hysteresis), Erode/Dilate/Open/Close |
Mermaid 1 |
color_and_filters.py: clahe_tile_equalize, conv2d_numpy, sobel_edges, canny_hysteresis_edges, binary_open, binary_close (Tests 02, 03) |
Trích xuất Đặc trưng Cổ điển (R43) |
HOG (chuẩn hóa L2-Hys), SIFT (DoG scale-space + Hessian) vs đặc trưng CNN học phân cấp |
Mermaid 1 |
color_and_filters.py: extract_hog_descriptor, evaluate_hog_linear_baseline (Test 04) |
Tích chập, Pooling & Hiệu quả (R44) |
Công thức \(O\), đệ quy Receptive Field \(r_l\) (có dilation \(D\)), DW-Sep (\(1/C_{\text{out}}+1/K^2\)), Grouped (\(1/G\)), Roofline OI, đồng biến tịnh tiến |
Mermaid 1 + Widget 1 (conv-receptive-field-flops-lab) |
conv_geometry.py & cnn_models.py: compute_receptive_field_stack, compare_standard_vs_dwsep_conv, StandardCNN, DepthwiseSeparableCNN, safetensors, ONNX/ORT (Tests 05, 06, 08, 09) |
Tăng cường Dữ liệu (Augmentation) (R44) |
Biến đổi hình học/quang trắc, RandAugment, Albumentations, MixUp, CutMix, Mosaic, Copy-Paste |
Mermaid 2 |
cnn_models.py: apply_randaugment_batch, apply_mixup_batch, apply_cutmix_batch, build_mosaic_quad (Test 07) |
Tấn công & Phòng thủ Đối kháng (R44) |
Threat models (\(L_\infty, L_2\)), FGSM, PGD, Obfuscated Gradients & AutoAttack, PGD Min–Max AT, Randomized Smoothing (\(R = \sigma\Phi^{-1}(\underline{p_A})\)) |
Mermaid 3 + Widget 2 (adversarial-fgsm-pgd-robustness) |
adversarial.py: fgsm_attack, pgd_linf_attack, train_pgd_adversarial_cnn, certify_randomized_smoothing (Tests 10, 11, 12) |
Giải thích Mô hình Thị giác (XAI) (R44) |
Grad-CAM (hooks + ReLU), Integrated Gradients (Completeness), RISE, Deletion/Insertion AUC & Adebayo Sanity Check |
Mermaid 2, Mermaid 3 + Widget 3 (visual-xai-gradcam-ig-explorer) |
visual_xai.py: compute_gradcam, compute_integrated_gradients, compute_rise_saliency, evaluate_deletion_insertion_auc, check_adebayo_weight_randomization_sanity (Tests 13, 14, 15) |
Bảng Ký hiệu Phi Mơ hồ (Disambiguated Notation Contract)#
| Ký hiệu LaTeX | Miền / Kích thước | Định nghĩa chuẩn trong Chương 16 | Tên biến trong cv_cnn_robustness_lab |
|---|---|---|---|
| \(I, \mathbf{x}\) | \([0, 1]^{C \times H \times W}\) | Ảnh RGB đầu vào chuẩn hóa (3×32×32 trong Lab 08) |
img, x |
| \(K, S, P, D\) | \(\mathbb{N}_+, \mathbb{N}_+, \mathbb{Z}_{\ge 0}, \mathbb{N}_+\) | Kích thước nhân lọc, bước nhảy, đệm biên, hệ số giãn (dilation) |
kernel_size, stride, padding, dilation |
| \(O, r_l, j_l\) | \(\mathbb{N}_+\) | Kích thước đầu ra, đường kính trường tiếp nhận & bước nhảy tích lũy tầng \(l\) | out_size, receptive_field, effective_stride |
| \(C_{\text{in}}, C_{\text{out}}, G\) | \(\mathbb{N}_+\) | Số kênh vào, số kênh ra, số nhóm tích chập (groups) |
in_channels, out_channels, groups |
| \(\mathbf{h}_{\text{HOG}}\) | \(\mathbb{R}^{1764}\) | Vector mô tả HOG chuẩn hóa khối L2-Hys (cell=4, block=2×2, 9 bins) |
hog_vec |
| \(\delta, \epsilon, \alpha_{\text{pgd}}\) | \(\mathbb{R}^{C\times H\times W}, \mathbb{R}_{>0}\) | Nhiễu đối kháng, ngân sách chuẩn \(L_\infty/L_2\), bước nhảy lặp PGD |
delta, epsilon, step_size |
| \(\sigma_{\text{rs}}, \underline{p_A}, R\) | \(\mathbb{R}_{>0}, (0.5, 1], \mathbb{R}_{\ge 0}\) | Độ lệch chuẩn làm mịn, cận dưới Clopper–Pearson, bán kính chứng nhận \(L_2\) | sigma, p_a_lower, certified_l2_radius |
| \(A^k, \alpha_k^c, L_{\text{GC}}^c\) | \(\mathbb{R}^{H_f \times W_f}, \mathbb{R}, [0,1]^{H\times W}\) | Bản đồ kích hoạt kênh \(k\), trọng số Grad-CAM, bản đồ nhiệt chuẩn hóa |
act, weights, heatmap |
| \(x', M_{\text{ig}}, \operatorname{IG}_i\) | \([0,1]^{C\times H\times W}, \mathbb{N}_+, \mathbb{R}\) | Ảnh nền baseline, số bước tích phân trung điểm Riemann, quy gán IG |
baseline, steps, attribution |
| \(\text{AUC}_{\text{del}}, \text{AUC}_{\text{ins}}\) | \([0, 1]\) | Diện tích đường cong xóa (càng thấp càng tốt) & chèn (càng cao càng tốt) | deletion_auc, insertion_auc |
Trụ cột 1 — Nền tảng Toán học: Xử lý Ảnh Cổ điển, Số học Tích chập, Bền vững Đối kháng & Visual XAI#
1.1 Hình thành Ảnh, Lấy mẫu Nyquist 2D, Không gian Màu & Bộ lọc Cổ điển#
Ảnh số rời rạc \(I[u, v]\) thu nhận từ cảm biến CMOS qua phép chiếu lỗ kim chịu sự chi phối của Định lý Lấy mẫu Nyquist–Shannon 2D: mọi tần số không gian vượt quá tần số Nyquist \((f_{N,x}, f_{N,y}) = \big(\frac{1}{2\Delta x}, \frac{1}{2\Delta y}\big)\) sẽ bị gấp phổ (spectral folding) tạo nên họa tiết giả Moiré. Do đó, mọi thao tác hạ phân giải bằng bước nhảy \(S > 1\) (trong tiền xử lý hay mạng CNN) đều cần làm mượt thông thấp trước bằng nhân Gaussian tách được \(G_\sigma(x,y) = g_\sigma(x)\,g_\sigma(y)\), giảm chi phí tính toán từ \(O(HWK^2)\) xuống \(O(2HWK)\).
Để tách biến thiên ánh sáng khỏi bản chất màu sắc vật thể, ta chuyển đổi từ RGB sang HSV (tách góc màu \(H \in [0^\circ, 360^\circ)\), độ bão hòa \(S\), độ sáng \(V = \max(R,G,B)\)), YCbCr (tách độ chói \(Y = 0.299 R + 0.587 G + 0.114 B\) khỏi sắc độ \(C_b, C_r\)), hoặc CIELAB (đều về cảm nhận màu \(\Delta E_{ab}^*\)). Khi ánh sáng nền biến thiên cục bộ, CLAHE chia kênh độ chói thành lưới ô, cắt đỉnh biểu đồ tần suất tại ngưỡng \(\beta_{\text{clip}}\) để chặn khuếch đại nhiễu đồng nhất rồi nội suy song tuyến tính qua tâm các ô kề nhau.
Trên ảnh đã chuẩn hóa, các toán tử cổ điển trích xuất cấu trúc hình học theo 3 tầng:
- Đạo hàm biên (
Sobel,Laplacian,Canny): NhânSobelkết hợp làm mượt 1D và sai phân trung tâm cho biên độ \(M = \sqrt{G_x^2 + G_y^2}\) và góc \(\theta = \operatorname{atan2}(G_y, G_x)\). Thuật toánCannytiến thêm hai bước then chốt: triệt tiêu phi cực đại (NMS) dọc pháp tuyến biên làm nét biên mảnh còn đúng1pixel và nối biên trễ ngưỡng kép (double-threshold hysteresis) giữ biên yếu chỉ khi liên thông 8-lân cận với biên mạnh. - Hình thái học toán học: Với phần tử cấu trúc \(B\), phép Mở (
Opening) \(A \circ B = (A \ominus B) \oplus B\) quét sạch nhiễu đốm sáng nhỏ ngoài vật thể, còn phép Đóng (Closing) \(A \bullet B = (A \oplus B) \ominus B\) lấp kín lỗ rỗ tối bên trong linh kiện. - Bộ mô tả
HOG(Dalal & Triggs 2005) &SIFT(Lowe 2004):HOGtích lũy phiếu bầu biên độ gradient vào9thùng góc không dấu \([0^\circ, 180^\circ)\) trên từng ô4×4, sau đó ghép khối2×2ô chồng lấn và chuẩn hóaL2-Hys:\[\mathbf{v}' = \frac{\mathbf{v}}{\sqrt{\lVert \mathbf{v} \rVert_2^2 + \varepsilon^2}}, \qquad \mathbf{v}'' = \frac{\min(\mathbf{v}',\, 0.2)}{\sqrt{\lVert \min(\mathbf{v}',\, 0.2) \rVert_2^2 + \varepsilon^2}}.\]Phép chuẩn hóa theo khối này làmHOGgần như bất biến với phép nhân độ sáng đồng nhất (cosine similarity > 0.99trongTest 04củaLab 08), nhưngHOGbỏ qua thông tin sắc độ và nhạy cảm với dịch chuyển không gian lớn. Trong khi đó,SIFTdò cực trị 3D trên tháp hiệu hai hàm Gaussian (DoG) \(D(x,y,\sigma) = (G_{k\sigma} - G_\sigma) * I\) và lọc điểm cạnh bằng tỷ số ma trận Hessian \(\operatorname{Tr}(\mathbf{H})^2/\det(\mathbf{H})\) để tạo vector128-chiều bất biến cả tỷ lệ lẫn góc xoay.
1.2 Số học Tích chập, Công thức Đệ quy Trường Tiếp nhận & Hiệu quả Depthwise-Separable#
Trong thực thi học sâu (nn.Conv2d), phép toán thực sự là tương quan chéo 2D có chia sẻ trọng số không gian, tạo nên thiên kiến quy nạp (inductive bias) gồm tính cục bộ (locality) và tính đồng biến tịnh tiến (translation equivariance): \(f(T_\delta(I)) = T_\delta(f(I))\) (tuy nhiên bị phá vỡ nhẹ tại biên do zero-padding và bước nhảy \(S > 1\) không anti-aliasing).
Mệnh đề 1.1 (Kích thước Đầu ra & Đệ quy Trường Tiếp nhận có Hệ số Giãn \(D\)):
Xét chuỗi \(L\) tầng tích chập hoặc pooling với nhân \(k_l\), bước nhảy \(s_l\), đệm \(p_l\) và hệ số giãn \(d_l \ge 1\). Khi đó nhân hiệu dụng có kích thước \(k_{l,\text{eff}} = d_l(k_l - 1) + 1\), kích thước bản đồ đặc trưng đầu ra là:
và đường kính trường tiếp nhận lý thuyết \(r_l\) cùng bước nhảy hiệu dụng \(j_l\) (khởi tạo \(r_0 = 1, j_0 = 1\)) tuân theo hệ đệ quy chính xác:
Kiểm chứng trên Lab 08 (Test 05): Chuỗi 5 tầng conv1(3×3, s=1) -> pool1(2×2, s=2) -> conv2(3×3, s=1) -> pool2(2×2, s=2) -> conv3(3×3, s=1, d=2) trên ảnh 32×32 mở rộng lần lượt \(r_l \in \{3, 4, 8, 10, 26\}\) pixel với bước nhảy \(j_l \in \{1, 2, 2, 4, 4\}\) — chỉ một tầng giãn \(D=2\) ở cuối đã mở rộng trường tiếp nhận từ 10 px lên 26 px bao phủ hầu hết vi mạch 32×32 mà không làm mất độ phân giải 8×8 (dù cần cẩn trọng hiệu ứng lưới gridding nếu xếp nhiều tầng giãn cùng \(D\)). Lưu ý thêm: Trường Tiếp nhận Hiệu dụng (ERF, Luo et al. 2016) suy giảm theo dạng Gaussian quanh tâm, mở rộng chậm hơn chỉ \(O(\sqrt{L})\).
Mệnh đề 1.2 (Định lý Cắt giảm MACs của Tích chập Phân tách Chiều sâu — MobileNet & Bẫy Roofline):
So sánh tích chập chuẩn 2D (\(C_{\text{in}} \to C_{\text{out}}\), nhân \(K\times K\), không gian đầu ra \(H_o \times W_o\)) với Tích chập Phân tách Chiều sâu (DW-Sep) gồm bước Depthwise (groups = C_in, nhân \(K\times K\)) nối tiếp bước Pointwise (\(1\times 1\), trộn \(C_{\text{in}} \to C_{\text{out}}\)):
Tương tự, với Tích chập Nhóm (Grouped Conv, số nhóm \(G\)), tỷ lệ tham số và MACs giảm đúng bằng \(1/G\). Tuy nhiên, xét Mô hình Roofline: số phép toán dấu phẩy động trên mỗi byte truyền bộ nhớ (Operational Intensity — OI) của bước Depthwise là:
Trong Lab 08 (Test 06, khối 48 -> 64, 8×8), tỷ lệ MACs đo được khớp tuyệt đối lý thuyết 0.1267 (7.89x ít MACs hơn), nhưng OI của tầng Depthwise chỉ đạt 2.10 FLOPs/byte so với 25.41 FLOPs/byte của tích chập chuẩn — chứng minh vì sao trên GPU không có kernel fusion, giảm 7.89x MACs không bao giờ tự động tăng tốc thực tế 7.89x!
1.3 Tăng cường Dữ liệu SOTA (RandAugment, MixUp, CutMix, Mosaic, Copy-Paste)#
Tăng cường dữ liệu mã hóa trực tiếp các nhóm bất biến mong muốn vào rủi ro thực nghiệm (Vicinal Risk Minimization):
RandAugment: Chỉ dùng 2 siêu tham số \((N_{\text{ops}}, M_{\text{mag}})\) chọn ngẫu nhiên đều \(N_{\text{ops}}\) phép biến đổi hình học/quang trắc cùng cường độ \(M_{\text{mag}}\), bỏ qua chi phí tìm kiếm RL đắt đỏ.MixUp&CutMix: Với \(\lambda \sim \operatorname{Beta}(\alpha, \alpha)\),MixUptrộn tuyến tính \(\tilde{\mathbf{x}} = \lambda \mathbf{x}_i + (1-\lambda)\mathbf{x}_j\) và \(\tilde{\mathbf{y}} = \lambda \mathbf{y}_i + (1-\lambda)\mathbf{y}_j\) giúp làm trơn biên quyết định và hạECE; cònCutMixdán mảng chữ nhật \(M\) từ \(\mathbf{x}_j\) lên \(\mathbf{x}_i\) với \(\lambda = 1 - \frac{|M|}{HW}\), buộc mạng phải tổng hợp bằng chứng từ nhiều vùng đặc trưng không gian thay vì bám vào một dấu hiệu đường tắt duy nhất.Mosaic&Copy-Paste:Mosaicghép 4 ảnh vào cùng khung2×2tăng đa dạng ngữ cảnh cục bộ và vật nhỏ, cònCopy-Pastenhân bản mặt nạ khuyết tật hiếm vào nền mới rất hiệu quả trong kiểm tra công nghiệpAOI.
1.4 Tấn công Đối kháng, Điểm yên ngựa PGD-AT & Chứng nhận Randomized Smoothing#
Cho bộ phân loại \(f_\theta: [0,1]^d \to \mathbb{R}^C\) và quả cầu nhiễu \(\mathcal{S}_p(\epsilon) = \{\delta : \lVert \delta \rVert_p \le \epsilon,\; \mathbf{x} + \delta \in [0, 1]^d\}\).
FGSM(Goodfellow et al. 2015) — Bước Tuyến tính đối ngẫu \(L_\infty\): Khai triển bậc 1 \(\mathcal{L}(f_\theta(\mathbf{x}+\delta), y) \approx \mathcal{L}(f_\theta(\mathbf{x}), y) + \delta^\top \nabla_{\mathbf{x}}\mathcal{L}\). Theo bất đẳng thức Hölder, cực đại trên quả cầu \(L_\infty\) đạt tại \(\delta^* = \epsilon \operatorname{sign}(\nabla_{\mathbf{x}}\mathcal{L})\):\[\mathbf{x}_{\text{adv}}^{\text{FGSM}} = \operatorname{clip}_{[0, 1]}\!\Big(\mathbf{x} + \epsilon \operatorname{sign}\big(\nabla_{\mathbf{x}}\mathcal{L}(f_\theta(\mathbf{x}), y)\big)\Big).\]PGD(Madry et al. 2018) — Tấn công Bậc 1 Chuẩn mực: Khởi tạo ngẫu nhiên đều trong \(\mathcal{B}_\infty(\mathbf{x}, \epsilon)\) rồi lặp \(T\) bước cập nhật kèm phép chiếu \(\Pi_{\mathcal{B}_\infty(\mathbf{x},\epsilon)\cap[0,1]^d}\):\[\mathbf{x}^{(t+1)} = \Pi_{\mathcal{B}_\infty(\mathbf{x}, \epsilon)\cap[0,1]^d}\!\Big(\mathbf{x}^{(t)} + \alpha_{\text{pgd}} \operatorname{sign}\big(\nabla_{\mathbf{x}^{(t)}} \mathcal{L}(f_\theta(\mathbf{x}^{(t)}), y)\big)\Big).\]Cảnh báo Obfuscated Gradients &AutoAttack: Phòng thủ bằng nénJPEG, lượng tử hóa không khả vi hay nhiễu hóa đầu vào chỉ phá hủy gradient (obfuscated gradients, Athalye et al. 2018), tạo cảm giác an toàn giả trướcPGDchuẩn nhưng gục ngay dướiBPDA/EOThoặc bộ kiểm toán chuẩnAutoAttack(APGD-CE,APGD-DLR,FAB,Square Attack).- Huấn luyện Đối kháng Min–Max (
PGD Adversarial Training):\[\min_\theta \; \mathbb{E}_{(\mathbf{x}, y)\sim \mathcal{D}} \left[ \max_{\delta \in \mathcal{S}_\infty(\epsilon)} \mathcal{L}\big(f_\theta(\mathbf{x} + \delta),\, y\big) \right].\]Theo Định lý Danskin, gradient của bài toán ngoài theo \(\theta\) được xấp xỉ bởi gradient đánh giá tại mẫu đối kháng xấu nhất \(\delta_{\text{PGD}}\) tìm được từ vòng lặp trong. Điều này buộc mạng loại bỏ các đặc trưng phi bền vững tần số cao (Tsipras et al. 2019), giải cứu độ chính xác dướiPGD-10trongLab 08từ0.0%lên99.2%. - Định lý 1.3 (Chứng nhận Bền vững \(L_2\) qua Làm mịn Ngẫu nhiên — Cohen et al., ICML 2019):
Xây dựng bộ phân loại làm mịn \(g(\mathbf{x}) = \arg\max_{c} \mathbb{P}_{\varepsilon \sim \mathcal{N}(\mathbf{0}, \sigma_{\text{rs}}^2\mathbf{I})}(f(\mathbf{x}+\varepsilon) = c)\). Giả sử với độ tin cậy \(1 - \alpha_{\text{conf}}\), cận dưới Clopper–Pearson của lớp thắng \(c_A\) thỏa \(\underline{p_A} > 0.5\) và cận trên lớp nhì thỏa \(\overline{p_B} \le 1 - \underline{p_A}\). Khi đó, theo Bổ đề Neyman–Pearson cho hai phân phối chuẩn dịch tâm \(\mathcal{N}(\mathbf{x}, \sigma_{\text{rs}}^2\mathbf{I})\) và \(\mathcal{N}(\mathbf{x}+\delta, \sigma_{\text{rs}}^2\mathbf{I})\), ta có bảo đảm toán học tuyệt đối \(g(\mathbf{x} + \delta) = c_A\) với mọi nhiễu \(\delta\) thỏa:
\[\lVert \delta \rVert_2 < R = \frac{\sigma_{\text{rs}}}{2}\Big(\Phi^{-1}(\underline{p_A}) - \Phi^{-1}(\overline{p_B})\Big) = \sigma_{\text{rs}}\,\Phi^{-1}(\underline{p_A}).\]Nếu \(\underline{p_A} \le 0.5\), bộ chứng nhận bắt buộc trả về
ABSTAIN(\(R = 0\)) để tránh đưa ra quyết định thiếu cơ sở an toàn.
1.5 Giải thích Thị giác (Visual XAI): Grad-CAM, Integrated Gradients, RISE & Kiểm định Trung thực#
Grad-CAM(Selvaraju et al., ICCV 2017): Lấy bản đồ kích hoạt \(A^k \in \mathbb{R}^{H_f\times W_f}\) ở tầng tích chập cuối cùng (nơi cân bằng tốt nhất giữa ngữ nghĩa cấp cao và cấu trúc không gian), tính trọng số tầm quan trọng của kênh \(k\) đối với logit lớp \(c\) trước softmax bằngGAPcủa gradient rồi lọc phần dương quaReLU:\[\alpha_k^c = \frac{1}{H_f W_f} \sum_{i=1}^{H_f}\sum_{j=1}^{W_f} \frac{\partial y^c}{\partial A_{ij}^k}, \qquad L_{\text{GC}}^c = \operatorname{ReLU}\!\left(\sum_{k=1}^{C_f} \alpha_k^c A^k\right).\]Integrated Gradients(Sundararajan et al., ICML 2017) & Tiên đề Completeness: Tích phân gradient dọc đường thẳng nối ảnh nền chuẩn \(x'\) tới ảnh đầu vào \(x\):\[\operatorname{IG}_i(x; x') = (x_i - x_i') \int_{0}^{1} \frac{\partial F\big(x' + \alpha (x - x')\big)}{\partial x_i}\, d\alpha \approx (x_i - x_i') \frac{1}{M_{\text{ig}}} \sum_{m=1}^{M_{\text{ig}}} \frac{\partial F\big(x' + \tfrac{m - 0.5}{M_{\text{ig}}}(x - x')\big)}{\partial x_i}.\]Theo Định lý Cơ bản của Giải tích cho Tích phân Đường,IGlà phương pháp quy gán theo đường đi duy nhất thỏa đồng thời các tiên đề Độ nhạy (Sensitivity), Bất biến Cài đặt (Implementation Invariance), và Đầy đủ (Completeness):\[\sum_{i} \operatorname{IG}_i(x; x') = F(x) - F(x').\]Lưu ý chọn baseline: Nếu chọn nền đen \(x' = \mathbf{0}\), các pixel khuyết tật màu đen (\(x_i = 0\)) sẽ nhận \(\operatorname{IG}_i = 0\) do thừa số \((x_i - x_i')\); trong sản xuất cần kết hợp nền mờ (blur baseline) hoặc kỳ vọng nhiều nền.RISEHộp đen,Deletion / Insertion AUC& Kiểm tra Tỉnh táo Adebayo (2018):RISEước lượng tầm quan trọng không cần gradient qua kỳ vọng \(N_m\) mặt nạ nhị phân ngẫu nhiên phóng to song tuyến tính: \(S_c = \frac{1}{\mathbb{E}[M] N_m}\sum_{m=1}^{N_m} f_c(x \odot M_m)\, M_m\).- Kiểm định Trung thực (
Faithfulness): Một bản đồ giải thích trung thực phải làm xác suất \(f_c\) rơi nhanh nhất khi xóa dần pixel quan trọng nhất (Deletion AUCcàng thấp càng tốt) và phục hồi nhanh nhất khi chèn dần vào ảnh nền trung tính (Insertion AUCcàng cao càng tốt). - Kiểm tra Tỉnh táo Adebayo (NeurIPS 2018): Ngẫu nhiên hóa trọng số các tầng
Conv2d/Linearcủa mạng; phương pháp trung thực (Grad-CAM,IG) phải thay đổi bản đồ rõ rệt (tương quan thấp với bản đồ gốc), ngược lại các phương pháp giả mạo nhưGuided Backpropgiữ nguyên đường biên ảnh bất chấp mô hình đã bị phá hủy hoàn toàn!
Trụ cột 2 — Kiến trúc Hệ thống Thị giác Sản xuất Bền vững & Có thể Kiểm toán#
2.1 Kiến trúc Đường ống Kiểm tra Quang học Biên (AOI Edge Pipeline) & Kiểm soát Rủi ro#
2.2 Vòng lặp Điểm yên ngựa PGD Min–Max & Luồng Hook Grad-CAM#
2.3 Ngân sách Độ trễ, Bộ nhớ, Chi phí & Bảng Quyết định Sản xuất#
| Ràng buộc / Hạng mục | Ngân sách Mục tiêu (AOI Biên CPU) | Kết quả Đo Thực tế (Lab 08) |
Cơ chế Dự phòng & An toàn |
|---|---|---|---|
| Độ trễ suy luận ROI | < 4.0 ms / ROI (>= 250 ROI/s) |
0.319 ms/ảnh (ORT CPU, DW-Sep) |
Gộp batch động hoặc tách luồng intra_op_num_threads |
| Kích thước trọng số | < 100 KB (nằm gọn L2 Cache) |
29,120 B (safetensors), 26,257 B (ONNX) |
Khóa chữ ký SHA-256, tuyệt đối cấm .pt pickle |
| Độ lệch số học xuất biên | < 1e-4 (FP32 ORT parity) |
sf = 0.00e+00, ORT = 2.38e-06 |
Bắt buộc xuất torch.onnx.export(..., dynamo=False) khi thiếu onnxscript |
| Độ bền đối kháng (\(L_\infty\)) | PGD-10 >= 85% tại \(\epsilon = 0.06\) |
99.2% (PGD-AT vs 0.0% StdCNN) |
Kích hoạt ABSTAIN khi Randomized Smoothing \(\underline{p_A} \le 0.5\) |
Cổng kiểm toán Visual XAI |
Del AUC < 0.30, Adebayo PASS |
IG Del = 0.110, GC Del = 0.138 (Rand = 0.688) |
Chặn phát hành nếu Deletion AUC tệ hơn xóa ngẫu nhiên hoặc trượt Adebayo |
2.4 Mẹo Công nghiệp SOTA 2025–2026: Kỷ luật Tiền xử lý Ảnh (EXIF 0x0112, JPEG 4:2:0, INTER_AREA, static camera leak), Hybrid CNN–ViT & Nén KV-Cache Biên (Principal Tip #3a)#
Khi đưa hệ thống kiểm tra quang học AOI hoặc thị giác biên từ môi trường thí nghiệm sạch ra dây chuyền nhà máy/camera thực địa dùng mạng lai CNN–Attention (FastViT, MobileViT) hay Edge VLM (Qwen2.5-VL / InternVL), hầu hết thảm họa suy giảm độ chính xác không nằm ở hàm mất mát mà phát sinh từ 4 bẫy đường ống ảnh và 2 nút thắt băng thông phần cứng:
- Bốn Bẫy Tiền xử lý & Rò rỉ Dữ liệu Thị giác Sản xuất:
- Bẫy Xoay Ngược
EXIF 0x0112(Orientation Metadata Trap): Điện thoại và camera công nghiệp thường lưu ảnh nguyên trạng cảm biến và ghi hướng xoay (90°/180°/270°hoặc lật gương) vào thẻEXIF 0x0112. Khi đọc bằngcv2.imreadđời cũ hoặcPILrồi ép thẳng sangnp.asarray(img)mà quên chuẩn hóa vật lý, ảnh đưa vào mô hình sẽ bị xoay sai chiều so với nhãn bounding box/mask gán trên trình duyệt, tạo sai lệch huấn luyện–suy luận thầm lặng (train-serve skew). Khắc phục: bắt buộc gọiImageOps.exif_transpose()(hoặccv2.IMREAD_COLORchuẩn hóa hướng) và tước sạch thẻEXIFtrước bước resize. - Răng cưa Sắc độ
JPEG 4:2:0(Chroma Subsampling Aliasing): Nén JPEG phổ thông mặc định lấy mẫu giảm sắc độCb/Crtheo khối2×2(JPEG 4:2:0), làm nhòe rìa màu mảnh (1–2 px) và tạo nhiễu khối DCT8×8quanh vết nứt mạch in PCB hay chữ khắc laser. Không bao giờ huấn luyện trên ảnhPNG/4:4:4không nén rồi suy luận trên luồng RTSP nénJPEG 4:2:0mà không kiểm chứng domain parity và mô phỏng nhiễu nén lúc augment. - Chống Răng cưa Nyquist Với
INTER_AREA: Theo định lý lấy mẫu 2D (§1.1), thu nhỏ ảnh độ phân giải cao (4K -> 224×224) bằngINTER_NEARESThoặcINTER_LINEARchỉ gộp trọng số từ1–4điểm ảnh lân cận, bỏ sót phần lớn pixel và kích hoạt răng cưa phổ tần số cao (aliasing) sinh vân moiré giả. Luôn épINTER_AREA(hoặcantialias=Truetrong PyTorch/Pillow) cho mọi phép thu nhỏ kích thước, chỉ dùngINTER_LINEAR/INTER_CUBICkhi phóng lớn. - Rò rỉ Dấu vân tay Nền Tĩnh (
static camera leak): Chia ngẫu nhiên (random frame split) các khung hình rút từ cùng một camera giám sát cố định, băng chuyền AOI hoặc cùng một lộ trình quay video khiến tậptrainvàtestchia sẻ chung nền tĩnh, hạt bụi ống kính hay góc chiếu sáng. Mô hình học thuộc dấu vân tay nền (static camera leak) đạt99%khi kiểm thử nội bộ nhưng sập ngay khi lắp sang dây chuyền/camera mới! Bắt buộc tách tập bằngGroupKFold/ tách thời gian theocamera_id,line_idvàsession_id.
- Bẫy Xoay Ngược
- Rào cản IO Băng thông
FlashAttentionở Đầu vào Độ phân giải Cao: Một ảnh PCB1024×1024cắt lưới16×16sinh tới \(N = 4{,}096\) token; Self-Attention tiêu chuẩn ghi trọn ma trận \(4096 \times 4096\)fp16(33.5 MB/head/lớp) qua lại HBM gây nghẽn băng thông.FlashAttention-2/3chia khốitilingngay trong SRAM trên chip kèm Online Softmax, giảm lưu lượng HBM từ \(\mathcal{O}(N^2)\) xuống \(\mathcal{O}(N)\). Cạm bẫy: dùng mặt nạ chú ý tùy biến không chuẩn hoặc kích thước chiều đầud_headkhông thuộc{64, 128}làm rơi về kernelMathchậm gấp4x. - Nén Token Hình ảnh bằng
GQA& Lượng tử hóaINT8/FP8KV-Cache: Trên thiết bị biên Jetson phục vụ Edge VLM đọc nhiều khung hình liên tiếp (multi-crop AOI), bộ nhớKV-Cachecho token ảnh nhanh chóng vượt RAM trọng số. Chuyển sangGQA(Grouped-Query Attention, chia sẻ K/V cho nhóm \(g\) query head) cắt trực tiếp \(g\times\) lưu lượng nạp KV, và lượng tử hóa KV sangINT8/FP8(per-channel / per-headcho Key) nén tiếp2xbộ nhớ — tránh lượng tử hóa đối xứng toàn tensor vì các chiều ngoại lai (outlier channels) trênKeysẽ làm sụp đổ độ chính xác OCR mã linh kiện PCB.
Trụ cột 3 — Hệ sinh thái 2026 & Mã nguồn Thực thi Chuẩn Mực#
Đoạn mã độc lập dưới đây chạy trực tiếp trong môi trường .venv (PyTorch 2.15.0+cpu, safetensors, onnx, onnxruntime, scipy), tái lập trọn vẹn ba kiểm chứng cốt lõi của Chương 16: (1) Hiệu quả DW-Sep + xuất safetensors/ONNX (dynamo=False), (2) Kiểm chứng biên chuẩn \(L_\infty\) của PGD, và (3) Kiểm chứng tiên đề Completeness của Integrated Gradients cùng hook Grad-CAM:
"""Pillar 3 Executable Specimen: DW-Sep Efficiency, Safetensors/ONNX, PGD Bound & IG Completeness."""
from __future__ import annotations
import json
import tempfile
import warnings
from pathlib import Path
import numpy as np
import onnx
import onnxruntime as ort
import torch
import torch.nn as nn
import torch.nn.functional as F
from safetensors.torch import load as sf_load
from safetensors.torch import save as sf_save
class EdgeDWSepNet(nn.Module):
"""Compact Depthwise-Separable CNN exposing target_conv_layer for Grad-CAM."""
def __init__(self, num_classes: int = 4) -> None:
super().__init__()
self.stem = nn.Sequential(
nn.Conv2d(3, 16, kernel_size=3, padding=1, bias=False),
nn.BatchNorm2d(16),
nn.ReLU(inplace=False),
nn.MaxPool2d(2),
)
self.dw = nn.Conv2d(16, 16, kernel_size=3, padding=1, groups=16, bias=False)
self.pw = nn.Conv2d(16, 32, kernel_size=1, bias=False)
self.bn = nn.BatchNorm2d(32)
self.head = nn.Linear(32, num_classes)
def forward(self, x: torch.Tensor) -> torch.Tensor:
h = self.stem(x)
h = F.relu(self.bn(self.pw(F.relu(self.dw(h)))))
return self.head(h.mean(dim=(2, 3)))
def run_ch16_specimen(seed: int = 42) -> dict[str, float]:
"""Run deterministic offline checks for DW-Sep export, PGD L_inf bound, Grad-CAM & IG axiom."""
torch.manual_seed(seed)
model = EdgeDWSepNet(num_classes=4).eval()
x = torch.rand(4, 3, 32, 32, dtype=torch.float32)
y = torch.tensor([0, 1, 2, 3], dtype=torch.long)
# 1. Zero-pickle safetensors + ONNX (dynamo=False) ORT CPU parity
sf_bytes = sf_save({k: v.detach().cpu().contiguous() for k, v in model.state_dict().items()})
reloaded = EdgeDWSepNet(num_classes=4).eval()
reloaded.load_state_dict(sf_load(sf_bytes), strict=True)
with torch.no_grad():
sf_diff = float((model(x) - reloaded(x)).abs().max().item())
with tempfile.TemporaryDirectory() as td:
onnx_path = Path(td) / "dwsep.onnx"
with warnings.catch_warnings():
warnings.simplefilter("ignore", DeprecationWarning)
torch.onnx.export(
reloaded,
(x[:1],),
str(onnx_path),
dynamo=False,
input_names=["image"],
output_names=["logits"],
dynamic_axes={"image": {0: "batch"}, "logits": {0: "batch"}},
opset_version=17,
)
raw_onnx = onnx_path.read_bytes()
onnx.checker.check_model(onnx.load_model_from_string(raw_onnx))
sess = ort.InferenceSession(raw_onnx, providers=["CPUExecutionProvider"])
with torch.no_grad():
pt_out = reloaded(x).numpy()
ort_out = np.asarray(sess.run(None, {"image": x.numpy()})[0], dtype=np.float32)
ort_diff = float(np.max(np.abs(pt_out - ort_out)))
# 2. 5-step PGD L_inf projection bound verification
eps, alpha = 0.06, 0.02
x_adv = x.clone()
for _ in range(5):
x_adv = x_adv.detach().requires_grad_(True)
loss = F.cross_entropy(reloaded(x_adv), y)
grad = torch.autograd.grad(loss, x_adv)[0]
x_adv = torch.clamp(x + torch.clamp(x_adv.detach() + alpha * grad.sign() - x, -eps, eps), 0.0, 1.0)
max_linf = float((x_adv - x).abs().max().item())
# 3. Integrated Gradients Completeness Axiom: sum(IG) == F(x) - F(0)
x0 = x[:1]
base = torch.zeros_like(x0)
cls_id = int(reloaded(x0).argmax(dim=1).item())
steps = 48
alphas = (torch.arange(steps, dtype=torch.float32) + 0.5) / steps
path = (base + alphas.view(-1, 1, 1, 1) * (x0 - base)).detach().requires_grad_(True)
grads = torch.autograd.grad(reloaded(path)[:, cls_id].sum(), path)[0]
ig = (x0 - base) * grads.mean(dim=0, keepdim=True)
with torch.no_grad():
fx_diff = float((reloaded(x0)[0, cls_id] - reloaded(base)[0, cls_id]).item())
ig_completeness_err = abs(float(ig.sum().item()) - fx_diff)
return {
"safetensors_max_diff": sf_diff,
"ort_max_diff": ort_diff,
"pgd_max_linf": round(max_linf, 6),
"ig_completeness_err": round(ig_completeness_err, 6),
}
if __name__ == "__main__":
print(json.dumps(run_ch16_specimen(seed=42), indent=2))
Trụ cột 4 — Phòng thí nghiệm Thực chiến (Lab 08: cv_cnn_robustness_lab) & Rubric Đánh giá#
4.1 Kiến trúc Hai Tầng (Two-Tier) của Lab 08#
Toàn bộ mã nguồn thực nghiệm đặt tại labs/lab-08-image-processing-101/README.md dưới gói cv_cnn_robustness_lab (100% ngoại tuyến, không cần torchvision/cv2, khóa phụ thuộc bằng uv.lock):
- Tầng 1 (
Reference Corethuần Python /NumPy/SciPy/Pillow):color_and_filters.py: Trình sinh dữ liệuPCB AOI4 lớp (32×32 RGB) kèm mặt nạ vùng khuyết tật thực tế (ROI mask), chuyển đổiRGB -> HSV / YCbCr,HistEqvsCLAHE,conv2d_numpy,Gaussian,Sobel,Laplacian,Canny(NMS+ hysteresis), hình thái học (erode/dilate/open/close),PILround-trip, vàHOG(L2-Hys) + phân loại Ridge tuyến tính.conv_geometry.py: Tính chính xác \(O\), chuỗi đệ quy trường tiếp nhận \(r_l\) & \(j_l\) (có dilation \(D\)), so sánhMACs/Params/Roofline OI giữa tích chập chuẩn vsDW-Sep&Grouped Conv.
- Tầng 2 (
PyTorch 2.15.0+cpu,safetensors,ONNX/ORT,SciPy stats):cnn_models.py:StandardCNNvsDepthwiseSeparableCNN, tăng cườngRandAugment/MixUp/CutMix/Mosaic, huấn luyện CPU nhanh, lưu nạp bất biếnsafetensors(0pickle) và xuấtONNX (dynamo=False)kiểm chứngORT CPU.adversarial.py:FGSM,PGD(\(L_\infty\)),PGD Adversarial Training(Madry min-max) và chứng nhậnRandomized Smoothing(Clopper–Pearson + bán kính Neyman–Pearson \(R\) +ABSTAIN).visual_xai.py:Grad-CAM(forward/backward hooks),Integrated Gradients(kiểm toán Completeness),RISEhộp đen,Deletion / Insertion AUCvà kiểm định ngẫu nhiên hóa trọng số Adebayo.
4.2 Kết quả Thực nghiệm Chuẩn hóa (seed=42, artifacts/ch16_lab08_results.json)#
| Phân hệ Thực nghiệm | Cấu hình / Đối chứng | Chỉ số Đo được (seed=42) |
Kết luận Nghiệm thu |
|---|---|---|---|
Tiền xử lý & HOG (Tầng 1) |
RGB->HSV/YCbCr, CLAHE, Canny, HOG (1764d) + Ridge |
PIL err = 0.0020; CLAHE std = 0.177 (vs HistEq 0.288); HOG Test = 98.3% |
Đường cơ sở cổ điển vững trên crop căn chỉnh |
Số học RF & DW-Sep |
Chuỗi 5 tầng (có conv3 d=2) & khối 48->64 (8×8) |
RF cuối = 26 px (j=4); tỷ lệ DW-Sep = 0.1267 (7.89x MACs); DW OI = 2.10 vs Std 25.41 |
Khớp tuyệt đối lý thuyết \(1/64 + 1/9\) & Roofline |
StandardCNN vs DW-Sep |
360 ảnh train / 120 ảnh test (32×32, 4 lớp PCB) |
StdCNN = 100.0% (39,196 params, 5.09M MACs) vs DW-Sep = 100.0% (6,196 params, 0.98M MACs) |
Giảm 6.33x params, 5.21x MACs, giữ nguyên 100% |
| Đóng gói An toàn Biên | safetensors + ONNX (dynamo=False) + ORT CPU |
sf = 29,120 B (diff = 0.00e+00); ORT = 2.38e-06 (0.319 ms/ảnh) |
0 pickle, vượt xa SLA biên < 4 ms |
Tấn công & PGD-AT |
\(L_\infty\) (\(\epsilon = 0.06\), PGD-10, \(\alpha = 0.015\)) |
StdCNN: Clean 100% \(\to\) FGSM 20.0% \(\to\) PGD-10 0.0%; PGD-AT: Clean 100.0%, PGD-10 99.2% |
Giải cứu +99.2 điểm % độ bền đối kháng |
Chứng nhận RS (\(L_2\)) |
Randomized Smoothing (\(\sigma = 0.10, \alpha = 0.001, n=400\)) |
Certified Acc = 100.0%, bán kính trung bình R = 0.212, abstain = 0/16 |
Chứng chỉ toán học chắc chắn & hỗ trợ ABSTAIN |
Visual XAI Trung thực |
Grad-CAM, IG (M=48), RISE vs Random |
Deletion AUC: IG 0.110, GC 0.138 vs Rand 0.688; Insertion: IG 0.963, GC 0.946 vs Rand 0.682 |
IG Completeness err <= 2.61e-2, Adebayo PASS (0.304/0.596) |
4.3 Hợp đồng 16 Bài kiểm thử Tự động (tests/test_cv_cnn_robustness_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_pydantic_configs_strict_forbid |
Từ chối trường lạ (extra="forbid") và tham số sai miền trên mọi lớp cấu hình |
2 |
test_02_color_spaces_and_clahe_pil_roundtrip |
Khớp tọa độ chuẩn HSV/YCbCr, HistEq/CLAHE nâng tương phản & PIL round-trip chính xác |
3 |
test_03_spatial_filters_sobel_canny_and_morphology |
Gaussian, Sobel, Laplacian, Canny 1-pixel, conv2d_numpy valid/stride, Opening/Closing |
4 |
test_04_hog_descriptor_l2hys_invariance_and_baseline |
HOG đúng 1764 chiều, bất biến tỷ lệ sáng (cosine > 0.99), và độ chính xác Ridge baseline |
5 |
test_05_conv_output_size_and_receptive_field_recurrence |
Khớp chính xác \(O\), đệ quy \(r_l\) và \(j_l\) cho cả tích chập chuẩn, pooling và dilation (\(D=2\)) |
6 |
test_06_depthwise_separable_and_grouped_flops_reduction |
Khớp giải tích \(1/C_{\text{out}} + 1/K^2\), chứng minh DW OI < Std OI và tỷ lệ \(1/G\) |
7 |
test_07_augmentations_randaugment_cutmix_mixup_mosaic |
Miền \([0,1]\), tổng nhãn mềm MixUp/CutMix bằng 1.0, hình học ghép 4 góc Mosaic |
8 |
test_08_standard_vs_dwsep_cnn_training_and_efficiency |
Độ chính xác >= 90% (StdCNN) / >= 88% (DW-Sep), cắt >= 3.0x params & >= 2.5x MACs |
9 |
test_09_safetensors_zero_pickle_and_onnx_ort_parity |
Header <Q + JSON safetensors (diff == 0.0) và ONNX (dynamo=False) ORT (diff < 1e-4) |
10 |
test_10_fgsm_and_pgd_linf_bounds_and_attack_efficacy |
Mọi nhiễu thỏa \(\lVert \delta \rVert_\infty \le \epsilon\), miền \([0,1]\); PGD hạ mạnh độ chính xác StandardCNN |
11 |
test_11_pgd_adversarial_training_rescues_robust_accuracy |
PGD-AT tăng PGD Robust Accuracy >= +25 điểm % so với StandardCNN và giữ Clean >= 80% |
12 |
test_12_randomized_smoothing_certified_radius_and_abstention |
Khớp \(R = \sigma\Phi^{-1}(\underline{p_A})\), Clopper–Pearson đơn điệu và kích hoạt ABSTAIN khi \(\underline{p_A} \le 0.5\) |
13 |
test_13_gradcam_hook_and_roi_localization |
Grad-CAM qua forward/backward hooks chuẩn hóa \([0,1]\) và phân biệt rõ theo lớp đích |
14 |
test_14_integrated_gradients_completeness_axiom |
Kiểm chứng sai số tiên đề Completeness \(|\sum_i \operatorname{IG}_i - (F_c(x) - F_c(x'))| < 0.05\) |
15 |
test_15_visual_xai_deletion_insertion_faithfulness_and_adebayo_sanity |
Grad-CAM & IG vượt trội Random trên Deletion/Insertion AUC, kiểm khói RISE & Adebayo PASS |
16 |
test_16_cli_workbench_schema_and_ast_security_guard |
CLI --quick xuất đủ 6 KPI, 4 bar, 4 table và quét AST cấm mọi module giải tuần tự hóa nguy hiểm |
Trụ cột 5 — Văn liệu Nền tảng, Ôn tập Nhanh & Hệ thống Bài tập Chuyên sâu#
5.1 Sáu Công trình Học thuật Nền tảng & SOTA (1986–2026)#
- Canny, J. (1986), Lowe, D. G. (IJCV 2004) & Dalal, N. & Triggs, B. (CVPR 2005). A Computational Approach to Edge Detection, Distinctive Image Features from Scale-Invariant Keypoints (
SIFT), & Histograms of Oriented Gradients (HOG). (Bộ ba trụ cột tiền xử lý & đặc trưng thị giác cổ điển.) - Howard, A. G. et al. (2017) & Luo, W. et al. (NeurIPS 2016). MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications & Understanding the Effective Receptive Field in Deep Convolutional Neural Networks. (Nền tảng
Depthwise-Separable Convvà phân biệtRFlý thuyết vsERF.) - Cubuk, E. D. et al. (CVPR 2020) & Yun, S. et al. (ICCV 2019). RandAugment: Practical automated data augmentation with a reduced search space & CutMix: Regularization Strategy to Train Strong Classifiers with Localizable Features. (Chuẩn tăng cường dữ liệu hiện đại.)
- Madry, A. et al. (ICLR 2018), Athalye, A. et al. (ICML 2018) & Croce, F. & Hein, M. (ICML 2020 —
AutoAttack/RobustBench). Towards Deep Learning Models Resistant to Adversarial Attacks, Obfuscated Gradients Give a False Sense of Security, & Reliable evaluation of adversarial robustness with an ensemble of diverse parameter-free attacks. - Cohen, J. M., Rosenfeld, E., & Kolter, J. Z. (ICML 2019). Certified Adversarial Robustness via Randomized Smoothing. (Định lý Neyman–Pearson cấp chứng chỉ \(L_2\) không phụ thuộc kiến trúc mạng.)
- Selvaraju, R. R. et al. (ICCV 2017), Sundararajan, M. et al. (ICML 2017), Petsiuk, V. et al. (BMVC 2018) & Adebayo, J. et al. (NeurIPS 2018). Grad-CAM, Axiomatic Attribution for Deep Networks (
IG),RISE(Deletion/Insertion AUC) & Sanity Checks for Saliency Maps.
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(Không gian Màu, Nyquist &CLAHE): Tách kênh chóiYCbCr+CLAHEcục bộ tránh làm lệch sắc độ và chặn khuếch đại nhiễu đồng nhất (std = 0.177vsGlobal HistEq 0.288trongLab 08); cần lọc thông thấp Gaussian trước khi hạ phân giải để tránh răng cưa Nyquist 2D.Q2(Canny, Hình thái học &HOGL2-Hys):CannydùngNMSdọc pháp tuyến làm mảnh biên còn1pixel và hysteresis nối biên yếu;Openingxóa nhiễu đốm trắng,Closinglấp lỗ tối;HOGchuẩn hóa khốiL2-Hysgiúp bất biến tỷ lệ sáng cục bộ (cosine > 0.99,1764chiều trên ảnh32×32, đạt98.3%đường cơ sở).Q3(Số học Tích chập & Trường Tiếp nhận Giãn): Kích thước đầu ra tuân theo \(O = \lfloor(W + 2P - D(K-1) - 1)/S\rfloor + 1\) và đệ quy trường tiếp nhận \(r_l = r_{l-1} + (k_l - 1)d_l j_{l-1}\) (chuỗi 5 tầngLab 08đạtRF = 26 px, \(j = 4\)).Q4(Depthwise-Separable Conv& Bẫy Roofline): Tỷ lệ MACs là \(1/C_{\text{out}} + 1/K^2\) (0.1267/7.89xtrên khối48->64;6.33xparams,5.21xMACs toàn mạngLab 08, giữ100%độ chính xác ở0.319 msORT CPU), nhưngOItầng Depthwise chỉ2.10FLOPs/byte (bị nghẽn băng thông trên GPU nếu thiếu kernel fusion).Q5(RandAugment,CutMix,MixUp,Mosaic):CutMixghép mảng chữ nhật theo tỷ lệ diện tích \(\lambda = 1 - |M|/(HW)\) buộc mạng nhận diện từ nhiều vùng phân tán;MixUplàm trơn biên và cải thiện hiệu chuẩn;Mosaicghép 4 ảnh tăng ngữ cảnh vật nhỏ.Q6(FGSM,PGD,Obfuscated Gradients&PGD-AT): Dưới \(L_\infty\) (\(\epsilon = 0.06\)),StandardCNNrơi từ100%xuống20.0%(FGSM) và0.0%(PGD-10); phòng thủ che khuất gradient thất bại trướcBPDA/AutoAttack, còn Min–MaxPGD-ATgiải cứu lên99.2%(+99.2 pp).Q7(Randomized Smoothing&ABSTAIN): Định lý Cohen et al. cấp chứng chỉ \(L_2\) chắc chắn với bán kính \(R = \sigma_{\text{rs}}\Phi^{-1}(\underline{p_A})\) dùng cận dưới Clopper–Pearson (R = 0.212,Cert Acc = 100%ở \(\sigma = 0.10, \alpha = 0.001\) trongLab 08) và bắt buộcABSTAINkhi \(\underline{p_A} \le 0.5\).Q8(Grad-CAM,IG Completeness,Deletion/Insertion& Adebayo):IGthỏa tiên đề Completeness \(\sum \operatorname{IG}_i = F(x)-F(x')\) (sai số tối đa2.61e-2trongLab 08), cảIG(Del 0.110,Ins 0.963) lẫnGrad-CAM(Del 0.138,Ins 0.946) vượt xaRandom(Del 0.688,Ins 0.682) và vượt qua kiểm định Adebayo (|r| = 0.304 / 0.596).
5.3 Sáu Bài tập Chuyên sâu & Thang chấm Rubric (ex1..ex6)#
- Bài tập 1 (
15%) — Không gian Màu,CLAHE, Hình thái học & Bất biếnHOG(L2-Hys): Chứng minh vì sao cân bằng histogram trênYCbCr(kênh \(Y\)) bảo toàn sắc độ tốt hơnRGB, thiết kế chuỗiOpening\(\to\)Closingloại nhiễu bụi và lấp lỗ hàn, và chứng minh toán học tính bất biến tỷ lệ sáng củaHOGchuẩn hóaL2-Hys(kiểm chứng quaTests 02–04). - Bài tập 2 (
15%) — Đệ quy Trường Tiếp nhận có Dilation & Nghịch lý Roofline củaDW-Sep: Chứng minh quy nạp công thức \(r_l = r_{l-1} + (k_l - 1)d_l j_{l-1}\), tính tay \(r_l, j_l\) cho chuỗi 5 tầng củaLab 08(xác nhận \(r_5 = 26\)), dẫn xuất tỷ lệ \(1/C_{\text{out}} + 1/K^2\), và phân tích cường độ số họcOI(2.10vs25.41FLOPs/byte) trênTests 05–06. - Bài tập 3 (
15%) — So sánhStandardCNNvsDepthwiseSeparableCNN,Augmentation& Đóng góisafetensors/ONNX: Cài đặt và đối chiếu hiệu quả tham số/MACs (6.33x/5.21x), kiểm tra bảo toàn nhãn mềm củaMixUp/CutMix, và xác thực chuỗi cung ứng biênsafetensors(0pickle,diff = 0.0) +ONNX (dynamo=False)(ORT diff < 1e-4,Tests 07–09). - Bài tập 4 (
20%) — Tấn côngFGSM/PGD, Che khuất Gradient & Huấn luyện Điểm yên ngựaPGD-AT: Chứng minhFGSMlà nghiệm cực đại hóa tuyến tính bậc 1 trên quả cầu \(L_\infty\), giải thích vì sao phòng thủ nén JPEG thất bại trướcBPDA/AutoAttack, và thực nghiệm chứng minhPGD-ATgiải cứu độ bền từ0.0% -> 99.2%(Tests 10–11). - Bài tập 5 (
15%) — Chứng nhận Bền vững \(L_2\) quaRandomized Smoothing& Cơ chếABSTAIN: Thiết lập mối liên hệ giữa Bổ đề Neyman–Pearson, cận dưới nhị thức Clopper–Pearson \(\underline{p_A}\) và bán kính \(R = \sigma_{\text{rs}}\Phi^{-1}(\underline{p_A})\); phân tích đánh đổi giữa \(\sigma_{\text{rs}}\) (tăng \(R\) tối đa vs giảm độ chính xác sạch) và kiểm chứng hành viABSTAINkhi \(\underline{p_A} \le 0.5\) (Test 12). - Bài tập 6 (
20%) — Kiểm toán Trung thựcVisual XAI(Grad-CAM,IG,RISE,Deletion/Insertion, Adebayo) & Chạy Toàn trìnhLab 08: Chứng minh tiên đề Completeness củaIntegrated Gradients, phân tích bẫy nền đen \(x' = \mathbf{0}\) trên lỗi lỗ rỗng tối màu (Missing_Pad_Void), thực thi kiểm địnhDeletion/Insertion AUC+ Adebayo (Tests 13–15), và hoàn tất trọn bộ16/16 pytest+ruff+mypy+scripts/run_lab_demo.py.
| Tiêu chí Rubric | Đạt (Pass, 60–74%) |
Khá (Merit, 75–84%) |
Xuất sắc (Distinction, 85–100%) |
|---|---|---|---|
Chứng minh Toán học (ex1, ex2, ex4, ex5) |
Viết đúng công thức RF, DW-Sep, FGSM, RS |
Chứng minh đầy đủ bước biến đổi đại số và biên chuẩn \(L_\infty/L_2\) | Phân tích sắc sảo Roofline OI, obfuscated gradients và đánh đổi \(\sigma_{\text{rs}}\) |
Thực nghiệm & Kiểm thử (Lab 08) |
Vượt qua 16/16 pytest, xuất đúng JSON |
Đạt 0 lỗi ruff/mypy, kiểm toán đủ safetensors/ONNX/PGD-AT |
Trình bày trọn vẹn phân tích Deletion/Insertion AUC, IG Completeness, Adebayo và mở rộng kiểm chứng blur baseline |
| Kiến trúc Sản xuất | Mô tả được luồng camera \(\to\) CNN \(\to\) XAI | Định lượng được SLA độ trễ, dung lượng L2 cache & cổng ABSTAIN |
Thiết kế hoàn chỉnh cổng CI/CD chặn phát hành khi rò rỉ đường tắt hoặc trượt kiểm toán đối kháng |
PCB Defect Classification Accuracy: Classical HOG vs CNN Backbones (%)
Compute Footprint: Standard 2D Conv vs Depthwise-Separable CNN (kMACs)
Adversarial Robustness Under L_inf Attack (eps=0.06): Standard vs PGD-AT (%)
Visual XAI Faithfulness: Deletion AUC (Low) vs Insertion AUC (High)
Tier 1 Classical Image Processing, Morphology & HOG Baseline
| Operator / Pipeline | Output Shape / Dim | Observed Property | Status |
|---|---|---|---|
| RGB -> HSV / YCbCr / PIL Round-Trip | 32x32x3 | PIL uint8 max err = 0.0020 (Y mean=0.213) | PASS |
| Global HistEq vs CLAHE (4x4, clip=2.5) | 32x32 | Std: raw 0.135 -> HistEq 0.288 | CLAHE 0.177 | PASS |
| Gaussian + Sobel + Canny + Open/Close | 32x32 | Canny px=107 | Open=0 | Close=224 | PASS |
| HOG (cell=4, block=2x2, 9 bins, L2-Hys) + Ridge | 1764 dims | Train 100.0% | Test 98.3% | BASELINE |
Exact Convolution Receptive-Field Recurrence & DW-Sep / Grouped Reduction
| Layer / Comparison | Out Spatial | Receptive Field / Jump | Params & MACs |
|---|---|---|---|
| conv1_3x3 | 32x32 | RF=3 px (j=1) | 648 params | 663,552 MACs |
| pool1_2x2 | 16x16 | RF=4 px (j=2) | 0 params | 0 MACs |
| conv2_3x3 | 16x16 | RF=8 px (j=2) | 10,368 params | 2,654,208 MACs |
| pool2_2x2 | 8x8 | RF=10 px (j=4) | 0 params | 0 MACs |
| conv3_3x3_d2 | 8x8 | RF=26 px (j=4) | 27,648 params | 1,769,472 MACs |
| Block 48->64 (3x3): Std vs DW-Sep | 8x8 | Ratio 0.1267 (Theory 0.1267) | 7.89x MACs | Grouped(G=4)=0.25x |
CNN Efficiency, Zero-Pickle Deployment & Adversarial Robustness Audit
| Model / Regime | Clean Acc | FGSM / PGD-10 (eps=0.06) | Deployment / Cert |
|---|---|---|---|
| StandardCNN (RandAugment) | 100.0% (F1 100.0%) | FGSM 20.0% | PGD 0.0% | 39,196 params | 5,087,488 MACs |
| DepthwiseSeparableCNN (Edge) | 100.0% (F1 100.0%) | 5.21x fewer MACs (6.33x params) | sf diff=0.0e+00 | ORT 2.38e-06 (0.092 ms) |
| PGD Adversarial Trained CNN (Madry) | 100.0% | FGSM 100.0% | PGD 99.2% (+99.2 pp) | L_inf max=0.0600 <= 0.06 |
| Randomized Smoothing (sigma=0.1) | Cert Acc 100.0% | Mean L2 Radius R = 0.2117 | Clopper-Pearson alpha=0.001 | Abstain 0/16 |
Visual XAI Faithfulness (Deletion/Insertion AUC), Completeness & Adebayo Sanity
| XAI Method | Deletion AUC (Low) | Insertion AUC (High) | Axiom / Sanity Check |
|---|---|---|---|
| Grad-CAM (Forward/Backward Hook) | 0.1382 | 0.9457 | Adebayo corr=0.304 | ROI energy=21.8% |
| Integrated Gradients (M=48) | 0.1100 | 0.9627 | Completeness err=2.61e-02 | Adebayo=0.596 |
| RISE Black-Box (N=120) | 0.2818 | 0.9138 | Gradient-free Monte Carlo occlusion |
| Random Pixel Masking Baseline | 0.6882 | 0.6816 | Reference uninformative baseline |
02-track-1-data-science-and-ai/part-03-deep-learning-and-modern-cv/labs/lab-08-image-processing-101
[build-system]
requires = ["setuptools>=68.0"]
build-backend = "setuptools.build_meta"
[project]
name = "cv-cnn-robustness-lab"
version = "0.1.0"
description = "Lab 08: Image Processing 101, Classical Descriptors (HOG), CNN Arithmetic & Depthwise-Separable Efficiency, Adversarial Attacks/Training/Randomized Smoothing, and Visual XAI Faithfulness (T1-P3-U03)."
readme = "README.md"
requires-python = ">=3.12"
dependencies = [
"numpy>=1.26",
"onnx>=1.16",
"onnxruntime>=1.18",
"pillow>=10.0",
"pydantic>=2.0",
"safetensors>=0.4",
"scipy>=1.12",
"torch>=2.5",
]
[project.optional-dependencies]
dev = [
"mypy>=1.11",
"pytest>=8.0",
"ruff>=0.6",
]
[[tool.uv.index]]
name = "pytorch-cpu"
url = "https://download.pytorch.org/whl/cpu"
explicit = true
[tool.uv.sources]
torch = { index = "pytorch-cpu" }
[tool.setuptools]
package-dir = {"" = "src"}
[tool.setuptools.packages.find]
where = ["src"]
[tool.pytest.ini_options]
pythonpath = ["src"]
testpaths = ["tests"]
addopts = "-v"
[tool.ruff]
line-length = 110
target-version = "py312"
[tool.ruff.lint]
select = ["E", "F", "I", "UP", "B"]
[tool.mypy]
python_version = "3.12"
ignore_missing_imports = true
warn_unused_ignores = true
"""Lab 08 (`T1-P3-U03`): Image Processing 101, CNN Arithmetic, Adversarial Robustness & Visual XAI."""
from __future__ import annotations
from cv_cnn_robustness_lab.adversarial import (
AdversarialConfig,
SmoothingConfig,
certify_randomized_smoothing,
evaluate_adversarial_accuracy,
fgsm_attack,
pgd_linf_attack,
train_pgd_adversarial_cnn,
)
from cv_cnn_robustness_lab.cnn_models import (
DepthwiseSeparableCNN,
StandardCNN,
TrainConfig,
apply_cutmix_batch,
apply_mixup_batch,
apply_randaugment_batch,
build_mosaic_quad,
evaluate_cnn_classifier,
export_and_verify_onnx_parity,
load_cnn_safetensors,
save_cnn_safetensors,
train_cnn_classifier,
)
from cv_cnn_robustness_lab.color_and_filters import (
CLASS_NAMES,
DatasetConfig,
HOGConfig,
array_to_pil_and_back,
binary_close,
binary_dilate,
binary_erode,
binary_open,
canny_hysteresis_edges,
clahe_tile_equalize,
conv2d_numpy,
evaluate_hog_linear_baseline,
extract_hog_descriptor,
gaussian_blur,
gaussian_kernel_2d,
generate_aoi_pcb_dataset,
histogram_equalize_uint8,
laplacian_filter,
rgb_to_grayscale,
rgb_to_hsv,
rgb_to_ycbcr,
sobel_edges,
)
from cv_cnn_robustness_lab.conv_geometry import (
ConvLayerSpec,
compare_standard_vs_dwsep_conv,
compute_grouped_conv_stats,
compute_receptive_field_stack,
conv_output_size,
)
from cv_cnn_robustness_lab.visual_xai import (
XAIConfig,
check_adebayo_weight_randomization_sanity,
compute_gradcam,
compute_integrated_gradients,
compute_rise_saliency,
evaluate_deletion_insertion_auc,
)
__all__ = [
"CLASS_NAMES",
"AdversarialConfig",
"ConvLayerSpec",
"DatasetConfig",
"DepthwiseSeparableCNN",
"HOGConfig",
"SmoothingConfig",
"StandardCNN",
"TrainConfig",
"XAIConfig",
"apply_cutmix_batch",
"apply_mixup_batch",
"apply_randaugment_batch",
"array_to_pil_and_back",
"binary_close",
"binary_dilate",
"binary_erode",
"binary_open",
"build_mosaic_quad",
"canny_hysteresis_edges",
"certify_randomized_smoothing",
"check_adebayo_weight_randomization_sanity",
"clahe_tile_equalize",
"compare_standard_vs_dwsep_conv",
"compute_gradcam",
"compute_grouped_conv_stats",
"compute_integrated_gradients",
"compute_receptive_field_stack",
"compute_rise_saliency",
"conv2d_numpy",
"conv_output_size",
"evaluate_adversarial_accuracy",
"evaluate_cnn_classifier",
"evaluate_deletion_insertion_auc",
"evaluate_hog_linear_baseline",
"export_and_verify_onnx_parity",
"extract_hog_descriptor",
"fgsm_attack",
"gaussian_blur",
"gaussian_kernel_2d",
"generate_aoi_pcb_dataset",
"histogram_equalize_uint8",
"laplacian_filter",
"load_cnn_safetensors",
"pgd_linf_attack",
"rgb_to_grayscale",
"rgb_to_hsv",
"rgb_to_ycbcr",
"save_cnn_safetensors",
"sobel_edges",
"train_cnn_classifier",
"train_pgd_adversarial_cnn",
]
"""Tier 1 (NumPy/SciPy/Pillow): Industrial PCB AOI synthetic dataset, color spaces, spatial filters & HOG."""
from __future__ import annotations
from collections import deque
from typing import Any
import numpy as np
from numpy.typing import NDArray
from PIL import Image
from pydantic import BaseModel, ConfigDict, Field
from scipy import ndimage
CLASS_NAMES: tuple[str, ...] = (
"Normal_IC_Package",
"Solder_Bridge_Defect",
"Surface_Scratch_Crack",
"Missing_Pad_Void",
)
class DatasetConfig(BaseModel):
"""Strict configuration for deterministic industrial PCB AOI dataset generation."""
model_config = ConfigDict(extra="forbid")
image_size: int = Field(default=32, ge=16, le=64)
n_train_per_class: int = Field(default=90, ge=12, le=500)
n_test_per_class: int = Field(default=30, ge=8, le=200)
noise_std: float = Field(default=0.035, ge=0.0, le=0.25)
max_shift_px: int = Field(default=3, ge=0, le=6)
seed: int = Field(default=42, ge=0)
class HOGConfig(BaseModel):
"""Strict configuration for Histogram of Oriented Gradients (Dalal & Triggs 2005)."""
model_config = ConfigDict(extra="forbid")
cell_size: int = Field(default=4, ge=2, le=16)
block_cells: int = Field(default=2, ge=1, le=4)
num_bins: int = Field(default=9, ge=4, le=18)
l2_hys_clip: float = Field(default=0.2, gt=0.0, le=1.0)
eps: float = Field(default=1e-6, gt=0.0, le=1e-2)
def _render_pcb_sample(
label: int,
size: int,
rng: np.random.Generator,
noise_std: float,
max_shift_px: int,
) -> tuple[NDArray[np.float32], NDArray[np.float32]]:
"""Render one 3xHxW RGB industrial IC/PCB inspection image in [0, 1] plus HxW defect/target ROI mask."""
h = size
w = size
yy, xx = np.mgrid[0:h, 0:w]
# PCB fiberglass dark-green substrate with subtle woven trace texture
img = np.zeros((h, w, 3), dtype=np.float32)
base_gain = float(rng.uniform(0.84, 1.16))
tint_r = float(rng.uniform(-0.025, 0.025))
tint_b = float(rng.uniform(-0.025, 0.025))
substrate = np.array([0.08 + tint_r, 0.25, 0.13 + tint_b], dtype=np.float32) * base_gain
img[:, :, :] = substrate
# Subtle copper micro-traces on substrate
trace_mask = ((yy % 6 == 1) | (xx % 8 == 2)) & ((xx + yy) % 3 != 0)
img[trace_mask] += np.array([0.03, 0.05, 0.02], dtype=np.float32) * base_gain
# Random translation of the IC package inside the inspection ROI
dx = int(rng.integers(-max_shift_px, max_shift_px + 1)) if max_shift_px > 0 else 0
dy = int(rng.integers(-max_shift_px, max_shift_px + 1)) if max_shift_px > 0 else 0
cx = w // 2 + dx
cy = h // 2 + dy
half_w = max(5, w // 4)
half_h = max(5, h // 4)
x0, x1 = max(3, cx - half_w), min(w - 3, cx + half_w)
y0, y1 = max(3, cy - half_h), min(h - 3, cy + half_h)
# Dark epoxy IC package body with slight chamfer highlight
img[y0:y1, x0:x1, 0] = 0.14 * base_gain
img[y0:y1, x0:x1, 1] = 0.15 * base_gain
img[y0:y1, x0:x1, 2] = 0.18 * base_gain
# Subtle crisp package border
img[y0 : y0 + 1, x0:x1] += 0.08 * base_gain
img[y1 - 1 : y1, x0:x1] += 0.05 * base_gain
# Metallic gull-wing solder pins along top and bottom edges (4 pins each side)
pin_color = np.array([0.74, 0.77, 0.80], dtype=np.float32) * base_gain
pin_xs = np.linspace(x0 + 1, x1 - 3, 4).astype(int)
top_y0, top_y1 = max(1, y0 - 3), y0
bot_y0, bot_y1 = y1, min(h - 1, y1 + 3)
for px in pin_xs:
img[top_y0:top_y1, px : px + 2] = pin_color
img[bot_y0:bot_y1, px : px + 2] = pin_color
# Gold corner fiducial pad (top-left inside chip)
pad_color = np.array([0.88, 0.72, 0.22], dtype=np.float32) * base_gain
pad_y0, pad_y1 = y0 + 2, min(y1 - 1, y0 + 5)
pad_x0, pad_x1 = x0 + 2, min(x1 - 1, x0 + 5)
img[pad_y0:pad_y1, pad_x0:pad_x1] = pad_color
roi_mask = np.zeros((h, w), dtype=np.float32)
if label == 0:
# Normal IC package: ROI is the crisp gold fiducial + healthy body center
roi_mask[y0:y1, x0:x1] = 1.0
elif label == 1:
# Solder Bridge Defect: thick bright metallic horizontal blob shorting adjacent pins
side_top = bool(rng.integers(0, 2) == 0)
pair_idx = int(rng.integers(0, 3))
bx0 = max(1, int(pin_xs[pair_idx]) - 1)
bx1 = min(w - 1, int(pin_xs[pair_idx + 1]) + 3)
by0 = max(0, top_y0 - 1) if side_top else bot_y0
by1 = min(h, top_y1 + 1) if side_top else min(h, bot_y1 + 1)
bridge_color = np.array([0.95, 0.96, 0.99], dtype=np.float32) * min(1.05, base_gain)
img[by0:by1, bx0:bx1] = bridge_color
# Bright specular core inside the solder bridge
img[by0 : min(by1, by0 + 2), bx0 + 1 : max(bx0 + 2, bx1 - 1)] = 0.99
roi_mask[max(0, by0 - 1) : min(h, by1 + 1), max(0, bx0 - 1) : min(w, bx1 + 1)] = 1.0
elif label == 2:
# Surface Scratch / Micro-Crack: high-contrast diagonal scratch cutting across IC body
slope = float(rng.choice([-1.0, 1.0])) * float(rng.uniform(0.75, 1.25))
offset = float(rng.uniform(-2.0, 2.0))
dist = np.abs((yy - cy) - slope * (xx - cx) - offset) / np.sqrt(1.0 + slope * slope)
in_body = (xx >= x0 + 1) & (xx < x1 - 1) & (yy >= y0 + 1) & (yy < y1 - 1)
scratch = in_body & (dist <= 1.15)
img[scratch] = np.array([0.92, 0.42, 0.28], dtype=np.float32) * min(1.05, base_gain)
roi_mask[in_body & (dist <= 2.0)] = 1.0
elif label == 3:
# Missing Pad & Dark Void Crater: remove gold pad and carve a bright-rimmed dark circular void
img[pad_y0:pad_y1, pad_x0:pad_x1] = np.array([0.04, 0.04, 0.06], dtype=np.float32)
vx = cx + int(rng.integers(-2, 3))
vy = cy + int(rng.integers(-2, 3))
r2 = (xx - vx) ** 2 + (yy - vy) ** 2
outer_rim = (r2 <= 18.0) & (r2 >= 8.0)
inner_void = r2 < 8.0
img[outer_rim] = np.array([0.28, 0.62, 0.94], dtype=np.float32) * min(1.05, base_gain)
img[inner_void] = np.array([0.02, 0.02, 0.03], dtype=np.float32)
roi_mask[r2 <= 22.0] = 1.0
roi_mask[pad_y0:pad_y1, pad_x0:pad_x1] = 1.0
else:
raise ValueError(f"Unsupported class label: {label}")
# Subtle linear illumination gradient across inspection chamber + sensor Gaussian noise
grad_x = float(rng.uniform(-0.07, 0.07))
grad_y = float(rng.uniform(-0.07, 0.07))
illum = 1.0 + grad_x * ((xx / max(1, w - 1)) - 0.5) + grad_y * ((yy / max(1, h - 1)) - 0.5)
img = img * illum[:, :, None]
if noise_std > 0.0:
img = img + rng.normal(0.0, noise_std, size=img.shape).astype(np.float32)
img = np.clip(img, 0.0, 1.0).astype(np.float32)
# Return CHW layout (3, H, W) matching PyTorch convention
return np.transpose(img, (2, 0, 1)).copy(), roi_mask
def generate_aoi_pcb_dataset(config: DatasetConfig | None = None) -> dict[str, Any]:
"""Generate deterministic train/test splits of 4-class PCB AOI images and defect ROI masks."""
cfg = config or DatasetConfig()
rng = np.random.default_rng(cfg.seed)
n_classes = len(CLASS_NAMES)
def _build_split(n_per_class: int) -> tuple[NDArray[np.float32], NDArray[np.int64], NDArray[np.float32]]:
total = n_per_class * n_classes
xs = np.zeros((total, 3, cfg.image_size, cfg.image_size), dtype=np.float32)
ys = np.zeros((total,), dtype=np.int64)
masks = np.zeros((total, cfg.image_size, cfg.image_size), dtype=np.float32)
idx = 0
for cls_id in range(n_classes):
for _ in range(n_per_class):
img, mask = _render_pcb_sample(
label=cls_id,
size=cfg.image_size,
rng=rng,
noise_std=cfg.noise_std,
max_shift_px=cfg.max_shift_px,
)
xs[idx] = img
ys[idx] = cls_id
masks[idx] = mask
idx += 1
perm = rng.permutation(total)
return xs[perm], ys[perm], masks[perm]
x_train, y_train, mask_train = _build_split(cfg.n_train_per_class)
x_test, y_test, mask_test = _build_split(cfg.n_test_per_class)
return {
"x_train": x_train,
"y_train": y_train,
"mask_train": mask_train,
"x_test": x_test,
"y_test": y_test,
"mask_test": mask_test,
"class_names": list(CLASS_NAMES),
"config": cfg.model_dump(),
}
def _ensure_hwc_float(rgb: NDArray[np.floating[Any]]) -> NDArray[np.float32]:
arr = np.asarray(rgb, dtype=np.float32)
if arr.ndim != 3:
raise ValueError(f"Expected 3D RGB array, got shape {arr.shape}")
if arr.shape[0] == 3 and arr.shape[2] != 3:
arr = np.transpose(arr, (1, 2, 0))
if arr.shape[2] != 3:
raise ValueError(f"Expected 3 color channels, got shape {arr.shape}")
return np.clip(arr, 0.0, 1.0)
def rgb_to_grayscale(rgb: NDArray[np.floating[Any]]) -> NDArray[np.float32]:
"""Convert RGB image (H, W, 3) or (3, H, W) in [0, 1] to BT.601 luminance grayscale (H, W)."""
hwc = _ensure_hwc_float(rgb)
gray = 0.299 * hwc[:, :, 0] + 0.587 * hwc[:, :, 1] + 0.114 * hwc[:, :, 2]
return np.clip(gray, 0.0, 1.0).astype(np.float32)
def rgb_to_hsv(rgb: NDArray[np.floating[Any]]) -> NDArray[np.float32]:
"""Convert RGB image in [0, 1] to HSV (H in [0, 360), S in [0, 1], V in [0, 1]), shape (H, W, 3)."""
hwc = _ensure_hwc_float(rgb)
r, g, b = hwc[:, :, 0], hwc[:, :, 1], hwc[:, :, 2]
c_max = np.maximum(np.maximum(r, g), b)
c_min = np.minimum(np.minimum(r, g), b)
delta = c_max - c_min
h = np.zeros_like(c_max, dtype=np.float32)
nz = delta > 1e-8
mask_r = nz & (c_max == r)
mask_g = nz & (c_max == g) & (~mask_r)
mask_b = nz & (~mask_r) & (~mask_g)
h[mask_r] = 60.0 * (((g[mask_r] - b[mask_r]) / delta[mask_r]) % 6.0)
h[mask_g] = 60.0 * (((b[mask_g] - r[mask_g]) / delta[mask_g]) + 2.0)
h[mask_b] = 60.0 * (((r[mask_b] - g[mask_b]) / delta[mask_b]) + 4.0)
h = np.mod(h, 360.0)
s = np.where(c_max > 1e-8, delta / np.maximum(c_max, 1e-8), 0.0).astype(np.float32)
v = c_max.astype(np.float32)
return np.stack([h, s, v], axis=-1)
def rgb_to_ycbcr(rgb: NDArray[np.floating[Any]]) -> NDArray[np.float32]:
"""Convert RGB image in [0, 1] to BT.601 normalized YCbCr in [0, 1], shape (H, W, 3)."""
hwc = _ensure_hwc_float(rgb)
r, g, b = hwc[:, :, 0], hwc[:, :, 1], hwc[:, :, 2]
y = 0.299 * r + 0.587 * g + 0.114 * b
cb = -0.168736 * r - 0.331264 * g + 0.500000 * b + 0.5
cr = 0.500000 * r - 0.418688 * g - 0.081312 * b + 0.5
return np.clip(np.stack([y, cb, cr], axis=-1), 0.0, 1.0).astype(np.float32)
def array_to_pil_and_back(rgb: NDArray[np.floating[Any]]) -> NDArray[np.float32]:
"""Round-trip an RGB float array [0, 1] through Pillow uint8 Image and back to HWC float32."""
hwc = _ensure_hwc_float(rgb)
u8 = np.rint(hwc * 255.0).astype(np.uint8)
pil_img = Image.fromarray(u8, mode="RGB")
restored = np.asarray(pil_img, dtype=np.float32) / 255.0
return restored
def histogram_equalize_uint8(gray: NDArray[np.floating[Any]]) -> NDArray[np.float32]:
"""Global histogram equalization on a grayscale [0, 1] image."""
u8 = np.rint(np.clip(gray, 0.0, 1.0) * 255.0).astype(np.uint8)
hist = np.bincount(u8.ravel(), minlength=256).astype(np.float64)
cdf = np.cumsum(hist)
cdf_nz = cdf[cdf > 0]
if cdf_nz.size == 0 or cdf[-1] == cdf_nz[0]:
return u8.astype(np.float32) / 255.0
lut = np.rint(((cdf - cdf_nz[0]) / (cdf[-1] - cdf_nz[0])) * 255.0)
lut = np.clip(lut, 0.0, 255.0).astype(np.uint8)
return lut[u8].astype(np.float32) / 255.0
def clahe_tile_equalize(
gray: NDArray[np.floating[Any]],
grid_size: int = 4,
clip_limit: float = 2.5,
) -> NDArray[np.float32]:
"""Contrast-Limited Adaptive Histogram Equalization (CLAHE) with bilinear tile blending."""
arr = np.clip(np.asarray(gray, dtype=np.float32), 0.0, 1.0)
h, w = arr.shape
u8 = np.rint(arr * 255.0).astype(np.uint8)
g = max(1, min(grid_size, h // 4, w // 4))
th = max(1, h // g)
tw = max(1, w // g)
luts = np.zeros((g, g, 256), dtype=np.float32)
for ty in range(g):
y0 = ty * th
y1 = h if ty == g - 1 else (ty + 1) * th
for tx in range(g):
x0 = tx * tw
x1 = w if tx == g - 1 else (tx + 1) * tw
tile = u8[y0:y1, x0:x1]
hist = np.bincount(tile.ravel(), minlength=256).astype(np.float64)
limit = max(1.0, clip_limit * (tile.size / 256.0))
excess = np.maximum(hist - limit, 0.0).sum()
hist = np.minimum(hist, limit) + excess / 256.0
cdf = np.cumsum(hist)
cdf = (cdf - cdf[0]) / max(float(cdf[-1] - cdf[0]), 1e-8)
luts[ty, tx] = np.clip(cdf, 0.0, 1.0).astype(np.float32)
# Bilinear interpolation across tile centers
cy = np.array([(ty + 0.5) * (h / g) for ty in range(g)], dtype=np.float32)
cx = np.array([(tx + 0.5) * (w / g) for tx in range(g)], dtype=np.float32)
out = np.zeros((h, w), dtype=np.float32)
for y in range(h):
yf = (y - cy[0]) / max(float(h / g), 1e-6)
y_lo = int(np.clip(np.floor(yf), 0, g - 1))
y_hi = min(g - 1, y_lo + 1)
wy = float(np.clip(yf - y_lo, 0.0, 1.0)) if y_hi != y_lo else 0.0
for x in range(w):
xf = (x - cx[0]) / max(float(w / g), 1e-6)
x_lo = int(np.clip(np.floor(xf), 0, g - 1))
x_hi = min(g - 1, x_lo + 1)
wx = float(np.clip(xf - x_lo, 0.0, 1.0)) if x_hi != x_lo else 0.0
val = int(u8[y, x])
v00 = luts[y_lo, x_lo, val]
v01 = luts[y_lo, x_hi, val]
v10 = luts[y_hi, x_lo, val]
v11 = luts[y_hi, x_hi, val]
out[y, x] = (
(1.0 - wy) * ((1.0 - wx) * v00 + wx * v01)
+ wy * ((1.0 - wx) * v10 + wx * v11)
)
return np.clip(out, 0.0, 1.0).astype(np.float32)
def conv2d_numpy(
image: NDArray[np.floating[Any]],
kernel: NDArray[np.floating[Any]],
padding: str = "same",
stride: int = 1,
) -> NDArray[np.float32]:
"""Pure-NumPy 2D cross-correlation supporting 'same' and 'valid' padding with arbitrary stride."""
if stride < 1:
raise ValueError("stride must be >= 1")
img = np.asarray(image, dtype=np.float32)
ker = np.asarray(kernel, dtype=np.float32)
if img.ndim != 2 or ker.ndim != 2:
raise ValueError("conv2d_numpy expects 2D image and 2D kernel")
kh, kw = ker.shape
if padding == "same":
pad_h = kh // 2
pad_w = kw // 2
padded = np.pad(img, ((pad_h, kh - 1 - pad_h), (pad_w, kw - 1 - pad_w)), mode="edge")
elif padding == "valid":
padded = img
else:
raise ValueError(f"Unsupported padding mode: {padding}")
ph, pw = padded.shape
out_h = (ph - kh) // stride + 1
out_w = (pw - kw) // stride + 1
if out_h <= 0 or out_w <= 0:
raise ValueError("Kernel larger than padded image")
windows = np.lib.stride_tricks.sliding_window_view(padded, (kh, kw))[::stride, ::stride]
out = np.einsum("ijmn,mn->ij", windows, ker, optimize=True)
return np.asarray(out, dtype=np.float32)
def gaussian_kernel_2d(kernel_size: int = 5, sigma: float = 1.0) -> NDArray[np.float32]:
"""Construct normalized 2D isotropic Gaussian kernel."""
if kernel_size % 2 == 0 or kernel_size < 3:
raise ValueError("kernel_size must be an odd integer >= 3")
if sigma <= 0.0:
raise ValueError("sigma must be > 0")
half = kernel_size // 2
ax = np.arange(-half, half + 1, dtype=np.float32)
g1d = np.exp(-0.5 * (ax / sigma) ** 2)
g2d = np.outer(g1d, g1d)
g2d /= np.sum(g2d)
return g2d.astype(np.float32)
def gaussian_blur(
gray: NDArray[np.floating[Any]],
kernel_size: int = 5,
sigma: float = 1.0,
) -> NDArray[np.float32]:
"""Apply 2D Gaussian low-pass filter (anti-aliasing / noise reduction)."""
ker = gaussian_kernel_2d(kernel_size=kernel_size, sigma=sigma)
return conv2d_numpy(gray, ker, padding="same", stride=1)
def sobel_edges(gray: NDArray[np.floating[Any]]) -> dict[str, NDArray[np.float32]]:
"""Compute Sobel Gx, Gy, gradient magnitude, and orientation in [-pi, pi]."""
kx = np.array([[-1.0, 0.0, 1.0], [-2.0, 0.0, 2.0], [-1.0, 0.0, 1.0]], dtype=np.float32)
ky = kx.T
gx = conv2d_numpy(gray, kx, padding="same")
gy = conv2d_numpy(gray, ky, padding="same")
mag = np.hypot(gx, gy).astype(np.float32)
ori = np.arctan2(gy, gx).astype(np.float32)
return {"gx": gx, "gy": gy, "magnitude": mag, "orientation": ori}
def laplacian_filter(gray: NDArray[np.floating[Any]]) -> NDArray[np.float32]:
"""Compute discrete 8-neighbor Laplacian second derivative response."""
ker = np.array([[1.0, 1.0, 1.0], [1.0, -8.0, 1.0], [1.0, 1.0, 1.0]], dtype=np.float32)
return conv2d_numpy(gray, ker, padding="same")
def canny_hysteresis_edges(
gray: NDArray[np.floating[Any]],
sigma: float = 1.0,
low_ratio: float = 0.15,
high_ratio: float = 0.35,
) -> NDArray[np.bool_]:
"""Canny edge detector: Gaussian -> Sobel -> Non-Maximum Suppression -> Hysteresis linking."""
smooth = gaussian_blur(gray, kernel_size=5, sigma=sigma)
sob = sobel_edges(smooth)
mag = sob["magnitude"]
angle = np.mod(np.degrees(sob["orientation"]), 180.0)
h, w = mag.shape
nms = np.zeros((h, w), dtype=np.float32)
for y in range(1, h - 1):
for x in range(1, w - 1):
a = float(angle[y, x])
if (0.0 <= a < 22.5) or (157.5 <= a <= 180.0):
q, r = mag[y, x + 1], mag[y, x - 1]
elif 22.5 <= a < 67.5:
q, r = mag[y + 1, x - 1], mag[y - 1, x + 1]
elif 67.5 <= a < 112.5:
q, r = mag[y + 1, x], mag[y - 1, x]
else:
q, r = mag[y - 1, x - 1], mag[y + 1, x + 1]
if mag[y, x] >= q and mag[y, x] >= r:
nms[y, x] = mag[y, x]
max_val = float(np.max(nms))
if max_val <= 1e-8:
return np.zeros((h, w), dtype=np.bool_)
high_thr = max_val * high_ratio
low_thr = max_val * low_ratio
strong = nms >= high_thr
weak = (nms >= low_thr) & (~strong)
edges = strong.copy()
queue: deque[tuple[int, int]] = deque(
(int(y), int(x)) for y, x in np.argwhere(strong)
)
while queue:
cy, cx = queue.popleft()
for dy in (-1, 0, 1):
for dx in (-1, 0, 1):
ny, nx = cy + dy, cx + dx
if 0 <= ny < h and 0 <= nx < w and weak[ny, nx] and not edges[ny, nx]:
edges[ny, nx] = True
queue.append((ny, nx))
return edges
def binary_erode(mask: NDArray[np.bool_], kernel_size: int = 3) -> NDArray[np.bool_]:
"""Binary morphological erosion with square structuring element."""
struct = np.ones((kernel_size, kernel_size), dtype=np.bool_)
return np.asarray(ndimage.binary_erosion(mask, structure=struct), dtype=np.bool_)
def binary_dilate(mask: NDArray[np.bool_], kernel_size: int = 3) -> NDArray[np.bool_]:
"""Binary morphological dilation with square structuring element."""
struct = np.ones((kernel_size, kernel_size), dtype=np.bool_)
return np.asarray(ndimage.binary_dilation(mask, structure=struct), dtype=np.bool_)
def binary_open(mask: NDArray[np.bool_], kernel_size: int = 3) -> NDArray[np.bool_]:
"""Binary morphological opening (erosion followed by dilation) to remove speckle noise."""
return binary_dilate(binary_erode(mask, kernel_size), kernel_size)
def binary_close(mask: NDArray[np.bool_], kernel_size: int = 3) -> NDArray[np.bool_]:
"""Binary morphological closing (dilation followed by erosion) to fill small holes."""
return binary_erode(binary_dilate(mask, kernel_size), kernel_size)
def extract_hog_descriptor(
image: NDArray[np.floating[Any]],
config: HOGConfig | None = None,
) -> NDArray[np.float32]:
"""Extract Dalal & Triggs HOG descriptor with bilinear orientation voting and L2-Hys block norm."""
cfg = config or HOGConfig()
gray = rgb_to_grayscale(image) if image.ndim == 3 else np.asarray(image, dtype=np.float32)
h, w = gray.shape
cs = cfg.cell_size
n_cells_y = h // cs
n_cells_x = w // cs
if n_cells_y < cfg.block_cells or n_cells_x < cfg.block_cells:
raise ValueError("Image too small for configured HOG cell/block dimensions")
sob = sobel_edges(gray)
mag = sob["magnitude"][: n_cells_y * cs, : n_cells_x * cs]
# Unsigned orientation in [0, 180)
ori = np.mod(np.degrees(sob["orientation"][: n_cells_y * cs, : n_cells_x * cs]), 180.0)
n_bins = cfg.num_bins
bin_width = 180.0 / n_bins
bin_pos = ori / bin_width
bin_floor = np.floor(bin_pos)
bin_lo = (bin_floor.astype(np.int32) % n_bins)
bin_hi = (bin_lo + 1) % n_bins
frac = (bin_pos - bin_floor).astype(np.float32)
n_cells = n_cells_y * n_cells_x
cell_area = cs * cs
def _to_cells(arr: NDArray[Any]) -> NDArray[Any]:
return arr.reshape(n_cells_y, cs, n_cells_x, cs).transpose(0, 2, 1, 3).reshape(n_cells, cell_area)
w_lo = _to_cells(mag * (1.0 - frac))
w_hi = _to_cells(mag * frac)
b_lo = _to_cells(bin_lo)
b_hi = _to_cells(bin_hi)
cell_offsets = (np.arange(n_cells, dtype=np.int32) * n_bins)[:, None]
cell_hists = (
np.bincount((cell_offsets + b_lo).ravel(), weights=w_lo.ravel(), minlength=n_cells * n_bins)
+ np.bincount((cell_offsets + b_hi).ravel(), weights=w_hi.ravel(), minlength=n_cells * n_bins)
).reshape(n_cells_y, n_cells_x, n_bins).astype(np.float32)
bc = cfg.block_cells
blks = (
np.lib.stride_tricks.sliding_window_view(cell_hists, (bc, bc), axis=(0, 1))
.transpose(0, 1, 3, 4, 2)
.reshape(-1, bc * bc * n_bins)
)
eps_sq = cfg.eps * cfg.eps
norm1 = np.sqrt(np.sum(blks * blks, axis=1, keepdims=True) + eps_sq)
blks = np.minimum(blks / norm1, cfg.l2_hys_clip)
norm2 = np.sqrt(np.sum(blks * blks, axis=1, keepdims=True) + eps_sq)
return (blks / norm2).ravel().astype(np.float32)
def evaluate_hog_linear_baseline(
x_train: NDArray[np.float32],
y_train: NDArray[np.int64],
x_test: NDArray[np.float32],
y_test: NDArray[np.int64],
config: HOGConfig | None = None,
ridge_lambda: float = 1.0,
) -> dict[str, Any]:
"""Classical baseline: HOG descriptors + closed-form multi-class ridge linear classifier."""
cfg = config or HOGConfig()
f_train = np.stack([extract_hog_descriptor(img, cfg) for img in x_train], axis=0).astype(np.float64)
f_test = np.stack([extract_hog_descriptor(img, cfg) for img in x_test], axis=0).astype(np.float64)
# Standardize strictly using train statistics (anti-leakage)
mean = f_train.mean(axis=0, keepdims=True)
std = np.maximum(f_train.std(axis=0, keepdims=True), 1e-6)
z_train = (f_train - mean) / std
z_test = (f_test - mean) / std
n_samples, feat_dim = z_train.shape
n_classes = int(max(int(y_train.max()), int(y_test.max())) + 1)
y_onehot = np.eye(n_classes, dtype=np.float64)[y_train]
if n_samples < feat_dim:
# Exact centered dual Ridge solves an (n x n) system instead of (d x d) when n < d
z_bar = z_train.mean(axis=0, keepdims=True)
y_bar = y_onehot.mean(axis=0, keepdims=True)
z_c = z_train - z_bar
y_c = y_onehot - y_bar
dual = np.linalg.solve(z_c @ z_c.T + ridge_lambda * np.eye(n_samples, dtype=np.float64), y_c)
w = z_c.T @ dual
b = y_bar - z_bar @ w
pred_train = np.argmax(z_train @ w + b, axis=1)
pred_test = np.argmax(z_test @ w + b, axis=1)
else:
x_tr_b = np.concatenate([z_train, np.ones((n_samples, 1), dtype=np.float64)], axis=1)
x_te_b = np.concatenate([z_test, np.ones((z_test.shape[0], 1), dtype=np.float64)], axis=1)
reg = np.eye(feat_dim + 1, dtype=np.float64) * ridge_lambda
reg[-1, -1] = 0.0
weights = np.linalg.solve(x_tr_b.T @ x_tr_b + reg, x_tr_b.T @ y_onehot)
pred_train = np.argmax(x_tr_b @ weights, axis=1)
pred_test = np.argmax(x_te_b @ weights, axis=1)
train_acc = float(np.mean(pred_train == y_train))
test_acc = float(np.mean(pred_test == y_test))
return {
"feature_dim": int(feat_dim),
"train_accuracy": train_acc,
"test_accuracy": test_acc,
"num_params": int((feat_dim + 1) * n_classes),
}
"""Tier 1 (Pure Python): Convolution arithmetic, dilated receptive-field recurrence & DW-Sep FLOPs."""
from __future__ import annotations
from typing import Any
from pydantic import BaseModel, ConfigDict, Field
class ConvLayerSpec(BaseModel):
"""Strict specification for a single 2D convolution or pooling layer."""
model_config = ConfigDict(extra="forbid")
name: str = Field(min_length=1)
in_channels: int = Field(ge=1)
out_channels: int = Field(ge=1)
kernel_size: int = Field(ge=1)
stride: int = Field(default=1, ge=1)
padding: int = Field(default=0, ge=0)
dilation: int = Field(default=1, ge=1)
groups: int = Field(default=1, ge=1)
is_pooling: bool = Field(default=False)
def conv_output_size(
input_size: int,
kernel_size: int,
stride: int = 1,
padding: int = 0,
dilation: int = 1,
) -> int:
"""Exact 2D convolution output spatial size: floor((W + 2P - D(K - 1) - 1) / S) + 1."""
if input_size < 1 or kernel_size < 1 or stride < 1 or padding < 0 or dilation < 1:
raise ValueError("Invalid convolution geometry arguments")
eff_k = dilation * (kernel_size - 1) + 1
numerator = input_size + 2 * padding - eff_k
if numerator < 0:
raise ValueError(
f"Effective kernel ({eff_k}) exceeds padded input ({input_size + 2 * padding})"
)
return (numerator // stride) + 1
def compute_receptive_field_stack(
layers: list[ConvLayerSpec],
input_size: int = 32,
) -> list[dict[str, Any]]:
"""Compute layer-by-layer output size, receptive field r_l, effective jump j_l, params & MACs.
Recurrence:
r_l = r_{l-1} + (k_l - 1) * d_l * j_{l-1}
j_l = j_{l-1} * s_l
"""
cur_size = input_size
rf = 1
jump = 1
rows: list[dict[str, Any]] = []
for idx, layer in enumerate(layers, start=1):
if not layer.is_pooling and (
layer.in_channels % layer.groups != 0 or layer.out_channels % layer.groups != 0
):
raise ValueError(f"Layer '{layer.name}': channels must be divisible by groups")
out_size = conv_output_size(
input_size=cur_size,
kernel_size=layer.kernel_size,
stride=layer.stride,
padding=layer.padding,
dilation=layer.dilation,
)
rf = rf + (layer.kernel_size - 1) * layer.dilation * jump
jump = jump * layer.stride
if layer.is_pooling:
params = 0
macs = 0
else:
params = (
layer.out_channels
* (layer.in_channels // layer.groups)
* layer.kernel_size
* layer.kernel_size
)
macs = out_size * out_size * params
rows.append(
{
"layer_index": idx,
"name": layer.name,
"in_size": cur_size,
"out_size": out_size,
"receptive_field": rf,
"effective_stride": jump,
"params": params,
"macs": macs,
}
)
cur_size = out_size
return rows
def compare_standard_vs_dwsep_conv(
in_channels: int,
out_channels: int,
kernel_size: int,
out_hw: int,
) -> dict[str, float | int]:
"""Exact comparison of Standard 2D Conv vs Depthwise-Separable Conv (MobileNet) MACs & params.
Theoretical ratio:
MACs_dwsep / MACs_std = 1 / C_out + 1 / K^2
"""
if in_channels < 1 or out_channels < 1 or kernel_size < 1 or out_hw < 1:
raise ValueError("All dimensions must be >= 1")
spatial = out_hw * out_hw
std_params = kernel_size * kernel_size * in_channels * out_channels
dw_params = kernel_size * kernel_size * in_channels
pw_params = in_channels * out_channels
dwsep_params = dw_params + pw_params
std_macs = spatial * std_params
dwsep_macs = spatial * dwsep_params
# Roofline arithmetic intensity estimate (FLOPs = 2*MACs, bytes moved FP32 = 4B/elem)
std_bytes = 4 * (spatial * (in_channels + out_channels) + std_params)
dw_bytes = 4 * (spatial * (in_channels + in_channels) + dw_params)
pw_bytes = 4 * (spatial * (in_channels + out_channels) + pw_params)
theoretical_ratio = (1.0 / out_channels) + (1.0 / (kernel_size * kernel_size))
empirical_ratio = dwsep_macs / std_macs
return {
"std_params": std_params,
"dwsep_params": dwsep_params,
"std_macs": std_macs,
"dwsep_macs": dwsep_macs,
"mac_ratio": empirical_ratio,
"theoretical_ratio": theoretical_ratio,
"speedup_factor_macs": std_macs / dwsep_macs,
"std_oi_flops_per_byte": (2.0 * std_macs) / std_bytes,
"dw_oi_flops_per_byte": (2.0 * spatial * dw_params) / dw_bytes,
"pw_oi_flops_per_byte": (2.0 * spatial * pw_params) / pw_bytes,
}
def compute_grouped_conv_stats(
in_channels: int,
out_channels: int,
kernel_size: int,
out_hw: int,
groups: int,
) -> dict[str, float | int]:
"""Compute grouped convolution parameters, MACs, and exact 1/G reduction ratio."""
if groups < 1 or in_channels % groups != 0 or out_channels % groups != 0:
raise ValueError("in_channels and out_channels must be divisible by groups >= 1")
std_params = kernel_size * kernel_size * in_channels * out_channels
grp_params = std_params // groups
spatial = out_hw * out_hw
return {
"groups": groups,
"std_params": std_params,
"grouped_params": grp_params,
"std_macs": spatial * std_params,
"grouped_macs": spatial * grp_params,
"reduction_ratio": grp_params / std_params,
}
"""Tier 2 (PyTorch 2.x CPU): Standard vs Depthwise-Separable CNN, SOTA Augmentations, Safetensors & ONNX."""
from __future__ import annotations
import tempfile
import time
import warnings
from pathlib import Path
from typing import Any
import numpy as np
import onnx
import onnxruntime as ort
import torch
import torch.nn as nn
import torch.nn.functional as F
from numpy.typing import NDArray
from pydantic import BaseModel, ConfigDict, Field
from safetensors.torch import load as safetensors_load
from safetensors.torch import load_file as safetensors_load_file
from safetensors.torch import save as safetensors_save
from safetensors.torch import save_file as safetensors_save_file
class TrainConfig(BaseModel):
"""Strict training hyperparameters for CPU CNN training."""
model_config = ConfigDict(extra="forbid")
epochs: int = Field(default=14, ge=2, le=100)
batch_size: int = Field(default=32, ge=4, le=256)
lr: float = Field(default=3e-3, gt=0.0, le=0.5)
weight_decay: float = Field(default=1e-4, ge=0.0, le=0.1)
use_augmentation: bool = Field(default=True)
seed: int = Field(default=42, ge=0)
class StandardCNN(nn.Module):
"""Compact 3-stage Standard 2D CNN baseline (3 -> 24 -> 48 -> 64 -> GAP -> Linear)."""
def __init__(self, num_classes: int = 4) -> None:
super().__init__()
self.block1 = nn.Sequential(
nn.Conv2d(3, 24, kernel_size=3, stride=1, padding=1, bias=False),
nn.BatchNorm2d(24),
nn.ReLU(inplace=False),
nn.MaxPool2d(kernel_size=2, stride=2),
)
self.block2 = nn.Sequential(
nn.Conv2d(24, 48, kernel_size=3, stride=1, padding=1, bias=False),
nn.BatchNorm2d(48),
nn.ReLU(inplace=False),
nn.MaxPool2d(kernel_size=2, stride=2),
)
self.last_conv = nn.Conv2d(48, 64, kernel_size=3, stride=1, padding=1, bias=False)
self.last_bn = nn.BatchNorm2d(64)
self.last_act = nn.ReLU(inplace=False)
self.head = nn.Linear(64, num_classes)
@property
def target_conv_layer(self) -> nn.Module:
"""Final spatial convolutional layer targeted by Grad-CAM hooks."""
return self.last_conv
def forward(self, x: torch.Tensor) -> torch.Tensor:
h = self.block1(x)
h = self.block2(h)
h = self.last_act(self.last_bn(self.last_conv(h)))
pooled = h.mean(dim=(2, 3))
return self.head(pooled)
class DepthwiseSeparableBlock(nn.Module):
"""MobileNet-style Depthwise (groups=C_in) + Pointwise (1x1) separable convolution block."""
def __init__(self, in_ch: int, out_ch: int, stride: int = 1) -> None:
super().__init__()
self.depthwise = nn.Conv2d(
in_ch,
in_ch,
kernel_size=3,
stride=stride,
padding=1,
groups=in_ch,
bias=False,
)
self.dw_bn = nn.BatchNorm2d(in_ch)
self.pointwise = nn.Conv2d(in_ch, out_ch, kernel_size=1, stride=1, padding=0, bias=False)
self.pw_bn = nn.BatchNorm2d(out_ch)
self.act = nn.ReLU(inplace=False)
def forward(self, x: torch.Tensor) -> torch.Tensor:
h = self.act(self.dw_bn(self.depthwise(x)))
return self.act(self.pw_bn(self.pointwise(h)))
class DepthwiseSeparableCNN(nn.Module):
"""Edge-efficient Depthwise-Separable CNN matching StandardCNN channels with >4x fewer MACs/params."""
def __init__(self, num_classes: int = 4) -> None:
super().__init__()
self.stem = nn.Sequential(
nn.Conv2d(3, 24, kernel_size=3, stride=1, padding=1, bias=False),
nn.BatchNorm2d(24),
nn.ReLU(inplace=False),
nn.MaxPool2d(kernel_size=2, stride=2),
)
self.dw_block2 = DepthwiseSeparableBlock(24, 48, stride=2)
self.dw_last_dw = nn.Conv2d(48, 48, kernel_size=3, stride=1, padding=1, groups=48, bias=False)
self.dw_last_dw_bn = nn.BatchNorm2d(48)
self.dw_last_pw = nn.Conv2d(48, 64, kernel_size=1, stride=1, padding=0, bias=False)
self.dw_last_pw_bn = nn.BatchNorm2d(64)
self.act = nn.ReLU(inplace=False)
self.head = nn.Linear(64, num_classes)
@property
def target_conv_layer(self) -> nn.Module:
"""Final spatial pointwise conv layer targeted by Grad-CAM hooks."""
return self.dw_last_pw
def forward(self, x: torch.Tensor) -> torch.Tensor:
h = self.stem(x)
h = self.dw_block2(h)
h = self.act(self.dw_last_dw_bn(self.dw_last_dw(h)))
h = self.act(self.dw_last_pw_bn(self.dw_last_pw(h)))
pooled = h.mean(dim=(2, 3))
return self.head(pooled)
def count_model_params_and_macs(model: nn.Module, input_hw: int = 32) -> dict[str, int]:
"""Count exact trainable parameters and Conv2d+Linear MACs via a single dry-run forward pass."""
total_params = sum(p.numel() for p in model.parameters())
macs_box = [0]
hooks: list[Any] = []
def _conv_hook(mod: nn.Module, _inp: Any, out: Any) -> None:
if isinstance(mod, nn.Conv2d) and isinstance(out, torch.Tensor):
_, c_out, h_o, w_o = out.shape
k_h, k_w = mod.kernel_size
c_in_per_group = mod.in_channels // mod.groups
macs_box[0] += int(h_o * w_o * c_out * c_in_per_group * k_h * k_w)
def _lin_hook(mod: nn.Module, _inp: Any, _out: Any) -> None:
if isinstance(mod, nn.Linear):
macs_box[0] += int(mod.in_features * mod.out_features)
for m in model.modules():
if isinstance(m, nn.Conv2d):
hooks.append(m.register_forward_hook(_conv_hook))
elif isinstance(m, nn.Linear):
hooks.append(m.register_forward_hook(_lin_hook))
was_training = model.training
model.eval()
with torch.no_grad():
_ = model(torch.zeros(1, 3, input_hw, input_hw, dtype=torch.float32))
for h in hooks:
h.remove()
if was_training:
model.train()
return {"params": int(total_params), "macs": int(macs_box[0])}
def apply_randaugment_batch(
images: torch.Tensor,
n_ops: int = 2,
magnitude: float = 0.25,
seed: int = 42,
) -> torch.Tensor:
"""Deterministic vectorized RandAugment-style geometric + photometric transforms on NCHW tensors."""
gen = torch.Generator().manual_seed(seed)
out = images.clone()
b, c, h, w = out.shape
if b == 0 or n_ops <= 0:
return torch.clamp(out, 0.0, 1.0)
k_ops = max(1, min(n_ops, 5))
for op in torch.randperm(5, generator=gen)[:k_ops].tolist():
if op == 0:
delta = (torch.rand((b, 1, 1, 1), generator=gen, dtype=out.dtype) * 2.0 - 1.0) * (
0.25 * magnitude
)
out = out + delta
elif op == 1:
factor = 1.0 + (torch.rand((b, 1, 1, 1), generator=gen, dtype=out.dtype) * 2.0 - 1.0) * (
0.5 * magnitude
)
mean = out.mean(dim=(2, 3), keepdim=True)
out = (out - mean) * factor + mean
elif op == 2:
max_px = max(1, int(round(2 * magnitude + 1)))
sx = int(torch.randint(-max_px, max_px + 1, (1,), generator=gen).item())
sy = int(torch.randint(-max_px, max_px + 1, (1,), generator=gen).item())
out = torch.roll(out, shifts=(sy, sx), dims=(2, 3))
elif op == 3:
noise = torch.randn((b, c, h, w), generator=gen, dtype=out.dtype) * (0.04 * magnitude)
out = out + noise
else:
gamma = torch.clamp(
1.0
+ (torch.rand((b, 1, 1, 1), generator=gen, dtype=out.dtype) * 2.0 - 1.0)
* (0.4 * magnitude),
min=0.5,
)
out = torch.clamp(out, 1e-4, 1.0).pow(gamma)
return torch.clamp(out, 0.0, 1.0)
def apply_mixup_batch(
images: torch.Tensor,
labels: torch.Tensor,
num_classes: int = 4,
alpha: float = 0.4,
seed: int = 42,
) -> tuple[torch.Tensor, torch.Tensor, float]:
"""MixUp convex interpolation of inputs and one-hot soft labels."""
rng = np.random.default_rng(seed)
lam = float(rng.beta(alpha, alpha)) if alpha > 0.0 else 1.0
perm = torch.tensor(rng.permutation(images.shape[0]), dtype=torch.long)
mixed_x = torch.clamp(lam * images + (1.0 - lam) * images[perm], 0.0, 1.0)
y_oh = F.one_hot(labels.long(), num_classes=num_classes).float()
mixed_y = lam * y_oh + (1.0 - lam) * y_oh[perm]
return mixed_x, mixed_y, lam
def apply_cutmix_batch(
images: torch.Tensor,
labels: torch.Tensor,
num_classes: int = 4,
alpha: float = 1.0,
seed: int = 42,
) -> tuple[torch.Tensor, torch.Tensor, float]:
"""CutMix rectangular patch replacement with exact area-adjusted soft labels."""
rng = np.random.default_rng(seed)
b, _, h, w = images.shape
lam = float(rng.beta(alpha, alpha)) if alpha > 0.0 else 1.0
perm = torch.tensor(rng.permutation(b), dtype=torch.long)
cut_ratio = float(np.sqrt(max(0.0, 1.0 - lam)))
cut_w = max(2, int(round(w * cut_ratio)))
cut_h = max(2, int(round(h * cut_ratio)))
cx = int(rng.integers(0, w))
cy = int(rng.integers(0, h))
x0 = max(0, cx - cut_w // 2)
x1 = min(w, cx + cut_w // 2)
y0 = max(0, cy - cut_h // 2)
y1 = min(h, cy + cut_h // 2)
mixed_x = images.clone()
mixed_x[:, :, y0:y1, x0:x1] = images[perm, :, y0:y1, x0:x1]
exact_lam = 1.0 - float((y1 - y0) * (x1 - x0)) / float(h * w)
y_oh = F.one_hot(labels.long(), num_classes=num_classes).float()
mixed_y = exact_lam * y_oh + (1.0 - exact_lam) * y_oh[perm]
return torch.clamp(mixed_x, 0.0, 1.0), mixed_y, exact_lam
def build_mosaic_quad(
images_four: torch.Tensor,
split_x: int | None = None,
split_y: int | None = None,
) -> torch.Tensor:
"""Stitch 4 CHW images into a single YOLO-style 2x2 Mosaic frame preserving (3, H, W) shape."""
if images_four.ndim != 4 or images_four.shape[0] != 4:
raise ValueError("build_mosaic_quad expects tensor of shape (4, C, H, W)")
_, c, h, w = images_four.shape
sx = w // 2 if split_x is None else int(np.clip(split_x, 2, w - 2))
sy = h // 2 if split_y is None else int(np.clip(split_y, 2, h - 2))
canvas = torch.zeros((c, h, w), dtype=images_four.dtype)
canvas[:, :sy, :sx] = images_four[0, :, :sy, :sx]
canvas[:, :sy, sx:] = images_four[1, :, :sy, sx:]
canvas[:, sy:, :sx] = images_four[2, :, sy:, :sx]
canvas[:, sy:, sx:] = images_four[3, :, sy:, sx:]
return torch.clamp(canvas, 0.0, 1.0)
def _compute_ece(probs: NDArray[np.float64], labels: NDArray[np.int64], n_bins: int = 10) -> float:
confidences = np.max(probs, axis=1)
preds = np.argmax(probs, axis=1)
correct = (preds == labels).astype(np.float64)
edges = np.linspace(0.0, 1.0, n_bins + 1)
ece = 0.0
n = max(1, len(labels))
for i in range(n_bins):
lo, hi = edges[i], edges[i + 1]
mask = (confidences >= lo) & (confidences <= hi if i == n_bins - 1 else confidences < hi)
if np.any(mask):
acc_bin = float(np.mean(correct[mask]))
conf_bin = float(np.mean(confidences[mask]))
ece += (float(np.sum(mask)) / n) * abs(acc_bin - conf_bin)
return float(ece)
def evaluate_cnn_classifier(
model: nn.Module,
x_data: NDArray[np.float32] | torch.Tensor,
y_data: NDArray[np.int64] | torch.Tensor,
) -> dict[str, float]:
"""Evaluate CNN accuracy, macro-F1, ECE-10, and per-image CPU inference latency."""
x_t = torch.as_tensor(x_data, dtype=torch.float32)
y_np = np.asarray(y_data, dtype=np.int64)
model.eval()
t0 = time.perf_counter()
with torch.no_grad():
logits = model(x_t)
probs_t = F.softmax(logits, dim=1)
elapsed_ms = (time.perf_counter() - t0) * 1000.0
probs = probs_t.numpy().astype(np.float64)
preds = np.argmax(probs, axis=1)
acc = float(np.mean(preds == y_np))
n_classes = probs.shape[1]
f1s: list[float] = []
for c in range(n_classes):
tp = float(np.sum((preds == c) & (y_np == c)))
fp = float(np.sum((preds == c) & (y_np != c)))
fn = float(np.sum((preds != c) & (y_np == c)))
denom = 2.0 * tp + fp + fn
f1s.append((2.0 * tp / denom) if denom > 0.0 else 0.0)
return {
"accuracy": acc,
"macro_f1": float(np.mean(f1s)),
"ece_10": _compute_ece(probs, y_np, n_bins=10),
"latency_ms_per_image": elapsed_ms / max(1, len(y_np)),
}
def train_cnn_classifier(
model: nn.Module,
x_train: NDArray[np.float32],
y_train: NDArray[np.int64],
config: TrainConfig | None = None,
) -> dict[str, Any]:
"""Deterministic fast CPU training loop with optional mild RandAugment + cosine annealing."""
cfg = config or TrainConfig()
torch.manual_seed(cfg.seed)
np.random.seed(cfg.seed)
x_t = torch.as_tensor(x_train, dtype=torch.float32)
y_t = torch.as_tensor(y_train, dtype=torch.long)
n = x_t.shape[0]
optimizer = torch.optim.AdamW(model.parameters(), lr=cfg.lr, weight_decay=cfg.weight_decay)
scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=cfg.epochs)
loss_history: list[float] = []
model.train()
for ep in range(cfg.epochs):
gen = torch.Generator().manual_seed(cfg.seed + ep * 131)
perm = torch.randperm(n, generator=gen)
ep_loss = 0.0
n_batches = 0
for start in range(0, n, cfg.batch_size):
idx = perm[start : start + cfg.batch_size]
xb = x_t[idx]
yb = y_t[idx]
if cfg.use_augmentation and ep < cfg.epochs - 2:
xb = apply_randaugment_batch(xb, n_ops=1, magnitude=0.2, seed=cfg.seed + ep * 997 + start)
optimizer.zero_grad(set_to_none=True)
logits = model(xb)
loss = F.cross_entropy(logits, yb)
loss.backward()
optimizer.step()
ep_loss += float(loss.item())
n_batches += 1
scheduler.step()
loss_history.append(ep_loss / max(1, n_batches))
model.eval()
return {
"final_train_loss": loss_history[-1],
"loss_history": loss_history,
"epochs": cfg.epochs,
}
def save_cnn_safetensors(model: nn.Module, path: Path | None = None) -> bytes:
"""Persist PyTorch CNN state_dict exclusively via zero-pickle safetensors."""
tensors = {k: v.detach().cpu().contiguous() for k, v in model.state_dict().items()}
if path is not None:
path.parent.mkdir(parents=True, exist_ok=True)
safetensors_save_file(tensors, str(path))
return path.read_bytes()
return bytes(safetensors_save(tensors))
def load_cnn_safetensors(model: nn.Module, payload: bytes | Path) -> nn.Module:
"""Load safetensors weights strictly into a model instance."""
if isinstance(payload, Path):
state = safetensors_load_file(str(payload))
else:
state = safetensors_load(payload)
model.load_state_dict(state, strict=True)
model.eval()
return model
def export_and_verify_onnx_parity(
model: nn.Module,
sample_batch: NDArray[np.float32] | torch.Tensor,
) -> dict[str, float]:
"""Export CNN to ONNX with dynamo=False (PyTorch 2.15 CPU compatible) and verify ORT CPU parity."""
model.eval()
x_t = torch.as_tensor(sample_batch, dtype=torch.float32)
dummy = x_t[:1]
with tempfile.TemporaryDirectory() as tmp_dir:
onnx_path = Path(tmp_dir) / "model.onnx"
with warnings.catch_warnings():
warnings.simplefilter("ignore", DeprecationWarning)
torch.onnx.export(
model,
(dummy,),
str(onnx_path),
dynamo=False,
input_names=["image"],
output_names=["logits"],
dynamic_axes={"image": {0: "batch"}, "logits": {0: "batch"}},
opset_version=17,
)
onnx_bytes = onnx_path.read_bytes()
onnx_model = onnx.load_model_from_string(onnx_bytes)
onnx.checker.check_model(onnx_model)
opts = ort.SessionOptions()
opts.intra_op_num_threads = 1
opts.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
session = ort.InferenceSession(onnx_bytes, sess_options=opts, providers=["CPUExecutionProvider"])
with torch.no_grad():
pt_out = model(x_t).numpy()
t0 = time.perf_counter()
ort_out = np.asarray(session.run(None, {"image": x_t.numpy()})[0], dtype=np.float32)
ort_ms = (time.perf_counter() - t0) * 1000.0 / max(1, x_t.shape[0])
max_diff = float(np.max(np.abs(pt_out - ort_out)))
return {
"onnx_bytes": float(len(onnx_bytes)),
"max_abs_diff": max_diff,
"ort_ms_per_image": float(ort_ms),
}
"""Tier 2 (PyTorch + SciPy): FGSM, PGD L_inf, PGD Adversarial Training & Randomized Smoothing."""
from __future__ import annotations
from typing import Any
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from numpy.typing import NDArray
from pydantic import BaseModel, ConfigDict, Field
from scipy import stats
class AdversarialConfig(BaseModel):
"""Strict configuration for L_inf FGSM/PGD attacks and Madry min-max adversarial training."""
model_config = ConfigDict(extra="forbid")
epsilon: float = Field(default=0.06, gt=0.0, le=0.5)
pgd_steps: int = Field(default=10, ge=1, le=50)
step_size: float = Field(default=0.015, gt=0.0, le=0.5)
random_start: bool = Field(default=True)
seed: int = Field(default=42, ge=0)
class SmoothingConfig(BaseModel):
"""Strict configuration for Cohen et al. (2019) Randomized Smoothing L2 certification."""
model_config = ConfigDict(extra="forbid")
sigma: float = Field(default=0.12, gt=0.0, le=2.0)
n_select: int = Field(default=64, ge=16, le=2000)
n_certify: int = Field(default=400, ge=50, le=10000)
alpha_conf: float = Field(default=0.001, gt=0.0, lt=0.5)
seed: int = Field(default=42, ge=0)
def fgsm_attack(
model: nn.Module,
images: torch.Tensor,
labels: torch.Tensor,
epsilon: float = 0.06,
) -> torch.Tensor:
"""One-step L_inf Fast Gradient Sign Method (Goodfellow et al. 2015)."""
was_training = model.training
model.eval()
x_adv = images.detach().clone().requires_grad_(True)
logits = model(x_adv)
loss = F.cross_entropy(logits, labels.long())
grad = torch.autograd.grad(loss, x_adv, retain_graph=False, create_graph=False)[0]
perturbed = torch.clamp(images.detach() + epsilon * grad.sign(), 0.0, 1.0)
if was_training:
model.train()
return perturbed.detach()
def pgd_linf_attack(
model: nn.Module,
images: torch.Tensor,
labels: torch.Tensor,
config: AdversarialConfig | None = None,
) -> torch.Tensor:
"""Multi-step L_inf Projected Gradient Descent (Madry et al. 2018) clamped to [0, 1] & eps-ball."""
cfg = config or AdversarialConfig()
was_training = model.training
model.eval()
x_orig = images.detach()
if cfg.random_start:
gen = torch.Generator().manual_seed(cfg.seed)
delta = (torch.rand(x_orig.shape, generator=gen, dtype=x_orig.dtype) * 2.0 - 1.0) * cfg.epsilon
x_adv = torch.clamp(x_orig + delta, 0.0, 1.0)
else:
x_adv = x_orig.clone()
for _ in range(cfg.pgd_steps):
x_adv = x_adv.detach().requires_grad_(True)
logits = model(x_adv)
loss = F.cross_entropy(logits, labels.long())
grad = torch.autograd.grad(loss, x_adv, retain_graph=False, create_graph=False)[0]
x_next = x_adv.detach() + cfg.step_size * grad.sign()
# Project back into L_inf ball around x_orig and valid pixel domain [0, 1]
eta = torch.clamp(x_next - x_orig, min=-cfg.epsilon, max=cfg.epsilon)
x_adv = torch.clamp(x_orig + eta, 0.0, 1.0)
if was_training:
model.train()
return x_adv.detach()
def evaluate_adversarial_accuracy(
model: nn.Module,
x_test: NDArray[np.float32] | torch.Tensor,
y_test: NDArray[np.int64] | torch.Tensor,
config: AdversarialConfig | None = None,
) -> dict[str, float]:
"""Evaluate clean, FGSM, and PGD L_inf accuracies plus verified perturbation norms."""
cfg = config or AdversarialConfig()
x_t = torch.as_tensor(x_test, dtype=torch.float32)
y_t = torch.as_tensor(y_test, dtype=torch.long)
model.eval()
with torch.no_grad():
clean_preds = model(x_t).argmax(dim=1)
clean_acc = float((clean_preds == y_t).float().mean().item())
x_fgsm = fgsm_attack(model, x_t, y_t, epsilon=cfg.epsilon)
x_pgd = pgd_linf_attack(model, x_t, y_t, config=cfg)
with torch.no_grad():
fgsm_acc = float((model(x_fgsm).argmax(dim=1) == y_t).float().mean().item())
pgd_acc = float((model(x_pgd).argmax(dim=1) == y_t).float().mean().item())
fgsm_linf = float((x_fgsm - x_t).abs().max().item())
pgd_linf = float((x_pgd - x_t).abs().max().item())
return {
"epsilon": cfg.epsilon,
"pgd_steps": float(cfg.pgd_steps),
"clean_accuracy": clean_acc,
"fgsm_accuracy": fgsm_acc,
"pgd_accuracy": pgd_acc,
"fgsm_max_linf": fgsm_linf,
"pgd_max_linf": pgd_linf,
}
def train_pgd_adversarial_cnn(
model: nn.Module,
x_train: NDArray[np.float32],
y_train: NDArray[np.int64],
adv_config: AdversarialConfig | None = None,
epochs: int = 16,
batch_size: int = 32,
lr: float = 3e-3,
clean_mix_weight: float = 0.25,
seed: int = 42,
inner_pgd_steps: int | None = None,
) -> dict[str, Any]:
"""Madry et al. (2018) min-max PGD adversarial training with TRADES-like clean stability anchor."""
cfg = adv_config or AdversarialConfig()
torch.manual_seed(seed)
np.random.seed(seed)
x_t = torch.as_tensor(x_train, dtype=torch.float32)
y_t = torch.as_tensor(y_train, dtype=torch.long)
n = x_t.shape[0]
optimizer = torch.optim.AdamW(model.parameters(), lr=lr, weight_decay=1e-4)
scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=epochs)
inner_steps = (
max(2, int(inner_pgd_steps))
if inner_pgd_steps is not None
else max(3, min(cfg.pgd_steps, 5))
)
loss_history: list[float] = []
for ep in range(epochs):
gen = torch.Generator().manual_seed(seed + ep * 173)
perm = torch.randperm(n, generator=gen)
ep_loss = 0.0
n_batches = 0
# Ramp epsilon smoothly over first 3 epochs for stable optimization
cur_eps = cfg.epsilon * min(1.0, (ep + 1) / 3.0)
cur_step = max(cur_eps / max(1, inner_steps) * 1.5, 1e-3)
for start in range(0, n, batch_size):
idx = perm[start : start + batch_size]
xb = x_t[idx]
yb = y_t[idx]
inner_cfg = AdversarialConfig(
epsilon=cur_eps,
pgd_steps=inner_steps,
step_size=cur_step,
random_start=True,
seed=seed + ep * 991 + start,
)
xb_adv = pgd_linf_attack(model, xb, yb, config=inner_cfg)
model.train()
optimizer.zero_grad(set_to_none=True)
loss_adv = F.cross_entropy(model(xb_adv), yb)
loss_clean = F.cross_entropy(model(xb), yb)
loss = (1.0 - clean_mix_weight) * loss_adv + clean_mix_weight * loss_clean
loss.backward()
optimizer.step()
ep_loss += float(loss.item())
n_batches += 1
scheduler.step()
loss_history.append(ep_loss / max(1, n_batches))
model.eval()
return {
"final_adv_loss": loss_history[-1],
"epochs": epochs,
"train_epsilon": cfg.epsilon,
"inner_pgd_steps": inner_steps,
}
def clopper_pearson_lower_bound(k_success: int, n_trials: int, alpha_conf: float) -> float:
"""Exact one-sided Clopper-Pearson lower confidence bound for binomial proportion."""
if k_success <= 0:
return 0.0
if k_success >= n_trials:
return float(stats.beta.ppf(alpha_conf, n_trials, 1))
return float(stats.beta.ppf(alpha_conf, k_success, n_trials - k_success + 1))
def certify_randomized_smoothing(
model: nn.Module,
image: torch.Tensor | NDArray[np.float32],
config: SmoothingConfig | None = None,
) -> dict[str, Any]:
"""Cohen et al. (ICML 2019) Randomized Smoothing L2 certificate with Neyman-Pearson radius.
R = sigma * Phi^{-1}(p_A_lower) if p_A_lower > 0.5 else ABSTAIN (R = 0.0)
"""
cfg = config or SmoothingConfig()
x = torch.as_tensor(image, dtype=torch.float32)
if x.ndim == 3:
x = x.unsqueeze(0)
if x.ndim != 4 or x.shape[0] != 1:
raise ValueError("certify_randomized_smoothing expects a single image (C, H, W) or (1, C, H, W)")
model.eval()
gen = torch.Generator().manual_seed(cfg.seed)
def _sample_counts(n_samples: int) -> NDArray[np.int64]:
counts: NDArray[np.int64] | None = None
remaining = n_samples
batch_cap = 128
with torch.no_grad():
while remaining > 0:
cur = min(batch_cap, remaining)
noise = torch.randn((cur, *x.shape[1:]), generator=gen, dtype=x.dtype) * cfg.sigma
noisy = torch.clamp(x.expand(cur, -1, -1, -1) + noise, 0.0, 1.0)
logits = model(noisy)
n_cls = logits.shape[1]
if counts is None:
counts = np.zeros((n_cls,), dtype=np.int64)
preds = logits.argmax(dim=1).numpy()
for c in preds:
counts[int(c)] += 1
remaining -= cur
assert counts is not None
return counts
# Stage 1: Selection draw to pick candidate top class c_A
sel_counts = _sample_counts(cfg.n_select)
c_a = int(np.argmax(sel_counts))
# Stage 2: Independent certification draw for valid Clopper-Pearson lower bound
cert_counts = _sample_counts(cfg.n_certify)
k_a = int(cert_counts[c_a])
p_a_hat = float(k_a) / float(cfg.n_certify)
p_a_lower = clopper_pearson_lower_bound(k_a, cfg.n_certify, cfg.alpha_conf)
if p_a_lower > 0.5:
abstain = False
p_b_upper = 1.0 - p_a_lower
# Equivalent exact form: (sigma / 2) * (Phi^{-1}(p_A) - Phi^{-1}(1 - p_A)) = sigma * Phi^{-1}(p_A)
radius = float(0.5 * cfg.sigma * (stats.norm.ppf(p_a_lower) - stats.norm.ppf(p_b_upper)))
predicted_class: int | None = c_a
else:
abstain = True
radius = 0.0
predicted_class = None
return {
"predicted_class": predicted_class,
"candidate_class": c_a,
"abstain": abstain,
"p_a_empirical": p_a_hat,
"p_a_lower": p_a_lower,
"sigma": cfg.sigma,
"alpha_conf": cfg.alpha_conf,
"certified_l2_radius": radius,
}
"""Tier 2 (PyTorch hooks & autograd): Grad-CAM, Integrated Gradients, RISE, Faithfulness & Adebayo."""
from __future__ import annotations
import copy
from typing import Any
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from numpy.typing import NDArray
from pydantic import BaseModel, ConfigDict, Field
class XAIConfig(BaseModel):
"""Strict configuration for Visual XAI methods and faithfulness evaluation."""
model_config = ConfigDict(extra="forbid")
ig_steps: int = Field(default=48, ge=8, le=256)
rise_masks: int = Field(default=120, ge=16, le=1000)
rise_grid: int = Field(default=6, ge=2, le=16)
rise_p: float = Field(default=0.5, gt=0.05, lt=0.95)
faithfulness_steps: int = Field(default=16, ge=4, le=64)
seed: int = Field(default=42, ge=0)
def _normalize_map(sal: NDArray[np.float32]) -> NDArray[np.float32]:
s_min = float(np.min(sal))
s_max = float(np.max(sal))
if s_max - s_min <= 1e-12:
return np.zeros_like(sal, dtype=np.float32)
return ((sal - s_min) / (s_max - s_min)).astype(np.float32)
def compute_gradcam(
model: nn.Module,
image: torch.Tensor | NDArray[np.float32],
target_layer: nn.Module,
target_class: int | None = None,
) -> dict[str, Any]:
"""Compute Grad-CAM (Selvaraju et al. ICCV 2017) using PyTorch forward & full backward hooks."""
x = torch.as_tensor(image, dtype=torch.float32)
if x.ndim == 3:
x = x.unsqueeze(0)
h_in, w_in = int(x.shape[2]), int(x.shape[3])
activations: list[torch.Tensor] = []
gradients: list[torch.Tensor] = []
def _fwd_hook(_mod: nn.Module, _inp: Any, out: Any) -> None:
if isinstance(out, torch.Tensor):
activations.append(out.detach())
def _bwd_hook(_mod: nn.Module, _grad_in: Any, grad_out: Any) -> None:
if isinstance(grad_out, tuple) and len(grad_out) > 0 and isinstance(grad_out[0], torch.Tensor):
gradients.append(grad_out[0].detach())
h_fwd = target_layer.register_forward_hook(_fwd_hook)
h_bwd = target_layer.register_full_backward_hook(_bwd_hook)
model.eval()
try:
model.zero_grad(set_to_none=True)
logits = model(x)
cls_id = int(logits.argmax(dim=1).item()) if target_class is None else int(target_class)
score = logits[0, cls_id]
score.backward()
finally:
h_fwd.remove()
h_bwd.remove()
act = activations[0] # (1, C_f, H_f, W_f)
grad = gradients[0] # (1, C_f, H_f, W_f)
weights = grad.mean(dim=(2, 3), keepdim=True) # alpha_k^c
cam = F.relu((weights * act).sum(dim=1, keepdim=True))
cam_up = F.interpolate(cam, size=(h_in, w_in), mode="bilinear", align_corners=False)
cam_np = cam_up[0, 0].cpu().numpy().astype(np.float32)
return {
"target_class": cls_id,
"raw_map": cam_np,
"heatmap": _normalize_map(cam_np),
"target_logit": float(score.detach().item()),
}
def compute_integrated_gradients(
model: nn.Module,
image: torch.Tensor | NDArray[np.float32],
target_class: int | None = None,
baseline: torch.Tensor | NDArray[np.float32] | None = None,
steps: int = 48,
) -> dict[str, Any]:
"""Compute Integrated Gradients (Sundararajan et al. ICML 2017) with Riemann midpoint quadrature.
Verifies Completeness Axiom: sum_i IG_i(x; x') == F_c(x) - F_c(x').
"""
x = torch.as_tensor(image, dtype=torch.float32)
if x.ndim == 3:
x = x.unsqueeze(0)
if baseline is None:
base = torch.zeros_like(x)
else:
base = torch.as_tensor(baseline, dtype=torch.float32)
if base.ndim == 3:
base = base.unsqueeze(0)
model.eval()
with torch.no_grad():
logits_x = model(x)
logits_b = model(base)
cls_id = int(logits_x.argmax(dim=1).item()) if target_class is None else int(target_class)
fx = float(logits_x[0, cls_id].item())
fbase = float(logits_b[0, cls_id].item())
# Midpoint Riemann sum: alpha_m = (m - 0.5) / M for m = 1..M
alphas = (torch.arange(steps, dtype=torch.float32) + 0.5) / float(steps)
diff = x - base
scaled = base + alphas.view(-1, 1, 1, 1) * diff # (M, C, H, W)
scaled = scaled.detach().requires_grad_(True)
logits_path = model(scaled)
target_scores = logits_path[:, cls_id].sum()
grads = torch.autograd.grad(target_scores, scaled, retain_graph=False, create_graph=False)[0]
avg_grad = grads.mean(dim=0, keepdim=True)
ig_tensor = (diff * avg_grad).detach()
ig_sum = float(ig_tensor.sum().item())
logit_diff = fx - fbase
completeness_error = abs(ig_sum - logit_diff)
# Spatial saliency magnitude across color channels
sal_2d = ig_tensor.abs().sum(dim=1)[0].cpu().numpy().astype(np.float32)
return {
"target_class": cls_id,
"attribution": ig_tensor[0].cpu().numpy().astype(np.float32),
"heatmap": _normalize_map(sal_2d),
"ig_sum": ig_sum,
"logit_diff": logit_diff,
"completeness_abs_error": completeness_error,
}
def compute_rise_saliency(
model: nn.Module,
image: torch.Tensor | NDArray[np.float32],
target_class: int | None = None,
config: XAIConfig | None = None,
) -> dict[str, Any]:
"""Black-box RISE saliency (Petsiuk et al. BMVC 2018) via upsampled random binary masks."""
cfg = config or XAIConfig()
x = torch.as_tensor(image, dtype=torch.float32)
if x.ndim == 3:
x = x.unsqueeze(0)
_, _, h, w = x.shape
model.eval()
with torch.no_grad():
logits = model(x)
cls_id = int(logits.argmax(dim=1).item()) if target_class is None else int(target_class)
gen = torch.Generator().manual_seed(cfg.seed)
rand_grid = torch.rand((cfg.rise_masks, 1, cfg.rise_grid, cfg.rise_grid), generator=gen)
small = (rand_grid < cfg.rise_p).float()
masks = F.interpolate(small, size=(h, w), mode="bilinear", align_corners=False)
# Mask toward per-image channel mean (neutral background)
mean_bg = x.mean(dim=(2, 3), keepdim=True)
masked_batch = x * masks + mean_bg * (1.0 - masks)
with torch.no_grad():
probs = F.softmax(model(masked_batch), dim=1)[:, cls_id]
weighted = (probs.view(-1, 1, 1, 1) * masks).mean(dim=0)[0] / max(cfg.rise_p, 1e-6)
sal_np = weighted.cpu().numpy().astype(np.float32)
return {
"target_class": cls_id,
"heatmap": _normalize_map(sal_np),
}
def evaluate_deletion_insertion_auc(
model: nn.Module,
image: torch.Tensor | NDArray[np.float32],
saliency_map: NDArray[np.float32],
target_class: int,
steps: int = 16,
seed: int = 42,
) -> dict[str, Any]:
"""Evaluate Visual XAI faithfulness via Deletion AUC (lower better) & Insertion AUC (higher better)."""
x = torch.as_tensor(image, dtype=torch.float32)
if x.ndim == 3:
x = x.unsqueeze(0)
_, _, h, w = x.shape
n_pix = h * w
# Neutral baseline (global channel mean) for masking/inserting
neutral = x.mean(dim=(2, 3), keepdim=True).expand_as(x)
flat_sal = np.asarray(saliency_map, dtype=np.float32).reshape(-1)
order_sal = np.argsort(-flat_sal) # descending importance
rng = np.random.default_rng(seed)
order_rand = rng.permutation(n_pix)
fractions = np.linspace(0.0, 1.0, steps + 1)
def _run_curves(order: NDArray[np.intp]) -> tuple[list[float], list[float]]:
del_probs: list[float] = []
ins_probs: list[float] = []
model.eval()
with torch.no_grad():
for frac in fractions:
k = int(round(float(frac) * n_pix))
mask_flat = np.zeros(n_pix, dtype=np.float32)
if k > 0:
mask_flat[order[:k]] = 1.0
m_t = torch.tensor(mask_flat.reshape(1, 1, h, w), dtype=torch.float32)
# Deletion removes top-k pixels; Insertion inserts top-k pixels into neutral canvas
x_del = x * (1.0 - m_t) + neutral * m_t
x_ins = neutral * (1.0 - m_t) + x * m_t
p_del = float(F.softmax(model(x_del), dim=1)[0, target_class].item())
p_ins = float(F.softmax(model(x_ins), dim=1)[0, target_class].item())
del_probs.append(p_del)
ins_probs.append(p_ins)
return del_probs, ins_probs
sal_del, sal_ins = _run_curves(order_sal)
rnd_del, rnd_ins = _run_curves(order_rand)
del_auc = float(np.trapezoid(sal_del, fractions))
ins_auc = float(np.trapezoid(sal_ins, fractions))
rand_del_auc = float(np.trapezoid(rnd_del, fractions))
rand_ins_auc = float(np.trapezoid(rnd_ins, fractions))
return {
"deletion_auc": del_auc,
"insertion_auc": ins_auc,
"random_deletion_auc": rand_del_auc,
"random_insertion_auc": rand_ins_auc,
"deletion_curve": sal_del,
"insertion_curve": sal_ins,
"random_deletion_curve": rnd_del,
"random_insertion_curve": rnd_ins,
}
def _pearson_corr(a: NDArray[np.float32], b: NDArray[np.float32]) -> float:
fa = a.ravel().astype(np.float64)
fb = b.ravel().astype(np.float64)
fa = fa - fa.mean()
fb = fb - fb.mean()
denom = float(np.linalg.norm(fa) * np.linalg.norm(fb))
if denom <= 1e-12:
return 0.0
return float(np.dot(fa, fb) / denom)
def _resolve_target_conv(model: nn.Module) -> nn.Module:
convs = [m for m in model.modules() if isinstance(m, nn.Conv2d)]
if not convs:
raise ValueError("Model contains no nn.Conv2d layer for Grad-CAM")
return convs[-1]
def check_adebayo_weight_randomization_sanity(
model: nn.Module,
image: torch.Tensor | NDArray[np.float32],
target_class: int,
seed: int = 42,
) -> dict[str, float]:
"""Adebayo et al. (NeurIPS 2018) cascading model-parameter randomization sanity check.
Faithful explanations (Grad-CAM, IG) must change substantially when model weights are randomized,
producing low correlation (< 0.6) with the trained model's saliency map.
"""
trained_layer = _resolve_target_conv(model)
gc_trained = compute_gradcam(model, image, trained_layer, target_class=target_class)["heatmap"]
ig_trained = compute_integrated_gradients(model, image, target_class=target_class, steps=24)["heatmap"]
rand_model = copy.deepcopy(model)
torch.manual_seed(seed + 777)
with torch.no_grad():
for m in rand_model.modules():
if isinstance(m, (nn.Conv2d, nn.Linear)):
nn.init.kaiming_normal_(m.weight)
if m.bias is not None:
nn.init.zeros_(m.bias)
rand_layer = _resolve_target_conv(rand_model)
gc_rand = compute_gradcam(rand_model, image, rand_layer, target_class=target_class)["heatmap"]
ig_rand = compute_integrated_gradients(rand_model, image, target_class=target_class, steps=24)["heatmap"]
gc_corr = abs(_pearson_corr(gc_trained, gc_rand))
ig_corr = abs(_pearson_corr(ig_trained, ig_rand))
return {
"gradcam_abs_corr_after_randomization": gc_corr,
"ig_abs_corr_after_randomization": ig_corr,
"gradcam_passes_sanity": 1.0 if gc_corr < 0.75 else 0.0,
"ig_passes_sanity": 1.0 if ig_corr < 0.75 else 0.0,
}
"""CLI Benchmark & Artifact Generator for Lab 08 (`T1-P3-U03`: Image Processing, CNN, Robustness & XAI)."""
from __future__ import annotations
import argparse
import json
import sys
from pathlib import Path
from typing import Any
_SRC_DIR = str(Path(__file__).resolve().parents[1] / "src")
if _SRC_DIR not in sys.path:
sys.path.insert(0, _SRC_DIR)
import numpy as np # noqa: E402
import torch # noqa: E402
from cv_cnn_robustness_lab.adversarial import ( # noqa: E402
AdversarialConfig,
SmoothingConfig,
certify_randomized_smoothing,
evaluate_adversarial_accuracy,
train_pgd_adversarial_cnn,
)
from cv_cnn_robustness_lab.cnn_models import ( # noqa: E402
DepthwiseSeparableCNN,
StandardCNN,
TrainConfig,
apply_cutmix_batch,
apply_mixup_batch,
apply_randaugment_batch,
build_mosaic_quad,
count_model_params_and_macs,
evaluate_cnn_classifier,
export_and_verify_onnx_parity,
load_cnn_safetensors,
save_cnn_safetensors,
train_cnn_classifier,
)
from cv_cnn_robustness_lab.color_and_filters import ( # noqa: E402
DatasetConfig,
HOGConfig,
array_to_pil_and_back,
binary_close,
binary_open,
canny_hysteresis_edges,
clahe_tile_equalize,
evaluate_hog_linear_baseline,
gaussian_blur,
generate_aoi_pcb_dataset,
histogram_equalize_uint8,
rgb_to_grayscale,
rgb_to_hsv,
rgb_to_ycbcr,
sobel_edges,
)
from cv_cnn_robustness_lab.conv_geometry import ( # noqa: E402
ConvLayerSpec,
compare_standard_vs_dwsep_conv,
compute_grouped_conv_stats,
compute_receptive_field_stack,
)
from cv_cnn_robustness_lab.visual_xai import ( # noqa: E402
XAIConfig,
check_adebayo_weight_randomization_sanity,
compute_gradcam,
compute_integrated_gradients,
compute_rise_saliency,
evaluate_deletion_insertion_auc,
)
def run_lab08_benchmark(seed: int = 42, quick: bool = False) -> dict[str, Any]:
"""Execute end-to-end Tier 1 + Tier 2 benchmarks and build workbench_panels schema."""
n_train = 48 if quick else 90
n_test = 10 if quick else 30
epochs_std = 8 if quick else 16
epochs_adv = 4 if quick else 16
batch_sz = 32
lr_std = 5e-3 if quick else 3e-3
lr_dw = 5e-3 if quick else 4e-3
inner_adv_steps = 2 if quick else None
ds_cfg = DatasetConfig(
image_size=32,
n_train_per_class=n_train,
n_test_per_class=n_test,
noise_std=0.035,
max_shift_px=3,
seed=seed,
)
dataset = generate_aoi_pcb_dataset(ds_cfg)
x_train = dataset["x_train"]
y_train = dataset["y_train"]
x_test = dataset["x_test"]
y_test = dataset["y_test"]
mask_test = dataset["mask_test"]
# 1. Classical Image Processing & HOG Baseline (Tier 1)
sample_rgb = x_test[0]
gray = rgb_to_grayscale(sample_rgb)
hsv = rgb_to_hsv(sample_rgb)
ycbcr = rgb_to_ycbcr(sample_rgb)
pil_rt = array_to_pil_and_back(sample_rgb)
pil_max_err = float(np.max(np.abs(np.transpose(sample_rgb, (1, 2, 0)) - pil_rt)))
eq_global = histogram_equalize_uint8(gray)
eq_clahe = clahe_tile_equalize(gray, grid_size=4, clip_limit=2.5)
blurred = gaussian_blur(gray, kernel_size=5, sigma=1.0)
sob = sobel_edges(blurred)
canny = canny_hysteresis_edges(gray, sigma=1.0, low_ratio=0.15, high_ratio=0.35)
opened = binary_open(canny, kernel_size=3)
closed = binary_close(canny, kernel_size=3)
hog_cfg = HOGConfig(cell_size=4, block_cells=2, num_bins=9)
hog_res = evaluate_hog_linear_baseline(x_train, y_train, x_test, y_test, config=hog_cfg)
# 2. Convolution Arithmetic, Receptive Field & DW-Sep FLOPs Analysis (Tier 1)
rf_specs = [
ConvLayerSpec(name="conv1_3x3", in_channels=3, out_channels=24, kernel_size=3, stride=1, padding=1),
ConvLayerSpec(
name="pool1_2x2", in_channels=24, out_channels=24, kernel_size=2, stride=2, is_pooling=True
),
ConvLayerSpec(name="conv2_3x3", in_channels=24, out_channels=48, kernel_size=3, stride=1, padding=1),
ConvLayerSpec(
name="pool2_2x2", in_channels=48, out_channels=48, kernel_size=2, stride=2, is_pooling=True
),
ConvLayerSpec(
name="conv3_3x3_d2",
in_channels=48,
out_channels=64,
kernel_size=3,
stride=1,
padding=2,
dilation=2,
),
]
rf_stack = compute_receptive_field_stack(rf_specs, input_size=32)
dwsep_block_cmp = compare_standard_vs_dwsep_conv(
in_channels=48, out_channels=64, kernel_size=3, out_hw=8
)
grouped_cmp = compute_grouped_conv_stats(
in_channels=48, out_channels=64, kernel_size=3, out_hw=8, groups=4
)
# 3. Augmentation Sanity Stats & StandardCNN vs DepthwiseSeparableCNN Training (Tier 2)
sample_batch_t = torch.as_tensor(x_train[:8], dtype=torch.float32)
sample_lbl_t = torch.as_tensor(y_train[:8], dtype=torch.long)
aug_ra = apply_randaugment_batch(sample_batch_t, n_ops=2, magnitude=0.25, seed=seed)
aug_mx, aug_my, lam_mixup = apply_mixup_batch(sample_batch_t, sample_lbl_t, seed=seed)
aug_cx, aug_cy, lam_cutmix = apply_cutmix_batch(sample_batch_t, sample_lbl_t, seed=seed)
mosaic_img = build_mosaic_quad(sample_batch_t[:4])
torch.manual_seed(seed)
std_cnn = StandardCNN(num_classes=4)
std_stats = count_model_params_and_macs(std_cnn, input_hw=32)
std_train = train_cnn_classifier(
std_cnn,
x_train,
y_train,
config=TrainConfig(
epochs=epochs_std,
batch_size=batch_sz,
lr=lr_std,
use_augmentation=True,
seed=seed,
),
)
std_eval = evaluate_cnn_classifier(std_cnn, x_test, y_test)
torch.manual_seed(seed)
dw_cnn = DepthwiseSeparableCNN(num_classes=4)
dw_stats = count_model_params_and_macs(dw_cnn, input_hw=32)
dw_train = train_cnn_classifier(
dw_cnn,
x_train,
y_train,
config=TrainConfig(
epochs=epochs_std,
batch_size=batch_sz,
lr=lr_dw,
use_augmentation=True,
seed=seed,
),
)
dw_eval = evaluate_cnn_classifier(dw_cnn, x_test, y_test)
param_reduction = float(std_stats["params"]) / float(dw_stats["params"])
mac_reduction = float(std_stats["macs"]) / float(dw_stats["macs"])
# Zero-pickle safetensors + ONNX (dynamo=False) ORT CPU parity
sf_bytes = save_cnn_safetensors(dw_cnn)
dw_reloaded = load_cnn_safetensors(DepthwiseSeparableCNN(num_classes=4), sf_bytes)
with torch.no_grad():
sf_diff = float(
(dw_cnn(torch.as_tensor(x_test[:16])) - dw_reloaded(torch.as_tensor(x_test[:16])))
.abs()
.max()
.item()
)
onnx_parity = export_and_verify_onnx_parity(dw_reloaded, x_test[:16])
# 4. Adversarial Robustness: FGSM, PGD, PGD-AT & Randomized Smoothing (Tier 2)
adv_cfg = AdversarialConfig(epsilon=0.06, pgd_steps=10, step_size=0.015, random_start=True, seed=seed)
std_adv_eval = evaluate_adversarial_accuracy(std_cnn, x_test, y_test, config=adv_cfg)
torch.manual_seed(seed)
adv_cnn = StandardCNN(num_classes=4)
adv_train_meta = train_pgd_adversarial_cnn(
adv_cnn,
x_train,
y_train,
adv_config=adv_cfg,
epochs=epochs_adv,
batch_size=batch_sz,
lr=lr_std,
clean_mix_weight=0.25,
seed=seed,
inner_pgd_steps=inner_adv_steps,
)
at_adv_eval = evaluate_adversarial_accuracy(adv_cnn, x_test, y_test, config=adv_cfg)
# Randomized Smoothing certification across a slice of test samples
rs_cfg = SmoothingConfig(
sigma=0.10,
n_select=24 if quick else 48,
n_certify=64 if quick else 400,
alpha_conf=0.001,
seed=seed,
)
n_cert_imgs = 2 if quick else 16
rs_radii: list[float] = []
rs_correct_certified = 0
rs_abstain = 0
for idx in range(n_cert_imgs):
cert = certify_randomized_smoothing(
adv_cnn,
x_test[idx],
config=SmoothingConfig(
sigma=rs_cfg.sigma,
n_select=rs_cfg.n_select,
n_certify=rs_cfg.n_certify,
alpha_conf=rs_cfg.alpha_conf,
seed=seed + idx * 17,
),
)
if cert["abstain"]:
rs_abstain += 1
else:
rs_radii.append(float(cert["certified_l2_radius"]))
if cert["predicted_class"] == int(y_test[idx]):
rs_correct_certified += 1
rs_mean_radius = float(np.mean(rs_radii)) if rs_radii else 0.0
rs_certified_acc = float(rs_correct_certified) / float(n_cert_imgs)
# 5. Visual XAI & Faithfulness (Grad-CAM, Integrated Gradients, RISE, Deletion/Insertion, Adebayo)
xai_cfg = XAIConfig(
ig_steps=16 if quick else 48,
rise_masks=24 if quick else 120,
rise_grid=6,
faithfulness_steps=6 if quick else 16,
seed=seed,
)
# Pick defect test samples (classes 1, 2, 3) that std_cnn predicts accurately
defect_indices = [i for i in range(len(y_test)) if int(y_test[i]) in (1, 2, 3)]
eval_indices = defect_indices[: (2 if quick else 12)]
gc_del_aucs: list[float] = []
gc_ins_aucs: list[float] = []
ig_del_aucs: list[float] = []
ig_ins_aucs: list[float] = []
rnd_del_aucs: list[float] = []
rnd_ins_aucs: list[float] = []
ig_comp_errs: list[float] = []
gc_roi_energy: list[float] = []
adebayo_gc_corrs: list[float] = []
adebayo_ig_corrs: list[float] = []
for j, idx in enumerate(eval_indices):
img_i = x_test[idx]
lbl_i = int(y_test[idx])
roi_i = mask_test[idx]
gc_res = compute_gradcam(std_cnn, img_i, std_cnn.target_conv_layer, target_class=lbl_i)
ig_res = compute_integrated_gradients(std_cnn, img_i, target_class=lbl_i, steps=xai_cfg.ig_steps)
ig_comp_errs.append(float(ig_res["completeness_abs_error"]))
# Fraction of Grad-CAM energy inside ground-truth defect ROI normalized by ROI area ratio
roi_sum = float(np.sum(gc_res["heatmap"] * roi_i))
tot_sum = float(np.sum(gc_res["heatmap"])) + 1e-8
gc_roi_energy.append(roi_sum / tot_sum)
f_gc = evaluate_deletion_insertion_auc(
std_cnn, img_i, gc_res["heatmap"], lbl_i, steps=xai_cfg.faithfulness_steps, seed=seed + j
)
f_ig = evaluate_deletion_insertion_auc(
std_cnn, img_i, ig_res["heatmap"], lbl_i, steps=xai_cfg.faithfulness_steps, seed=seed + j
)
gc_del_aucs.append(float(f_gc["deletion_auc"]))
gc_ins_aucs.append(float(f_gc["insertion_auc"]))
ig_del_aucs.append(float(f_ig["deletion_auc"]))
ig_ins_aucs.append(float(f_ig["insertion_auc"]))
rnd_del_aucs.append(float(f_gc["random_deletion_auc"]))
rnd_ins_aucs.append(float(f_gc["random_insertion_auc"]))
if j < (1 if quick else 4):
ad = check_adebayo_weight_randomization_sanity(std_cnn, img_i, lbl_i, seed=seed + j)
adebayo_gc_corrs.append(float(ad["gradcam_abs_corr_after_randomization"]))
adebayo_ig_corrs.append(float(ad["ig_abs_corr_after_randomization"]))
rise_sample = compute_rise_saliency(
std_cnn, x_test[eval_indices[0]], int(y_test[eval_indices[0]]), xai_cfg
)
rise_faith = evaluate_deletion_insertion_auc(
std_cnn,
x_test[eval_indices[0]],
rise_sample["heatmap"],
int(y_test[eval_indices[0]]),
steps=xai_cfg.faithfulness_steps,
seed=seed,
)
xai_summary = {
"gradcam_mean_deletion_auc": float(np.mean(gc_del_aucs)),
"gradcam_mean_insertion_auc": float(np.mean(gc_ins_aucs)),
"ig_mean_deletion_auc": float(np.mean(ig_del_aucs)),
"ig_mean_insertion_auc": float(np.mean(ig_ins_aucs)),
"random_mean_deletion_auc": float(np.mean(rnd_del_aucs)),
"random_mean_insertion_auc": float(np.mean(rnd_ins_aucs)),
"rise_sample_deletion_auc": float(rise_faith["deletion_auc"]),
"rise_sample_insertion_auc": float(rise_faith["insertion_auc"]),
"ig_max_completeness_error": float(np.max(ig_comp_errs)),
"ig_mean_completeness_error": float(np.mean(ig_comp_errs)),
"gradcam_mean_roi_energy": float(np.mean(gc_roi_energy)),
"adebayo_gradcam_mean_corr": float(np.mean(adebayo_gc_corrs)),
"adebayo_ig_mean_corr": float(np.mean(adebayo_ig_corrs)),
}
pgd_rescue_pp = (at_adv_eval["pgd_accuracy"] - std_adv_eval["pgd_accuracy"]) * 100.0
# Workbench panels: strictly 6 KPIs, 4 bars, 4 tables matching platform schema
workbench_panels = {
"kpis": [
{
"id": "kpi_hog_vs_cnn_accuracy",
"label": "PCB AOI: HOG Classical vs CNN",
"value": f"{std_eval['accuracy'] * 100:.1f}%",
"unit": f"(HOG {hog_res['test_accuracy'] * 100:.1f}%)",
"status": "ok",
"detail": (
f"StandardCNN achieves {std_eval['accuracy']*100:.1f}% vs classical HOG+Ridge "
f"{hog_res['test_accuracy']*100:.1f}% (DW-Sep CNN {dw_eval['accuracy']*100:.1f}%)."
),
},
{
"id": "kpi_dwsep_efficiency",
"label": "Depthwise-Separable Efficiency",
"value": f"{mac_reduction:.2f}x MACs",
"unit": f"({param_reduction:.2f}x Params)",
"status": "ok",
"detail": (
f"DW-Sep cuts params {std_stats['params']} -> {dw_stats['params']} and MACs "
f"{std_stats['macs']:,} -> {dw_stats['macs']:,}; "
f"RF final = {rf_stack[-1]['receptive_field']} px."
),
},
{
"id": "kpi_safetensors_onnx_parity",
"label": "Safetensors & ONNX ORT Parity",
"value": f"{onnx_parity['max_abs_diff']:.2e}",
"unit": f"(sf {sf_diff:.1e})",
"status": "ok",
"detail": (
f"Zero-pickle safetensors ({len(sf_bytes)} B); ONNX dynamo=False ORT CPU "
f"{onnx_parity['ort_ms_per_image']:.3f} ms/img."
),
},
{
"id": "kpi_pgd_adv_training_rescue",
"label": "PGD-10 Robust Acc Rescue (eps=0.06)",
"value": f"{at_adv_eval['pgd_accuracy'] * 100:.1f}%",
"unit": f"(+{pgd_rescue_pp:.1f} pp)",
"status": "ok",
"detail": (
f"StandardCNN collapses to {std_adv_eval['pgd_accuracy']*100:.1f}% under PGD-10; "
f"PGD-AT rescues to {at_adv_eval['pgd_accuracy']*100:.1f}% "
f"(Clean {at_adv_eval['clean_accuracy']*100:.1f}%)."
),
},
{
"id": "kpi_randomized_smoothing_radius",
"label": "Randomized Smoothing L2 Cert",
"value": f"R={rs_mean_radius:.3f}",
"unit": f"(Cert Acc {rs_certified_acc * 100:.0f}%)",
"status": "ok",
"detail": (
f"Cohen et al. Neyman-Pearson radius at sigma={rs_cfg.sigma}, alpha={rs_cfg.alpha_conf}; "
f"abstain={rs_abstain}/{n_cert_imgs}."
),
},
{
"id": "kpi_visual_xai_faithfulness",
"label": "Visual XAI Deletion AUC & IG Axiom",
"value": f"{xai_summary['ig_mean_deletion_auc']:.3f}",
"unit": f"(Rand {xai_summary['random_mean_deletion_auc']:.3f})",
"status": "ok",
"detail": (
f"Grad-CAM Del={xai_summary['gradcam_mean_deletion_auc']:.3f}, "
f"IG Completeness max err={xai_summary['ig_max_completeness_error']:.2e}, "
f"Adebayo corr={xai_summary['adebayo_gradcam_mean_corr']:.2f}."
),
},
],
"bars": [
{
"id": "bar_classical_vs_cnn_accuracy",
"title": "PCB Defect Classification Accuracy: Classical HOG vs CNN Backbones (%)",
"metric_label": "Test Accuracy (%)",
"items": [
{
"label": "hog_ridge_baseline",
"value": round(hog_res["test_accuracy"] * 100.0, 2),
"display": f"{hog_res['test_accuracy'] * 100:.1f}% ({hog_res['feature_dim']}d HOG)",
"css_class": "is-mid",
},
{
"label": "standard_cnn",
"value": round(std_eval["accuracy"] * 100.0, 2),
"display": f"{std_eval['accuracy'] * 100:.1f}% ({std_stats['params']} params)",
"css_class": "is-fast",
},
{
"label": "dwsep_mobilenet_cnn",
"value": round(dw_eval["accuracy"] * 100.0, 2),
"display": f"{dw_eval['accuracy'] * 100:.1f}% ({dw_stats['params']} params)",
"css_class": "is-fast",
},
{
"label": "pgd_adv_trained_cnn",
"value": round(at_adv_eval["clean_accuracy"] * 100.0, 2),
"display": f"{at_adv_eval['clean_accuracy'] * 100:.1f}% (Clean, PGD-AT)",
"css_class": "is-mid",
},
],
},
{
"id": "bar_dwsep_macs_comparison",
"title": "Compute Footprint: Standard 2D Conv vs Depthwise-Separable CNN (kMACs)",
"metric_label": "kMACs (Lower is Faster)",
"items": [
{
"label": "standard_cnn_kmacs",
"value": round(std_stats["macs"] / 1000.0, 2),
"display": f"{std_stats['macs'] / 1000:.1f} kMACs (1.00x)",
"css_class": "is-slow",
},
{
"label": "dwsep_cnn_kmacs",
"value": round(dw_stats["macs"] / 1000.0, 2),
"display": f"{dw_stats['macs'] / 1000:.1f} kMACs ({mac_reduction:.2f}x faster)",
"css_class": "is-fast",
},
{
"label": "block3_std_kmacs",
"value": round(float(dwsep_block_cmp["std_macs"]) / 1000.0, 2),
"display": f"Layer 3x3 Std: {float(dwsep_block_cmp['std_macs']) / 1000:.1f} kMACs",
"css_class": "is-slow",
},
{
"label": "block3_dwsep_kmacs",
"value": round(float(dwsep_block_cmp["dwsep_macs"]) / 1000.0, 2),
"display": (
f"Layer DW-Sep: {float(dwsep_block_cmp['dwsep_macs']) / 1000:.1f} kMACs "
f"({float(dwsep_block_cmp['speedup_factor_macs']):.2f}x)"
),
"css_class": "is-fast",
},
],
},
{
"id": "bar_adversarial_robustness_rescue",
"title": "Adversarial Robustness Under L_inf Attack (eps=0.06): Standard vs PGD-AT (%)",
"metric_label": "Accuracy (%)",
"items": [
{
"label": "std_cnn_fgsm",
"value": round(std_adv_eval["fgsm_accuracy"] * 100.0, 2),
"display": f"Std FGSM: {std_adv_eval['fgsm_accuracy'] * 100:.1f}%",
"css_class": "is-mid",
},
{
"label": "std_cnn_pgd10",
"value": round(std_adv_eval["pgd_accuracy"] * 100.0, 2),
"display": f"Std PGD-10: {std_adv_eval['pgd_accuracy'] * 100:.1f}% (Collapse)",
"css_class": "is-slow",
},
{
"label": "pgd_at_fgsm",
"value": round(at_adv_eval["fgsm_accuracy"] * 100.0, 2),
"display": f"PGD-AT FGSM: {at_adv_eval['fgsm_accuracy'] * 100:.1f}%",
"css_class": "is-fast",
},
{
"label": "pgd_at_pgd10",
"value": round(at_adv_eval["pgd_accuracy"] * 100.0, 2),
"display": f"PGD-AT PGD-10: {at_adv_eval['pgd_accuracy'] * 100:.1f}% (Rescued)",
"css_class": "is-fast",
},
],
},
{
"id": "bar_visual_xai_faithfulness",
"title": "Visual XAI Faithfulness: Deletion AUC (Low) vs Insertion AUC (High)",
"metric_label": "AUC Score",
"items": [
{
"label": "random_deletion_auc",
"value": round(xai_summary["random_mean_deletion_auc"], 4),
"display": f"Random Del: {xai_summary['random_mean_deletion_auc']:.3f}",
"css_class": "is-slow",
},
{
"label": "gradcam_deletion_auc",
"value": round(xai_summary["gradcam_mean_deletion_auc"], 4),
"display": f"Grad-CAM Del: {xai_summary['gradcam_mean_deletion_auc']:.3f}",
"css_class": "is-fast",
},
{
"label": "ig_deletion_auc",
"value": round(xai_summary["ig_mean_deletion_auc"], 4),
"display": f"IG Del: {xai_summary['ig_mean_deletion_auc']:.3f}",
"css_class": "is-fast",
},
{
"label": "ig_insertion_auc",
"value": round(xai_summary["ig_mean_insertion_auc"], 4),
"display": (
f"IG Ins: {xai_summary['ig_mean_insertion_auc']:.3f} "
f"(vs Rand {xai_summary['random_mean_insertion_auc']:.3f})"
),
"css_class": "is-fast",
},
],
},
],
"tables": [
{
"id": "tbl_classical_preprocessing_and_hog",
"title": "Tier 1 Classical Image Processing, Morphology & HOG Baseline",
"columns": ["Operator / Pipeline", "Output Shape / Dim", "Observed Property", "Status"],
"rows": [
[
"RGB -> HSV / YCbCr / PIL Round-Trip",
f"{hsv.shape[0]}x{hsv.shape[1]}x3",
f"PIL uint8 max err = {pil_max_err:.4f} (Y mean={float(ycbcr[:,:,0].mean()):.3f})",
"PASS",
],
[
"Global HistEq vs CLAHE (4x4, clip=2.5)",
f"{gray.shape[0]}x{gray.shape[1]}",
(
f"Std: raw {float(gray.std()):.3f} -> HistEq {float(eq_global.std()):.3f} "
f"| CLAHE {float(eq_clahe.std()):.3f}"
),
"PASS",
],
[
"Gaussian + Sobel + Canny + Open/Close",
f"{canny.shape[0]}x{canny.shape[1]}",
f"Canny px={int(canny.sum())} | Open={int(opened.sum())} | Close={int(closed.sum())}",
"PASS",
],
[
"HOG (cell=4, block=2x2, 9 bins, L2-Hys) + Ridge",
f"{hog_res['feature_dim']} dims",
(
f"Train {hog_res['train_accuracy']*100:.1f}% "
f"| Test {hog_res['test_accuracy']*100:.1f}%"
),
"BASELINE",
],
],
},
{
"id": "tbl_conv_receptive_field_and_flops",
"title": "Exact Convolution Receptive-Field Recurrence & DW-Sep / Grouped Reduction",
"columns": ["Layer / Comparison", "Out Spatial", "Receptive Field / Jump", "Params & MACs"],
"rows": [
[
row["name"],
f"{row['out_size']}x{row['out_size']}",
f"RF={row['receptive_field']} px (j={row['effective_stride']})",
f"{row['params']:,} params | {row['macs']:,} MACs",
]
for row in rf_stack
]
+ [
[
"Block 48->64 (3x3): Std vs DW-Sep",
"8x8",
(
f"Ratio {float(dwsep_block_cmp['mac_ratio']):.4f} "
f"(Theory {float(dwsep_block_cmp['theoretical_ratio']):.4f})"
),
(
f"{float(dwsep_block_cmp['speedup_factor_macs']):.2f}x MACs | "
f"Grouped(G=4)={float(grouped_cmp['reduction_ratio']):.2f}x"
),
]
],
},
{
"id": "tbl_cnn_models_and_adversarial_audit",
"title": "CNN Efficiency, Zero-Pickle Deployment & Adversarial Robustness Audit",
"columns": ["Model / Regime", "Clean Acc", "FGSM / PGD-10 (eps=0.06)", "Deployment / Cert"],
"rows": [
[
"StandardCNN (RandAugment)",
f"{std_eval['accuracy']*100:.1f}% (F1 {std_eval['macro_f1']*100:.1f}%)",
(
f"FGSM {std_adv_eval['fgsm_accuracy']*100:.1f}% "
f"| PGD {std_adv_eval['pgd_accuracy']*100:.1f}%"
),
f"{std_stats['params']:,} params | {std_stats['macs']:,} MACs",
],
[
"DepthwiseSeparableCNN (Edge)",
f"{dw_eval['accuracy']*100:.1f}% (F1 {dw_eval['macro_f1']*100:.1f}%)",
f"{mac_reduction:.2f}x fewer MACs ({param_reduction:.2f}x params)",
(
f"sf diff={sf_diff:.1e} | ORT {onnx_parity['max_abs_diff']:.2e} "
f"({onnx_parity['ort_ms_per_image']:.3f} ms)"
),
],
[
"PGD Adversarial Trained CNN (Madry)",
f"{at_adv_eval['clean_accuracy']*100:.1f}%",
(
f"FGSM {at_adv_eval['fgsm_accuracy']*100:.1f}% | "
f"PGD {at_adv_eval['pgd_accuracy']*100:.1f}% (+{pgd_rescue_pp:.1f} pp)"
),
f"L_inf max={at_adv_eval['pgd_max_linf']:.4f} <= {adv_cfg.epsilon}",
],
[
f"Randomized Smoothing (sigma={rs_cfg.sigma})",
f"Cert Acc {rs_certified_acc*100:.1f}%",
f"Mean L2 Radius R = {rs_mean_radius:.4f}",
f"Clopper-Pearson alpha={rs_cfg.alpha_conf} | Abstain {rs_abstain}/{n_cert_imgs}",
],
],
},
{
"id": "tbl_visual_xai_faithfulness_audit",
"title": "Visual XAI Faithfulness (Deletion/Insertion AUC), Completeness & Adebayo Sanity",
"columns": [
"XAI Method",
"Deletion AUC (Low)",
"Insertion AUC (High)",
"Axiom / Sanity Check",
],
"rows": [
[
"Grad-CAM (Forward/Backward Hook)",
f"{xai_summary['gradcam_mean_deletion_auc']:.4f}",
f"{xai_summary['gradcam_mean_insertion_auc']:.4f}",
(
f"Adebayo corr={xai_summary['adebayo_gradcam_mean_corr']:.3f} | "
f"ROI energy={xai_summary['gradcam_mean_roi_energy']*100:.1f}%"
),
],
[
f"Integrated Gradients (M={xai_cfg.ig_steps})",
f"{xai_summary['ig_mean_deletion_auc']:.4f}",
f"{xai_summary['ig_mean_insertion_auc']:.4f}",
(
f"Completeness err={xai_summary['ig_max_completeness_error']:.2e} | "
f"Adebayo={xai_summary['adebayo_ig_mean_corr']:.3f}"
),
],
[
f"RISE Black-Box (N={xai_cfg.rise_masks})",
f"{xai_summary['rise_sample_deletion_auc']:.4f}",
f"{xai_summary['rise_sample_insertion_auc']:.4f}",
"Gradient-free Monte Carlo occlusion",
],
[
"Random Pixel Masking Baseline",
f"{xai_summary['random_mean_deletion_auc']:.4f}",
f"{xai_summary['random_mean_insertion_auc']:.4f}",
"Reference uninformative baseline",
],
],
},
],
}
return {
"config": {
"seed": seed,
"quick": quick,
"image_size": ds_cfg.image_size,
"n_train_total": int(x_train.shape[0]),
"n_test_total": int(x_test.shape[0]),
"epsilon_linf": adv_cfg.epsilon,
"pgd_steps": adv_cfg.pgd_steps,
"smoothing_sigma": rs_cfg.sigma,
},
"tier1_image_processing": {
"pil_roundtrip_max_err": pil_max_err,
"gray_std_raw": float(gray.std()),
"gray_std_global_histeq": float(eq_global.std()),
"gray_std_clahe": float(eq_clahe.std()),
"sobel_max_mag": float(sob["magnitude"].max()),
"canny_edge_pixels": int(canny.sum()),
"morph_open_pixels": int(opened.sum()),
"morph_close_pixels": int(closed.sum()),
"hog_baseline": hog_res,
},
"conv_geometry": {
"receptive_field_stack": rf_stack,
"dwsep_block_comparison": dwsep_block_cmp,
"grouped_conv_comparison": grouped_cmp,
},
"augmentations": {
"randaugment_min": float(aug_ra.min().item()),
"randaugment_max": float(aug_ra.max().item()),
"mixup_lambda": lam_mixup,
"mixup_label_sum": float(aug_my.sum(dim=1).mean().item()),
"cutmix_lambda": lam_cutmix,
"cutmix_label_sum": float(aug_cy.sum(dim=1).mean().item()),
"mosaic_shape": list(mosaic_img.shape),
},
"cnn_models": {
"standard_cnn": {
**std_stats,
**std_eval,
"final_train_loss": std_train["final_train_loss"],
},
"dwsep_cnn": {
**dw_stats,
**dw_eval,
"final_train_loss": dw_train["final_train_loss"],
},
"param_reduction_factor": param_reduction,
"mac_reduction_factor": mac_reduction,
"safetensors_bytes": len(sf_bytes),
"safetensors_max_diff": sf_diff,
"onnx_parity": onnx_parity,
},
"adversarial_robustness": {
"standard_cnn_under_attack": std_adv_eval,
"pgd_at_training": adv_train_meta,
"pgd_at_under_attack": at_adv_eval,
"pgd_robust_rescue_pp": pgd_rescue_pp,
"randomized_smoothing": {
"sigma": rs_cfg.sigma,
"alpha_conf": rs_cfg.alpha_conf,
"n_evaluated": n_cert_imgs,
"n_abstain": rs_abstain,
"certified_accuracy": rs_certified_acc,
"mean_certified_l2_radius": rs_mean_radius,
},
},
"visual_xai": xai_summary,
"workbench_panels": workbench_panels,
}
def main() -> None:
parser = argparse.ArgumentParser(description="Run Lab 08 CV, CNN, Robustness & Visual XAI Demo")
parser.add_argument("--seed", type=int, default=42)
parser.add_argument("--quick", action="store_true", help="Fast mode for automated CI verification")
parser.add_argument(
"--output",
type=str,
default="artifacts/ch16_lab08_results.json",
help="Output JSON artifact path",
)
args = parser.parse_args()
result = run_lab08_benchmark(seed=args.seed, quick=args.quick)
out_path = Path(args.output)
out_path.parent.mkdir(parents=True, exist_ok=True)
out_path.write_text(json.dumps(result, indent=2), encoding="utf-8")
hog_acc = result["tier1_image_processing"]["hog_baseline"]["test_accuracy"] * 100.0
std_acc = result["cnn_models"]["standard_cnn"]["accuracy"] * 100.0
dw_acc = result["cnn_models"]["dwsep_cnn"]["accuracy"] * 100.0
mac_red = result["cnn_models"]["mac_reduction_factor"]
pgd_std = result["adversarial_robustness"]["standard_cnn_under_attack"]["pgd_accuracy"] * 100.0
pgd_at = result["adversarial_robustness"]["pgd_at_under_attack"]["pgd_accuracy"] * 100.0
ig_del = result["visual_xai"]["ig_mean_deletion_auc"]
print(
f"[Lab 08] Saved {out_path} | HOG={hog_acc:.1f}% | StdCNN={std_acc:.1f}% "
f"| DW-Sep={dw_acc:.1f}% ({mac_red:.2f}x MACs) "
f"| PGD Std={pgd_std:.1f}% -> AT={pgd_at:.1f}% | IG DelAUC={ig_del:.3f}"
)
if __name__ == "__main__":
main()
"""16 deterministic offline unit, mathematical, robustness, Visual XAI & AST security tests for Lab 08."""
from __future__ import annotations
import ast
import json
import struct
import subprocess
import sys
from pathlib import Path
import numpy as np
import pytest
import torch
from pydantic import ValidationError
from scipy import stats
from cv_cnn_robustness_lab.adversarial import (
AdversarialConfig,
SmoothingConfig,
certify_randomized_smoothing,
clopper_pearson_lower_bound,
evaluate_adversarial_accuracy,
fgsm_attack,
pgd_linf_attack,
train_pgd_adversarial_cnn,
)
from cv_cnn_robustness_lab.cnn_models import (
DepthwiseSeparableCNN,
StandardCNN,
TrainConfig,
apply_cutmix_batch,
apply_mixup_batch,
apply_randaugment_batch,
build_mosaic_quad,
count_model_params_and_macs,
evaluate_cnn_classifier,
export_and_verify_onnx_parity,
load_cnn_safetensors,
save_cnn_safetensors,
train_cnn_classifier,
)
from cv_cnn_robustness_lab.color_and_filters import (
DatasetConfig,
HOGConfig,
array_to_pil_and_back,
binary_close,
binary_dilate,
binary_erode,
binary_open,
canny_hysteresis_edges,
clahe_tile_equalize,
conv2d_numpy,
evaluate_hog_linear_baseline,
extract_hog_descriptor,
gaussian_blur,
generate_aoi_pcb_dataset,
histogram_equalize_uint8,
laplacian_filter,
rgb_to_hsv,
rgb_to_ycbcr,
sobel_edges,
)
from cv_cnn_robustness_lab.conv_geometry import (
ConvLayerSpec,
compare_standard_vs_dwsep_conv,
compute_grouped_conv_stats,
compute_receptive_field_stack,
conv_output_size,
)
from cv_cnn_robustness_lab.visual_xai import (
XAIConfig,
check_adebayo_weight_randomization_sanity,
compute_gradcam,
compute_integrated_gradients,
compute_rise_saliency,
evaluate_deletion_insertion_auc,
)
LAB_ROOT = Path(__file__).resolve().parents[1]
@pytest.fixture(scope="module")
def shared_dataset_and_models() -> dict[str, object]:
"""Build deterministic PCB dataset and trained Standard/DW-Sep/PGD-AT CNNs once for fast tests."""
ds = generate_aoi_pcb_dataset(
DatasetConfig(image_size=32, n_train_per_class=48, n_test_per_class=20, noise_std=0.035, seed=42)
)
torch.manual_seed(42)
std_cnn = StandardCNN(num_classes=4)
train_cnn_classifier(
std_cnn,
ds["x_train"],
ds["y_train"],
config=TrainConfig(epochs=9, batch_size=32, lr=5e-3, use_augmentation=True, seed=42),
)
torch.manual_seed(42)
dw_cnn = DepthwiseSeparableCNN(num_classes=4)
train_cnn_classifier(
dw_cnn,
ds["x_train"],
ds["y_train"],
config=TrainConfig(epochs=9, batch_size=32, lr=5e-3, use_augmentation=True, seed=42),
)
torch.manual_seed(42)
adv_cfg = AdversarialConfig(epsilon=0.06, pgd_steps=10, step_size=0.015, random_start=True, seed=42)
adv_cnn = StandardCNN(num_classes=4)
train_pgd_adversarial_cnn(
adv_cnn,
ds["x_train"],
ds["y_train"],
adv_config=adv_cfg,
epochs=5,
batch_size=32,
lr=5e-3,
clean_mix_weight=0.25,
seed=42,
inner_pgd_steps=2,
)
return {
"ds": ds,
"std_cnn": std_cnn,
"dw_cnn": dw_cnn,
"adv_cnn": adv_cnn,
"adv_cfg": adv_cfg,
}
# ---------------------------------------------------------------------------
# Test 01: Strict Pydantic Configs Reject Unknown Fields & Out-of-Range Inputs
# ---------------------------------------------------------------------------
def test_01_pydantic_configs_strict_forbid() -> None:
with pytest.raises(ValidationError):
DatasetConfig(unknown_flag=True) # type: ignore[call-arg]
with pytest.raises(ValidationError):
HOGConfig(num_bins=1)
with pytest.raises(ValidationError):
ConvLayerSpec(name="c1", in_channels=0, out_channels=8, kernel_size=3)
with pytest.raises(ValidationError):
AdversarialConfig(epsilon=0.9)
with pytest.raises(ValidationError):
SmoothingConfig(alpha_conf=0.8)
with pytest.raises(ValidationError):
XAIConfig(ig_steps=2)
# ---------------------------------------------------------------------------
# Test 02: Color Spaces (HSV, YCbCr), Histogram Eq / CLAHE & PIL Round-Trip
# ---------------------------------------------------------------------------
def test_02_color_spaces_and_clahe_pil_roundtrip() -> None:
# Exact primary color verification in HSV & YCbCr
primaries = np.array([[[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]], dtype=np.float32)
hsv = rgb_to_hsv(primaries)
assert np.allclose(hsv[0, :, 0], [0.0, 120.0, 240.0], atol=1e-4)
assert np.allclose(hsv[0, :, 1], [1.0, 1.0, 1.0], atol=1e-4)
assert np.allclose(hsv[0, :, 2], [1.0, 1.0, 1.0], atol=1e-4)
ycbcr = rgb_to_ycbcr(primaries)
assert np.allclose(ycbcr[0, :, 0], [0.299, 0.587, 0.114], atol=1e-4)
assert float(ycbcr[0, 2, 1]) > 0.9 # Blue has high Cb
assert float(ycbcr[0, 0, 2]) > 0.9 # Red has high Cr
# Low-contrast patch improved by HistEq & CLAHE
rng = np.random.default_rng(7)
low_c = np.clip(0.45 + 0.06 * rng.normal(size=(32, 32)), 0.0, 1.0).astype(np.float32)
eq_g = histogram_equalize_uint8(low_c)
eq_c = clahe_tile_equalize(low_c, grid_size=4, clip_limit=2.5)
assert float(eq_g.std()) > float(low_c.std()) * 2.0
assert float(eq_c.std()) > float(low_c.std()) * 1.5
ds = generate_aoi_pcb_dataset(DatasetConfig(n_train_per_class=12, n_test_per_class=8, seed=1))
rgb_chw = ds["x_train"][0]
restored = array_to_pil_and_back(rgb_chw)
assert restored.shape == (32, 32, 3)
assert float(np.max(np.abs(np.transpose(rgb_chw, (1, 2, 0)) - restored))) <= (1.0 / 255.0 + 1e-4)
# ---------------------------------------------------------------------------
# Test 03: Spatial Filters (Conv2D, Gaussian, Sobel, Laplacian, Canny & Morphology)
# ---------------------------------------------------------------------------
def test_03_spatial_filters_sobel_canny_and_morphology() -> None:
# Vertical step edge at x=16
step = np.zeros((32, 32), dtype=np.float32)
step[:, 16:] = 1.0
blur = gaussian_blur(step, kernel_size=5, sigma=1.0)
assert blur.shape == (32, 32)
assert float(blur[16, 16]) < 1.0 and float(blur[16, 15]) > 0.0
sob = sobel_edges(step)
assert float(np.abs(sob["gx"][:, 15:17]).mean()) > 2.0
assert float(np.abs(sob["gy"]).max()) < 1e-5
lap = laplacian_filter(step)
assert float(np.abs(lap[:, 15:17]).max()) > 1.0
canny = canny_hysteresis_edges(step, sigma=1.0, low_ratio=0.15, high_ratio=0.35)
assert int(canny[:, 15:17].sum()) >= 20
assert int(canny[:, :10].sum()) == 0
# Valid convolution dimension sanity
valid_out = conv2d_numpy(step, np.ones((3, 3), dtype=np.float32), padding="valid", stride=2)
assert valid_out.shape == (15, 15)
# Morphology: Opening removes 1px white speckle; Closing fills 1px black hole
mask_speckle = np.zeros((16, 16), dtype=np.bool_)
mask_speckle[4:12, 4:12] = True
mask_speckle[1, 1] = True # isolated speckle
opened = binary_open(mask_speckle, kernel_size=3)
assert not bool(opened[1, 1])
assert bool(opened[8, 8])
mask_hole = np.zeros((16, 16), dtype=np.bool_)
mask_hole[4:12, 4:12] = True
mask_hole[8, 8] = False # isolated dark void
closed = binary_close(mask_hole, kernel_size=3)
assert bool(closed[8, 8])
assert int(binary_dilate(mask_hole).sum()) > int(binary_erode(mask_hole).sum())
# ---------------------------------------------------------------------------
# Test 04: HOG L2-Hys Block Normalization, Brightness Invariance & Classical Baseline
# ---------------------------------------------------------------------------
def test_04_hog_descriptor_l2hys_invariance_and_baseline(
shared_dataset_and_models: dict[str, object],
) -> None:
ds = shared_dataset_and_models["ds"]
assert isinstance(ds, dict)
img = ds["x_test"][0]
cfg = HOGConfig(cell_size=4, block_cells=2, num_bins=9)
h1 = extract_hog_descriptor(img, cfg)
# Uniform multiplicative brightness scaling should leave L2-Hys HOG nearly invariant
h2 = extract_hog_descriptor(np.clip(img * 0.65, 0.0, 1.0), cfg)
assert h1.ndim == 1
# Expected blocks for 32x32 with cell=4 -> 8x8 cells -> 7x7 blocks * (2*2*9) = 49 * 36 = 1764
assert h1.shape[0] == 1764
cos_sim = float(np.dot(h1, h2) / (np.linalg.norm(h1) * np.linalg.norm(h2) + 1e-8))
assert cos_sim > 0.99
hog_res = evaluate_hog_linear_baseline(ds["x_train"], ds["y_train"], ds["x_test"], ds["y_test"], cfg)
assert 0.55 <= hog_res["test_accuracy"] <= 1.0
# ---------------------------------------------------------------------------
# Test 05: Exact Convolution Output Size & Dilated Receptive-Field Recurrence
# ---------------------------------------------------------------------------
def test_05_conv_output_size_and_receptive_field_recurrence() -> None:
assert conv_output_size(32, kernel_size=3, stride=1, padding=1, dilation=1) == 32
assert conv_output_size(32, kernel_size=3, stride=2, padding=1, dilation=1) == 16
assert conv_output_size(32, kernel_size=3, stride=1, padding=2, dilation=2) == 32
assert conv_output_size(224, kernel_size=7, stride=2, padding=3, dilation=1) == 112
stack = [
ConvLayerSpec(name="c1", in_channels=3, out_channels=16, kernel_size=3, stride=1, padding=1),
ConvLayerSpec(name="p1", in_channels=16, out_channels=16, kernel_size=2, stride=2, is_pooling=True),
ConvLayerSpec(name="c2", in_channels=16, out_channels=32, kernel_size=3, stride=1, padding=1),
ConvLayerSpec(
name="c3_dil", in_channels=32, out_channels=64, kernel_size=3, stride=1, padding=2, dilation=2
),
]
rows = compute_receptive_field_stack(stack, input_size=32)
# r0=1, j0=1
# c1: r1 = 1 + (3-1)*1*1 = 3, j1 = 1
# p1: r2 = 3 + (2-1)*1*1 = 4, j2 = 2
# c2: r3 = 4 + (3-1)*1*2 = 8, j3 = 2
# c3_dil(d=2): r4 = 8 + (3-1)*2*2 = 16, j4 = 2
assert [r["receptive_field"] for r in rows] == [3, 4, 8, 16]
assert [r["effective_stride"] for r in rows] == [1, 2, 2, 2]
assert [r["out_size"] for r in rows] == [32, 16, 16, 16]
# ---------------------------------------------------------------------------
# Test 06: Depthwise-Separable & Grouped Convolution Exact FLOPs/Params Reduction
# ---------------------------------------------------------------------------
def test_06_depthwise_separable_and_grouped_flops_reduction() -> None:
cmp = compare_standard_vs_dwsep_conv(in_channels=48, out_channels=64, kernel_size=3, out_hw=8)
expected_ratio = (1.0 / 64.0) + (1.0 / 9.0)
assert np.isclose(cmp["mac_ratio"], expected_ratio, atol=1e-12)
assert np.isclose(cmp["theoretical_ratio"], expected_ratio, atol=1e-12)
assert float(cmp["speedup_factor_macs"]) > 7.5
# Depthwise conv has lower operational intensity than standard conv (memory-bound insight)
assert float(cmp["dw_oi_flops_per_byte"]) < float(cmp["std_oi_flops_per_byte"])
grp = compute_grouped_conv_stats(in_channels=48, out_channels=64, kernel_size=3, out_hw=8, groups=4)
assert np.isclose(grp["reduction_ratio"], 0.25, atol=1e-12)
# ---------------------------------------------------------------------------
# Test 07: Modern Vision Augmentations (RandAugment, MixUp, CutMix, Mosaic)
# ---------------------------------------------------------------------------
def test_07_augmentations_randaugment_cutmix_mixup_mosaic(
shared_dataset_and_models: dict[str, object],
) -> None:
ds = shared_dataset_and_models["ds"]
assert isinstance(ds, dict)
xb = torch.as_tensor(ds["x_train"][:8], dtype=torch.float32)
yb = torch.as_tensor(ds["y_train"][:8], dtype=torch.long)
ra = apply_randaugment_batch(xb, n_ops=2, magnitude=0.3, seed=42)
assert ra.shape == xb.shape
assert float(ra.min().item()) >= 0.0 and float(ra.max().item()) <= 1.0
mx, my, lam_m = apply_mixup_batch(xb, yb, num_classes=4, alpha=0.4, seed=42)
assert mx.shape == xb.shape and my.shape == (8, 4)
assert 0.0 <= lam_m <= 1.0
assert torch.allclose(my.sum(dim=1), torch.ones(8), atol=1e-5)
cx, cy, lam_c = apply_cutmix_batch(xb, yb, num_classes=4, alpha=1.0, seed=42)
assert cx.shape == xb.shape and cy.shape == (8, 4)
assert 0.0 <= lam_c <= 1.0
assert torch.allclose(cy.sum(dim=1), torch.ones(8), atol=1e-5)
mosaic = build_mosaic_quad(xb[:4], split_x=16, split_y=16)
assert mosaic.shape == (3, 32, 32)
assert torch.allclose(mosaic[:, :16, :16], xb[0, :, :16, :16])
assert torch.allclose(mosaic[:, 16:, 16:], xb[3, :, 16:, 16:])
# ---------------------------------------------------------------------------
# Test 08: StandardCNN vs DepthwiseSeparableCNN Accuracy & Efficiency Gain
# ---------------------------------------------------------------------------
def test_08_standard_vs_dwsep_cnn_training_and_efficiency(
shared_dataset_and_models: dict[str, object],
) -> None:
ds = shared_dataset_and_models["ds"]
std_cnn = shared_dataset_and_models["std_cnn"]
dw_cnn = shared_dataset_and_models["dw_cnn"]
assert isinstance(ds, dict)
assert isinstance(std_cnn, StandardCNN)
assert isinstance(dw_cnn, DepthwiseSeparableCNN)
std_eval = evaluate_cnn_classifier(std_cnn, ds["x_test"], ds["y_test"])
dw_eval = evaluate_cnn_classifier(dw_cnn, ds["x_test"], ds["y_test"])
std_stats = count_model_params_and_macs(std_cnn, input_hw=32)
dw_stats = count_model_params_and_macs(dw_cnn, input_hw=32)
assert std_eval["accuracy"] >= 0.90
assert dw_eval["accuracy"] >= 0.88
assert float(std_stats["params"]) / float(dw_stats["params"]) >= 3.0
assert float(std_stats["macs"]) / float(dw_stats["macs"]) >= 2.5
# ---------------------------------------------------------------------------
# Test 09: Zero-Pickle Safetensors Header Verification & ONNX (dynamo=False) Parity
# ---------------------------------------------------------------------------
def test_09_safetensors_zero_pickle_and_onnx_ort_parity(
shared_dataset_and_models: dict[str, object], tmp_path: Path
) -> None:
ds = shared_dataset_and_models["ds"]
dw_cnn = shared_dataset_and_models["dw_cnn"]
assert isinstance(ds, dict)
assert isinstance(dw_cnn, DepthwiseSeparableCNN)
sf_path = tmp_path / "dwsep_pcb.safetensors"
raw = save_cnn_safetensors(dw_cnn, path=sf_path)
header_len = struct.unpack("<Q", raw[:8])[0]
header_json = json.loads(raw[8 : 8 + header_len].decode("utf-8"))
assert "head.weight" in header_json
reloaded = load_cnn_safetensors(DepthwiseSeparableCNN(num_classes=4), sf_path)
xb = torch.as_tensor(ds["x_test"][:16], dtype=torch.float32)
with torch.no_grad():
sf_diff = float((dw_cnn(xb) - reloaded(xb)).abs().max().item())
assert sf_diff == 0.0
onnx_res = export_and_verify_onnx_parity(reloaded, ds["x_test"][:16])
assert onnx_res["max_abs_diff"] < 1e-4
assert onnx_res["onnx_bytes"] > 1000.0
# ---------------------------------------------------------------------------
# Test 10: FGSM & PGD L_inf Bounds, Domain Clamp & Attack Efficacy on StandardCNN
# ---------------------------------------------------------------------------
def test_10_fgsm_and_pgd_linf_bounds_and_attack_efficacy(
shared_dataset_and_models: dict[str, object],
) -> None:
ds = shared_dataset_and_models["ds"]
std_cnn = shared_dataset_and_models["std_cnn"]
adv_cfg = shared_dataset_and_models["adv_cfg"]
assert isinstance(ds, dict)
assert isinstance(std_cnn, StandardCNN)
assert isinstance(adv_cfg, AdversarialConfig)
x_t = torch.as_tensor(ds["x_test"], dtype=torch.float32)
y_t = torch.as_tensor(ds["y_test"], dtype=torch.long)
x_fgsm = fgsm_attack(std_cnn, x_t, y_t, epsilon=adv_cfg.epsilon)
x_pgd = pgd_linf_attack(std_cnn, x_t, y_t, config=adv_cfg)
assert float((x_fgsm - x_t).abs().max().item()) <= adv_cfg.epsilon + 1e-6
assert float((x_pgd - x_t).abs().max().item()) <= adv_cfg.epsilon + 1e-6
assert float(x_pgd.min().item()) >= 0.0 and float(x_pgd.max().item()) <= 1.0
res = evaluate_adversarial_accuracy(std_cnn, x_t, y_t, config=adv_cfg)
# PGD must significantly degrade standard CNN accuracy and be at least as strong as FGSM
assert res["clean_accuracy"] - res["pgd_accuracy"] >= 0.25
assert res["pgd_accuracy"] <= res["fgsm_accuracy"] + 0.05
# ---------------------------------------------------------------------------
# Test 11: PGD Adversarial Training Rescues Robust Accuracy
# ---------------------------------------------------------------------------
def test_11_pgd_adversarial_training_rescues_robust_accuracy(
shared_dataset_and_models: dict[str, object],
) -> None:
ds = shared_dataset_and_models["ds"]
std_cnn = shared_dataset_and_models["std_cnn"]
adv_cnn = shared_dataset_and_models["adv_cnn"]
adv_cfg = shared_dataset_and_models["adv_cfg"]
assert isinstance(ds, dict)
assert isinstance(std_cnn, StandardCNN)
assert isinstance(adv_cnn, StandardCNN)
assert isinstance(adv_cfg, AdversarialConfig)
std_res = evaluate_adversarial_accuracy(std_cnn, ds["x_test"], ds["y_test"], config=adv_cfg)
at_res = evaluate_adversarial_accuracy(adv_cnn, ds["x_test"], ds["y_test"], config=adv_cfg)
assert at_res["clean_accuracy"] >= 0.80
assert at_res["pgd_accuracy"] >= std_res["pgd_accuracy"] + 0.25
# ---------------------------------------------------------------------------
# Test 12: Randomized Smoothing L2 Certified Radius, Clopper-Pearson & Abstention
# ---------------------------------------------------------------------------
def test_12_randomized_smoothing_certified_radius_and_abstention(
shared_dataset_and_models: dict[str, object],
) -> None:
ds = shared_dataset_and_models["ds"]
adv_cnn = shared_dataset_and_models["adv_cnn"]
assert isinstance(ds, dict)
assert isinstance(adv_cnn, StandardCNN)
# Analytical Clopper-Pearson monotonicity check
lb_low = clopper_pearson_lower_bound(250, 400, 0.001)
lb_high = clopper_pearson_lower_bound(390, 400, 0.001)
assert 0.5 < lb_low < lb_high < 1.0
cfg = SmoothingConfig(sigma=0.10, n_select=48, n_certify=300, alpha_conf=0.001, seed=42)
cert = certify_randomized_smoothing(adv_cnn, ds["x_test"][0], config=cfg)
assert not cert["abstain"]
expected_r = float(cfg.sigma * stats.norm.ppf(cert["p_a_lower"]))
assert np.isclose(cert["certified_l2_radius"], expected_r, atol=1e-6)
assert cert["certified_l2_radius"] > 0.05
# Abstention check when model outputs tie/random noise across classes (p_A_lower <= 0.5)
class _RandomTieModel(torch.nn.Module):
def forward(self, x: torch.Tensor) -> torch.Tensor:
b = x.shape[0]
# Deterministic alternating class votes -> ~25% per class -> p_A_lower <= 0.5 -> ABSTAIN
idx = torch.arange(b) % 4
out = torch.zeros((b, 4), dtype=torch.float32)
out[torch.arange(b), idx] = 10.0
return out
cert_abs = certify_randomized_smoothing(_RandomTieModel(), ds["x_test"][0], config=cfg)
assert cert_abs["abstain"] is True
assert cert_abs["predicted_class"] is None
assert cert_abs["certified_l2_radius"] == 0.0
# ---------------------------------------------------------------------------
# Test 13: Grad-CAM Forward/Backward Hook & Defect ROI Localization
# ---------------------------------------------------------------------------
def test_13_gradcam_hook_and_roi_localization(shared_dataset_and_models: dict[str, object]) -> None:
ds = shared_dataset_and_models["ds"]
std_cnn = shared_dataset_and_models["std_cnn"]
assert isinstance(ds, dict)
assert isinstance(std_cnn, StandardCNN)
defect_idx = next(i for i in range(len(ds["y_test"])) if int(ds["y_test"][i]) in (1, 2, 3))
img = ds["x_test"][defect_idx]
lbl = int(ds["y_test"][defect_idx])
other_cls = (lbl + 1) % 4
gc = compute_gradcam(std_cnn, img, std_cnn.target_conv_layer, target_class=lbl)
gc_other = compute_gradcam(std_cnn, img, std_cnn.target_conv_layer, target_class=other_cls)
hmap = gc["heatmap"]
assert hmap.shape == (32, 32)
assert float(hmap.min()) >= 0.0 and float(hmap.max()) <= 1.0 + 1e-6
assert float(hmap.max()) > 0.5
# Class-discriminative check: different target class produces distinct Grad-CAM
assert not np.allclose(gc["raw_map"], gc_other["raw_map"])
# ---------------------------------------------------------------------------
# Test 14: Integrated Gradients Completeness Axiom Verification
# ---------------------------------------------------------------------------
def test_14_integrated_gradients_completeness_axiom(shared_dataset_and_models: dict[str, object]) -> None:
ds = shared_dataset_and_models["ds"]
std_cnn = shared_dataset_and_models["std_cnn"]
assert isinstance(ds, dict)
assert isinstance(std_cnn, StandardCNN)
for idx in range(4):
ig = compute_integrated_gradients(
std_cnn, ds["x_test"][idx], target_class=int(ds["y_test"][idx]), steps=64
)
assert ig["heatmap"].shape == (32, 32)
# Completeness Axiom: |sum(IG) - (F(x) - F(x'))| < 0.05
assert ig["completeness_abs_error"] < 0.05
# ---------------------------------------------------------------------------
# Test 15: Visual XAI Faithfulness (Deletion/Insertion AUC) & Adebayo Sanity Check
# ---------------------------------------------------------------------------
def test_15_visual_xai_deletion_insertion_faithfulness_and_adebayo_sanity(
shared_dataset_and_models: dict[str, object],
) -> None:
ds = shared_dataset_and_models["ds"]
std_cnn = shared_dataset_and_models["std_cnn"]
assert isinstance(ds, dict)
assert isinstance(std_cnn, StandardCNN)
defect_indices = [i for i in range(len(ds["y_test"])) if int(ds["y_test"][i]) in (1, 2, 3)][:6]
ig_del, ig_ins, rnd_del, rnd_ins = [], [], [], []
gc_del, gc_ins = [], []
for j, idx in enumerate(defect_indices):
img = ds["x_test"][idx]
lbl = int(ds["y_test"][idx])
gc = compute_gradcam(std_cnn, img, std_cnn.target_conv_layer, target_class=lbl)
ig = compute_integrated_gradients(std_cnn, img, target_class=lbl, steps=32)
f_gc = evaluate_deletion_insertion_auc(std_cnn, img, gc["heatmap"], lbl, steps=12, seed=42 + j)
f_ig = evaluate_deletion_insertion_auc(std_cnn, img, ig["heatmap"], lbl, steps=12, seed=42 + j)
gc_del.append(f_gc["deletion_auc"])
gc_ins.append(f_gc["insertion_auc"])
ig_del.append(f_ig["deletion_auc"])
ig_ins.append(f_ig["insertion_auc"])
rnd_del.append(f_gc["random_deletion_auc"])
rnd_ins.append(f_gc["random_insertion_auc"])
# Faithful XAI drops probability faster on Deletion and recovers faster on Insertion than random
assert float(np.mean(ig_del)) < float(np.mean(rnd_del))
assert float(np.mean(ig_ins)) > float(np.mean(rnd_ins))
assert float(np.mean(gc_del)) < float(np.mean(rnd_del))
# RISE black-box smoke check
rise = compute_rise_saliency(
std_cnn,
ds["x_test"][defect_indices[0]],
int(ds["y_test"][defect_indices[0]]),
XAIConfig(rise_masks=32),
)
assert rise["heatmap"].shape == (32, 32)
# Adebayo weight-randomization sanity check
ad = check_adebayo_weight_randomization_sanity(
std_cnn, ds["x_test"][defect_indices[0]], int(ds["y_test"][defect_indices[0]]), seed=42
)
assert ad["gradcam_passes_sanity"] == 1.0
assert ad["ig_passes_sanity"] == 1.0
# ---------------------------------------------------------------------------
# Test 16: CLI --quick Workbench Schema & AST Unsafe Deserialization Security Guard
# ---------------------------------------------------------------------------
def test_16_cli_workbench_schema_and_ast_security_guard(tmp_path: Path) -> None:
out_json = tmp_path / "quick_results.json"
proc = subprocess.run(
[
sys.executable,
str(LAB_ROOT / "scripts" / "run_lab_demo.py"),
"--quick",
"--seed",
"42",
"--output",
str(out_json),
],
cwd=str(LAB_ROOT),
capture_output=True,
text=True,
check=True,
)
assert "[Lab 08] Saved" in proc.stdout
data = json.loads(out_json.read_text(encoding="utf-8"))
panels = data["workbench_panels"]
assert len(panels["kpis"]) == 6
assert len(panels["bars"]) == 4
assert len(panels["tables"]) == 4
# AST security guard: strictly ban unsafe deserializers across src/, scripts/, tests/
banned_modules = {"pickle", "joblib", "cloudpickle", "dill", "shelve", "marshal"}
py_files = [
*list((LAB_ROOT / "src").rglob("*.py")),
*list((LAB_ROOT / "scripts").rglob("*.py")),
*list((LAB_ROOT / "tests").rglob("*.py")),
]
assert len(py_files) >= 7
for py_file in py_files:
tree = ast.parse(py_file.read_text(encoding="utf-8"), filename=str(py_file))
for node in ast.walk(tree):
if isinstance(node, ast.Import):
for alias in node.names:
root = alias.name.split(".")[0]
assert root not in banned_modules, f"Banned import '{root}' in {py_file}"
elif isinstance(node, ast.ImportFrom) and node.module is not None:
root = node.module.split(".")[0]
assert root not in banned_modules, f"Banned from-import '{root}' in {py_file}"
PCB AOI) dưới ánh sáng đèn LED nhà xưởng trôi ±16%, phát biểu nào ĐÚNG theo lý thuyết lấy mẫu Nyquist 2D và kết quả Lab 08?RGB, độ sáng và sắc độ trộn chặt nên cân bằng toàn cục làm lệch màu và khuếch đại nhiễu nền (gray std 0.135 -> 0.288); YCbCr + CLAHE cân bằng cục bộ êm hơn (0.177) và lọc Gaussian trước khi decimate tuân thủ Định lý Nyquist–Shannon 2D (Test 02, Test 03).
Canny, hình thái học Opening/Closing) và bộ mô tả HOG (Dalal & Triggs 2005) trong Lab 08?Opening quét nhiễu đốm sáng nhỏ nhờ co trước giãn sau, ngược lại Closing lấp lỗ tối nhờ giãn trước co sau (Test 03). Chuẩn hóa khối L2-Hys của HOG triệt tiêu nhân tử sáng cục bộ (cosine > 0.99, Test 04).
5 tầng trong Lab 08 trên ảnh 32×32: conv1(K=3, S=1, P=1) -> pool1(K=2, S=2) -> conv2(K=3, S=1, P=1) -> pool2(K=2, S=2) -> conv3(K=3, S=1, P=2, D=2). Kích thước bản đồ đặc trưng đầu ra, bước nhảy tích lũy \(j_5\) và trường tiếp nhận \(r_5\) lần lượt là bao nhiêu?conv1 cho \(r_1 = 3, j_1 = 1\); pool1 cho \(r_2 = 4, j_2 = 2\); conv2 cho \(r_3 = 4 + 2\cdot 1\cdot 2 = 8, j_3 = 2\); pool2 cho \(r_4 = 8 + 1\cdot 1\cdot 2 = 10, j_4 = 4\); conv3 (D=2) cho \(r_5 = 10 + 2\cdot 2\cdot 4 = 26\), kích thước ra \(8\times 8\) (Test 05).
3×3 với Tích chập Phân tách Chiều sâu (DW-Sep) trên khối 48 -> 64 (8×8) và toàn mạng Lab 08 (StandardCNN vs DepthwiseSeparableCNN), phát biểu nào ĐÚNG?DW-Sep tách lọc không gian (groups = C_in) và trộn kênh (1×1) nên tỷ lệ MACs bằng \(1/C_{\text{out}} + 1/K^2 = 0.1267\) (Test 06), đạt 6.33x params / 5.21x MACs trên toàn mạng (Test 08) với sf diff = 0.0 và ORT diff = 2.38e-06 (Test 09), nhưng bước Depthwise có OI rất thấp (2.10 FLOPs/byte).
2018–2026), khẳng định nào ĐÚNG?MixUp và CutMix đều bảo toàn tổng xác suất nhãn mềm bằng đúng 1.0 (Test 07), trong đó CutMix giữ cấu trúc cục bộ tự nhiên và chống phụ thuộc một đặc trưng duy nhất còn Mosaic ghép 4 góc tạo đa tỷ lệ ngữ cảnh.
PGD-10) của Lab 08 (Test 10, Test 11), điều gì xảy ra và vì sao các phòng thủ xử lý ảnh ngây thơ (như nén JPEG) dễ thất bại?PGD tìm điểm xấu nhất bên trong quả cầu \(\mathcal{B}_\infty(x,\epsilon)\) mạnh hơn hẳn FGSM (0.0% vs 20.0%, Test 10). Phòng thủ thật phải giải bài toán yên ngựa Min–Max (Madry 2018), giải cứu lên 99.2% (Test 11), tránh cảm giác an toàn giả của obfuscated gradients.
Lab 08 (Test 12). Khẳng định nào ĐÚNG về định lý chứng nhận Cohen et al. (2019)?ABSTAIN (Test 12).
Lab 08 (Tests 13–15), kết luận nào ĐÚNG về Grad-CAM, Integrated Gradients, Deletion/Insertion AUC và kiểm định tỉnh táo Adebayo (2018)?Deletion AUC càng thấp càng trung thực (0.110/0.138 vs 0.688), còn Insertion AUC càng cao càng tốt (0.963/0.946 vs 0.682). Khi trọng số bị ngẫu nhiên hóa, bản đồ trung thực phải thay đổi mạnh (Adebayo 2018), và cần lưu ý nền đen làm \((x_i - 0) = 0\) ở pixel đen (Tests 13–15).
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 — Không gian Màu, CLAHE, Hình thái học & Bất biến HOG (L2-Hys) 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
So sánh ảnh hưởng của nhân tử sáng \(\gamma\) lên vector (R, G, B) vs (Y, C_b, C_r) và chứng minh với ảnh nhân \(\gamma I\), biên độ gradient nhân \(\gamma\) sẽ triệt tiêu chính xác ở bước chuẩn hóa \(L_2\) của từng khối HOG (khi \(\varepsilon \ll \gamma\|\mathbf{v}\|_2\)).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy rgb_to_hsv, rgb_to_ycbcr, clahe_tile_equalize, binary_open, binary_close và extract_hog_descriptor trong color_and_filters.py (Tests 02–04).
Tiêu chí Đáp án & Số đối chứng
YCbCr tách riêng độ chói \(Y\) cho CLAHE (std = 0.177 êm hơn HistEq 0.288); Opening xóa đốm nhiễu sáng, Closing lấp lỗ tối; HOG (1764 chiều) đạt bất biến tỷ lệ sáng cosine > 0.99 và 98.3% trên tập kiểm thử PCB.
Bài tập 2 — Đệ quy Trường Tiếp nhận có Dilation & Nghịch lý Roofline của DW-Sep 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Chứng minh quy nạp \(r_l = r_{l-1} + (k_l - 1)d_l j_{l-1}\) bằng cách chiếu khoảng cách giữa hai phần tử ngoài cùng của nhân tầng \(l\) ngược qua \(l-1\) tầng với bước nhảy tích lũy \(j_{l-1} = \prod_{i<l} s_i\); lập tỷ số \(\text{MACs}_{\text{dwsep}}/\text{MACs}_{\text{std}}\).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Kiểm chứng compute_receptive_field_stack và compare_standard_vs_dwsep_conv trong conv_geometry.py (Tests 05–06) với tầng giãn conv3_3x3_d2 (\(D=2\)) và khối 48 -> 64 (8×8).
Tiêu chí Đáp án & Số đối chứng
Chuỗi 5 tầng cho \(r_l \in \{3, 4, 8, 10, 26\}\) px (\(j_5 = 4\)); khối DW-Sep 48->64 đạt tỷ lệ 0.1267 (7.89x ít MACs) khớp tuyệt đối \(1/64 + 1/9\), nhưng OI tầng Depthwise chỉ 2.10 vs 25.41 FLOPs/byte (nghẽn băng thông trên GPU nếu không fuse kernel).
Bài tập 3 — StandardCNN vs DepthwiseSeparableCNN, Augmentation & Chuỗi cung ứng Safetensors/ONNX 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Kiểm tra miền \([0, 1]\) và tổng xác suất nhãn mềm bằng 1.0 cho MixUp và CutMix (diện tích chính xác \(\lambda = 1 - \frac{(y_1-y_0)(x_1-x_0)}{HW}\)); phân biệt header 8-byte <Q của safetensors với bytecode pickle.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy StandardCNN, DepthwiseSeparableCNN, save_cnn_safetensors, và export_and_verify_onnx_parity (dynamo=False) trong cnn_models.py (Tests 07–09).
Tiêu chí Đáp án & Số đối chứng
DepthwiseSeparableCNN giữ nguyên 100.0% độ chính xác trong khi cắt 6.33x tham số (39,196 -> 6,196) và 5.21x MACs (5.09M -> 0.98M); safetensors đạt sai số 0.00e+00 (29,120 B) và ONNX ORT CPU đạt 2.38e-06 ở 0.092 ms/ảnh.
Bài tập 4 — Tấn công FGSM/PGD, Che khuất Gradient & Huấn luyện Điểm yên ngựa PGD-AT 20%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Áp dụng bất đẳng thức Hölder \(\delta^\top g \le \|\delta\|_\infty \|g\|_1\) để chứng minh dấu bằng đạt tại \(\delta^* = \epsilon\operatorname{sign}(g)\); phân tích định lý Danskin cho bài toán \(\min_\theta \mathbb{E}[\max_{\|\delta\|_\infty \le \epsilon} \mathcal{L}(f_\theta(x+\delta), y)]\).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy fgsm_attack, pgd_linf_attack, evaluate_adversarial_accuracy và train_pgd_adversarial_cnn trong adversarial.py (Tests 10–11) tại \(\epsilon = 0.06\).
Tiêu chí Đáp án & Số đối chứng
Dưới \(L_\infty\) (\(\epsilon = 0.06\)), StandardCNN rơi từ 100.0% xuống 20.0% (FGSM) và 0.0% (PGD-10); PGD-AT giải cứu độ bền PGD-10 lên 99.2% (+99.2 pp) trong khi giữ Clean Acc = 100.0% và mọi nhiễu thỏa \(\|\delta\|_\infty \le 0.06\).
Bài tập 5 — Chứng nhận Bền vững L2 qua Randomized Smoothing & Cơ chế ABSTAIN 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Viết tỷ số hợp lý của hai phân phối Gauss \(\mathcal{N}(x, \sigma^2 I)\) và \(\mathcal{N}(x+\delta, \sigma^2 I)\) để thấy nửa không gian tối ưu Neyman–Pearson dẫn về \(R = \sigma\Phi^{-1}(\underline{p_A})\); phân tích vai trò của mẫu độc lập n_select vs n_certify để tránh lệch thống kê.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy certify_randomized_smoothing và clopper_pearson_lower_bound trong adversarial.py (Test 12) trên cả PGD-AT CNN lẫn mô hình ngẫu nhiên chia phiếu để kiểm tra ABSTAIN.
Tiêu chí Đáp án & Số đối chứng
Tại \(\sigma = 0.10, \alpha = 0.001, n = 400\), Randomized Smoothing đạt Certified Acc = 100.0% với bán kính trung bình R = 0.212 (0/16 abstain) khớp chính xác \(\sigma\Phi^{-1}(\underline{p_A})\), và kích hoạt đúng ABSTAIN (\(R = 0\)) khi \(\underline{p_A} \le 0.5\).
Bài tập 6 — Kiểm toán Trung thực Visual XAI (Grad-CAM, IG Completeness, Deletion/Insertion, Adebayo) & Toàn trình Lab 08 20%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Áp dụng Định lý Cơ bản của Giải tích cho \(g(\alpha) = F(x' + \alpha(x-x'))\) trên \([0, 1]\) để chứng minh \(\sum_i \operatorname{IG}_i = F(x) - F(x')\); giải thích vì sao pixel đen có \((x_i - 0) = 0\) dưới nền đen \(x'=0\).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy compute_gradcam, compute_integrated_gradients, compute_rise_saliency, evaluate_deletion_insertion_auc, check_adebayo_weight_randomization_sanity (Tests 13–15), cùng trọn bộ ruff, mypy, pytest (16/16) và scripts/run_lab_demo.py.
Tiêu chí Đáp án & Số đối chứng
IG thỏa Completeness (max err = 2.61e-2, mean = 8.68e-3); Deletion AUC đạt 0.110 (IG) và 0.138 (Grad-CAM) so với 0.688 (Random); Insertion AUC đạt 0.963 (IG) và 0.946 (Grad-CAM) so với 0.682; cả hai vượt qua kiểm định Adebayo (|r| = 0.304 / 0.596) và 16/16 pytest đạt xanh.