Chương 15 — Autoencoders, Học Biểu diễn Ẩn, Vận hành Mô hình An toàn & Nén Triển khai Edge (Autoencoders, Model Operations & Compression)
Từ Bourlard-Kamp PCA (6.07e-15 rad), TopK/JumpReLU SAE & VAE Cyclical/FreeBits (AU 0->6) đến safetensors (0.00) & ONNX/ORT (3.81e-6), Structured+KD+INT8 (9.09x, Percentile +26.8 dB EMI) & IoT PdM 3 Tầng (PR-AUC 0.997, Bayes -91.2%, RCA 100%).
Đơn vị học phần (
Unit ID):T1-P3-U02(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 07 — Bảo trì Dự đoán IoT: Autoencoder, Bảo mật Chuỗi cung ứng, Nén Edge & Chẩn đoán 3 Tầng RUL–RCA (iot_ae_pdm_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 (SVD, Eckart–Young–Mirsky,VJP/JVP,REINFORCE), Chương 07 — Đánh giá Chống Rò rỉ & Hiệu chuẩn (PR-AUC,ECE, ngưỡng Bayes), Chương 13 — Chuỗi Thời gian & Chi phí Quyết định (lọc nhân quả),Chương 14(FFNN, lan truyền ngược,PyTorch 2.x), Chương trình gốc DSAI (R42& Lab IoTE41:E42), và Đề cương SOTA 2026 (Chương 15). Chương tiếp theo trong lộ trình làChương 16.
Bốn Ca Thất bại Thực chiến Mở màn: Từ RCE pickle, Ảo giác Nén Edge đến Sụp đổ Bảo trì Dự đoán IoT#
Trong kỹ nghệ học sâu công nghiệp, khoảng cách từ một mạng Autoencoder tái tạo tốt trên notebook đến một hệ thống giám sát đội tàu cảm biến chạy an toàn ở 100 Hz–1 kHz trên cổng biên (Edge Gateway) chứa đầy những cái bẫy toán học và hệ thống ít ngờ tới nhất:
-
Ca 1 — Thực thi Mã Từ xa qua
pickle(CWE-502/CVE-2025-32434) & Bẫytorch.onnx.export(..., dynamo=False)(Lab 07,Test 07–08):Định dạng lưu trữ mặc định của
PyTorch(.pt,.pth) gói dòng bytecode của Pickle Virtual Machine (PVM) trong tệp ZIP: bất kỳ đối tượng nào cài đặt phương thức__reduce__()đều phát lệnhGLOBAL+REDUCEép hệ thống gọios.systemhoặcsubprocess.Popenngay trong lúctorch.load()trước khi mô hình kịp khởi chạy. Trong chuỗi sự cố bảo mật 2024–2025 (nullifAI, bộ lỗ hổngpicklescanCVE-2025-1716đếnCVE-2025-10157), tin tặc dễ dàng qua mặt máy quét tĩnh, thậm chí lỗ hổngCVE-2025-32434(CVSS 9.3) còn xuyên thủng cảtorch.load(..., weights_only=True)trên PyTorch<= 2.5.1. TrongLab 07, việc chuyển sangsafetensors(24,272 B, tiêu đề 8 byte<Q+ JSON offsets, không chứa mã thực thi) tái lập trọng số với sai số0.00e+00 < 1e-6. Đồng thời, khi xuất đồ thị sangONNX+onnxruntimeCPU trên môi trườngPyTorch 2.15.0+cpukhông có góionnxscript, lệnh mặc địnhtorch.onnx.export(..., dynamo=True)lập tức sập vớiModuleNotFoundError: No module named 'onnxscript', buộc kỹ sư phải tường minh chọndynamo=Falsecho DAG tĩnh (sai số tối đa 3.81e-06 < 1e-4, độ trễ0.020 ms), đồng thời cảnh giác rằngdynamo=Falseđóng băng duy nhất nhánh điều kiệnif/elseđi qua tensor mẫu! -
Ca 2 — Ảo giác Tăng tốc từ Tỉa thưa Phi cấu trúc
80%(Lab 07,Test 09):Một đội kỹ sư biên dùng
torch.nn.utils.prune.l1_unstructuredxóa80%trọng số của Autoencoder với kỳ vọng giảm5xRAM và tăng tốc5xCPU. Thực tế hoàn toàn ngược lại: nếu quên gọiprune.remove(), hook mặt nạweight_orig * weight_masknhân đôi bộ nhớ đệm và làm chậm suy luận2.1x–2.5x; ngay cả sau khi gọiprune.remove(), tensor đặc vẫn chiếm nguyên23,640 B(1.00x,0%tiết kiệm RAM) và nhânBLAS/GEMMvẫn nhân–cộng đủ100%phần tử0.0! Ngược lại, Tỉa thưa Rộng Có cấu trúc (Structured Width Pruning\(128 \to 48\)) kết hợp Chưng cất Tri thức (FitNets+ \(T_{\text{kd}}^2\) KD) và lượng tử hóaINT8cắt kích thước xuống còn2,600 B(3.43x INT8,9.09xtổng cộng), đưa toàn bộ trọng số vào bộ nhớ đệm L2 CPU (< 200 KB,< 5 ms p99). -
Ca 3 — Sụp đổ Lượng tử hóa
MinMax INT8 PTQdưới Xung nhiễu Cảm biếnEMI(Lab 07,Test 10):Trên luồng cảm biến công nghiệp chuẩn hóa \(\mathcal{N}(0, 0.6^2)\), chỉ cần
0.3%mẫu bị xung nhiễu điện từ (EMI) vọt lên±48.0cũng đủ đẩy ngưỡng cắtMinMaxlên \(\alpha_{\text{clip}} = 48.0\), kéo bước nhảy lượng tử hóa \(\Delta_q = 48/127 \approx 0.378\) và phình phương sai làm tròn \(\Delta_q^2/12\) lên hàng nghìn lần. Hậu quả trongLab 07: toàn bộ dải tín hiệu vận hành bình thường bị nén chặt vào vỏn vẹn11mức nguyên (SQNR = 14.80 dB), gây bão cảnh báo giả! Khi chuyển sang hiệu chuẩn cắt ngọnPercentile 99.5%hoặcMSEtối ưu, số mức nguyên khả dụng phục hồi lên255 / 255bins, nângSQNRvọt lên41.57–42.48 dB(+26.8 dB). -
Ca 4 — Bộ ba Bẫy Chết người trong Bảo trì Dự đoán IoT
C-MAPSS(Lab 07,Test 11–14):- Rò rỉ tách chu kỳ ngẫu nhiên (
Leaky Cycle Split): Khi tách ngẫu nhiên từng chu kỳ thay vì tách theo định danh động cơ,45động cơ dùng chung xuất hiện ở cả tập huấn luyện và kiểm thử, khiến mô hình học thuộc độ lệch sản xuất (eng_bias) của từng máy và báo cáoOffline RMSE = 8.92đẹp như mơ trước khi sụp đổ lên34.23chu kỳ trên động cơ mới! Tách nghiêm ngặt theoEngine-ID GroupSplitgiữ0động cơ trùng lặp (Honest RMSE = 10.36). - Ngưỡng đối xứng
mean + 3*stdvàp = 0.50: Với chi phí kiểm tra giảc_fp = 800 USDnhưng chi phí hỏng hóc tuabin bỏ sótc_fn = 50,000 USD(62.5x), ngưỡng thống kêmean + 3*stdgây231báo giả (184,800 USD), còn ngưỡng đối xứngp = 0.50bỏ sót28sự cố thật (1,408,800 USD). Áp dụng hiệu chuẩn Platt trênD_calcùng ngưỡng quyết định Bayes tối ưu \(t^* = \frac{c_{\text{FP}}}{c_{\text{FP}}+c_{\text{FN}}} = 0.0157\) đưa tổng chi phí xuống123,600 USD(-33.1%vs3*std,-91.2%vsp = 0.50). - Cảnh báo hộp đen thiếu
RCA: Báo động chung chung không chỉ rõ hỏng ở phân hệ nào (Fan,HPC,Combustor,HPT) khiến đội bảo trì mất hàng giờ tháo dỡ mò mẫm; kết hợp phần dư chuẩn hóa theo \(\sigma_{j,\text{healthy}}^2\) và gradient đầu vào đạtTop-3 RCA Hit Rate = 100.0%trên cả 3 chế độ lỗi (vượt xa ngưỡng>= 85%) và giữ nguyên100.0%sau khi nénINT8(3.36x INT8,11.23xtổng cộng,0.017 msORT CPU).
- Rò rỉ tách chu kỳ ngẫu nhiên (
Mục tiêu Học tập (Learning Objectives)#
Sau khi hoàn tất chương học này và vượt qua trọn vẹn 16/16 bài kiểm thử của Lab 07, học viên đạt năng lực thạc sĩ chuyên sâu (UCL MSc Distinction) về các trụ cột sau:
- Chứng minh nền tảng các họ Autoencoder: Tự tay chứng minh Định lý Tương đương Bourlard–Kamp (
Linear AE\(\leftrightarrow\) không gian conPCAdưới bất biến nhóm \(\operatorname{GL}_{d_z}(\mathbb{R})\)), giải phẫuSparse AEcổ điển (L1chuẩn cột giải mã,KL) đến 2024–2026 Mechanistic Interpretability SAEs (TopK + AuxK,JumpReLU,BatchTopK,Matryoshka), chứng minh đồng nhất thức Tweedie Score Matching củaDAE, và dẫn xuất chuẩn Frobenius Jacobian củaCAE. - Làm chủ Mô hình Biến phân (
VAE) & Rời rạc (VQ-VAE/FSQ): Dẫn xuất trọn vẹnELBOtheo hai cách (phân rãKLvà bất đẳng thức Jensen), tính tích phân giải tíchKLGauss chéo, chứng minh ưu thế phương sai của Reparameterization Trick so vớiREINFORCE, và chẩn đoán/chữa trịPosterior Collapse(Cyclical Annealing,Free Bits,AU) lẫnCodebook Collapse(STE,EMA,FSQ,LFQ,Rotation Trick). - Vận hành & Bảo mật Chuỗi cung ứng Mô hình (
Model Operation): Phân tích cơ chếRCEqua__reduce__củapickle(CWE-502,CVE-2025-32434), thiết kế đóng gói bất biến bằngsafetensors(mmap\(O(1)\) và bẫyNFS/GCSFuse), nắm rõ hợp đồng biên dịchONNX+onnxruntime(dynamo=Falsevsdynamo=True) vàtorch.export+AOTInductor, cùng bộ chỉ số chẩn đoán sức khỏe biểu diễn (AU,PPL,r_dead, chuẩn gradient \(L_2\)). - Thiết kế Bộ ba Nén Mô hình Theo Roofline (
Pruning,KD,PTQ/QAT): Phân tích giới hạn băng thông bộ nhớ tại \(B=1\), phân biệt tỉa thưa phi cấu trúc vs2:4vs Structured Width Pruning, chứng minh hệ số nhân \(T_{\text{kd}}^2\) trong Knowledge Distillation (Hinton 2015+FitNets), dẫn xuất phương sai làm tròn \(\Delta_q^2/12\) và cơ chế giải cứu sụp đổ ngoại lai bằngPercentile/MSE/SmoothQuant/AWQ/QAT. - Kiến trúc hóa Đường ống 3 Tầng
IoT Predictive MaintenanceChống Rò rỉ: Triển khai tách biệt nghiêm ngặt theoEngine-ID GroupSplit, phát hiện bất thườngHealthy-Only AEkết hợp hiệu chuẩn xác suất và ngưỡng chi phí Bayes \(t^*\), dự báoRULcắt ngọnRUL_max = 125theo hàm điểm bất đối xứng NASAPHM08, và quy gán nguyên nhân gốc rễRCAđạtTop-3 Hit Rate >= 85%ngay cả trên mô hìnhINT8cổng biên.
Truy xuất Nguồn (Syllabus & Raw Curriculum Traceability)#
Thành phần Chương trình Nguồn (R42 & E41:E42) |
Nội dung Chuyên sâu trong Chương 15 | Sơ đồ / Mô phỏng Tương tác | Thực thi trong Lab 07 (iot_ae_pdm_lab) |
|---|---|---|---|
Kiến trúc Autoencoder & Tương đương PCA (R42) |
Nút cổ chai \(d_z < D_x\), chứng minh Bourlard–Kamp, bất biến \(\mathbf{R} \in \operatorname{GL}_{d_z}(\mathbb{R})\) | Mermaid 1 |
autoencoders_and_compression.py: fit_linear_ae_numpy, compute_pca_basis, subspace_principal_angle_rad (Test 02) |
Sparse, Denoising, Contractive AE & SAE 2024–2026 (R42) |
L1 chuẩn cột, KL Ng, TopK+AuxK, JumpReLU, Matryoshka, DAE Tweedie Score Matching, CAE Frobenius Jacobian |
Mermaid 1 |
autoencoders_and_compression.py: train_sparse_ae_comparison, fit_denoising_ae_numpy, contractive_jacobian_penalty_sigmoid (Tests 03, 04) |
VAE (ELBO) & VQ-VAE Rời rạc (R42) |
Hai chứng minh ELBO, KL Gauss, Reparameterization, Posterior Collapse, Cyclical Annealing, Free Bits, VQ-VAE EMA, FSQ / Rotation Trick |
Mermaid 1 + Widget 1 (vae-elbo-beta-kl-collapse) |
autoencoders_and_compression.py: gaussian_kl_divergence, cyclical_beta_schedule, train_vae_collapse_vs_annealed, VQVAEBottleneck, train_vqvae_ema_vs_no_ema (Tests 05, 06) |
Vận hành: Chẩn đoán & Lưu/Nạp An toàn (R42) |
AU, PPL, r_dead, pickle CWE-502 / CVE-2025-32434 vs safetensors, ONNX (dynamo=False) + ORT, AOTInductor |
Mermaid 2 |
autoencoders_and_compression.py: save_state_dict_safetensors, load_state_dict_safetensors, export_and_verify_onnx_parity (Tests 07, 08, 16) |
Vận hành: Bộ ba Nén Mô hình (R42) |
Roofline \(B=1\), Unstructured vs 2:4 vs Structured Pruning, KD (\(T_{\text{kd}}^2\) + FitNets), INT8 PTQ/QAT (\(\Delta_q^2/12\) & bẫy ngoại lai) |
Mermaid 2 + Widget 2 (compression-pruning-kd-quant-pareto) |
autoencoders_and_compression.py: unstructured_magnitude_prune_mask, structured_width_prune_ae, distill_student_ae, calibrate_clipping_threshold, compress_student_to_int8_bundle (Tests 09, 10) |
IoT Domain Lab: Anomaly -> RUL -> RCA (E41:E42) |
Engine-ID GroupSplit (0 trùng lặp), Stage 1 Healthy-Only AE + Bayes \(t^*\), Stage 2 RUL_max=125 + PHM08, Stage 3 Residual+Grad RCA (>= 85%), Edge INT8 |
Mermaid 3 + Widget 3 (iot-pdm-anomaly-rul-rca-console) |
pdm_pipeline.py: simulate_turbofan_fleet, split_fleet_by_engine_id, fit_stage1_healthy_detector, calibrate_and_threshold_bayes, fit_stage2_rul_predictor, evaluate_rca_subsystem_hit_rate, compress_and_evaluate_edge_pdm (Tests 11–15) |
Bảng Ký hiệu Phi Mơ hồ (Disambiguated Notation Contract)#
Nhằm loại bỏ mọi xung đột ký hiệu với Chương 02, Chương 07, Chương 13 và Chương 14 (nơi \(\phi\) từng ký hiệu hàm kích hoạt), toàn bộ Chương 15 tuân thủ quy ước thống nhất sau:
| Ký hiệu LaTeX | Miền / Kích thước | Định nghĩa chuẩn trong Chương 15 | Quy tắc Phân tách Liên chương | Định danh iot_ae_pdm_lab |
|---|---|---|---|---|
| \(\mathbf{x}, \hat{\mathbf{x}}, \tilde{\mathbf{x}}\) | \(\mathbb{R}^{D_x}\) | Vector cảm biến đầu vào, tái tạo và bản nhiễu DAE |
Vector cột; batch PyTorch là \(\mathbf{X}_{\text{batch}} \in \mathbb{R}^{B \times D_x}\) | x, x_hat, x_noisy |
| \(\mathbf{X}_{\text{col}}\) | \(\mathbb{R}^{D_x \times N}\) | Ma trận mẫu đã quy tâm \([\mathbf{x}_1,\dots,\mathbf{x}_N]\) cho SVD |
Chuyển vị của mảng (N, D_x) chuẩn NumPy |
x_centered.T |
| \(D_x, d_z, K_{\text{vq}}\) | \(\mathbb{N}_+\) | Số chiều đầu vào (16), chiều ẩn / từ điển SAE, kích thước VQ |
Phân biệt với số fold \(K_{\text{fold}}\) (ch-07) |
input_dim, latent_dim, num_codes |
| \(f_\phi, g_\theta, \psi(\cdot)\) | Ánh xạ | Bộ mã hóa (\(\phi\)), bộ giải mã (\(\theta\)), hàm kích hoạt \(\psi\) | Dùng \(\psi\) tránh trùng ký hiệu \(\phi\) ở ch-14 |
encoder, decoder, activation |
| \(\mathbf{h}, \mathbf{z}, \mathbf{z}_e, \mathbf{z}_q\) | \(\mathbb{R}^{d_z}\) | Mã tất định AE, biến ẩn VAE, trước/sau lượng tử hóa VQ |
Bảng mã VQ-VAE ký hiệu \(\mathbf{E} = [\mathbf{e}_1,\dots,\mathbf{e}_{K_{\text{vq}}}]^\top\) |
h, z, z_e, z_q, codebook |
| \(\mathbf{J}_{\mathbf{x}}\mathbf{h}(\mathbf{x})\) | \(\mathbb{R}^{d_z \times D_x}\) | Ma trận Jacobian bộ mã hóa theo bố cục tử số (\(\partial h_i / \partial x_j\)) | Kế thừa bố cục tử số ch-02 §1.5 |
encoder_jacobian |
| \(\sigma(\cdot);\; \sigma_k;\; \boldsymbol{\sigma}_\phi;\; \sigma_{\text{noise}}\) | Hàm / \(\mathbb{R}_{>0}\) | Sigmoid; giá trị kỳ dị \(\sigma_k\); độ lệch chuẩn VAE; nhiễu DAE |
Luôn có chỉ số dưới; nhiễu nền khỏe là \(\sigma_{j,\text{healthy}}\) | sigmoid, singular_vals, vae_std, noise_std |
| \(\rho, \hat{\rho}_j, \boldsymbol{\tau}_{\text{jump}}\) | \((0,1), \mathbb{R}_{>0}^{d_z}\) | Mục tiêu thưa SAE, trung bình kích hoạt mẫu, ngưỡng JumpReLU |
Phân biệt với ACF \(\rho(k)\) (ch-13) và giải mã \(\theta\) |
target_sparsity, empirical_sparsity, jumprelu_theta |
| \(\lambda_{\text{L1}}, \lambda_{\text{KL}}, \lambda_{\text{cae}}, \lambda_{\text{fb}}\) | \(\mathbb{R}_{\ge 0}\) | Hệ số phạt L1, KL của SAE, Jacobian CAE, sàn Free Bits |
Không dùng \(\lambda\) trần thiếu chỉ số phụ | l1_lambda, kl_lambda, cae_lambda, free_bits_lambda |
| \(\beta_{\text{VAE}}, \beta_{\text{vq}}, \gamma_{\text{ema}}\) | \(\mathbb{R}_{>0}, (0,1)\) | Hệ số KL VAE, hệ số cam kết VQ, hệ số suy giảm EMA |
Tách biệt với \(\gamma_{\text{ets}}\) (ch-13) |
beta_vae, commitment_beta, ema_decay |
| \(\text{AU}, \text{PPL}, r_{\text{dead}}\) | \(\mathbb{Z}_{\ge 0}, [1,K_{\text{vq}}], [0,1]\) | Số chiều VAE hoạt động, Perplexity bảng mã, tỷ lệ nút chết |
Bộ chỉ số chẩn đoán sức khỏe biểu diễn | active_units, perplexity, dead_latent_fraction |
| \(s_p, T_{\text{kd}}, \alpha_{\text{kd}}\) | \((0,1), \mathbb{R}_{>0}, [0,1]\) | Tỷ lệ tỉa kênh, nhiệt độ chưng cất KD, trọng số KD |
Tách biệt với bước nhảy \(s_q\) và chu kỳ hỏng \(T_{\text{fail}}\) | prune_ratio, kd_temperature, kd_alpha |
| \(b_q, s_q, \Delta_q, z_p, \alpha_{\text{clip}}\) | \(\mathbb{N}_+, \mathbb{R}, \mathbb{Z}\) | Số bit (8), hệ số tỷ lệ/bước nhảy \(\Delta_q = s_q\), điểm không, ngưỡng cắt |
\(z_p \in \mathbb{Z}\) tách biệt hoàn toàn khỏi biến ẩn \(\mathbf{z}\) | quant_bits, scale, step_size, zero_point, clip_alpha |
| \(c_{\text{FN}}, c_{\text{FP}}, t^*\) | \(\mathbb{R}_{>0}, (0,1)\) | Chi phí hỏng bỏ sót, kiểm tra giả, ngưỡng Bayes \(\frac{c_{\text{FP}}}{c_{\text{FP}}+c_{\text{FN}}}\) | Chuyên biệt hóa ch-07 với \(C_{\text{TP}} = C_{\text{TN}} = 0\) |
cost_fn_usd, cost_fp_usd, bayes_threshold |
| \(d_i^{\text{rul}}, \text{RUL}_{\max}, T_{\text{fail}}^{(u)}\) | \(\mathbb{R}, \mathbb{N}_+\) | Sai số RUL \(\widehat{\text{RUL}}_i - \text{RUL}_i\), trần cắt ngọn (125), chu kỳ hỏng |
Có chỉ số rul tránh trùng chiều \(d\) |
rul_err, rul_max, failure_cycle |
| \(a_j^{\text{res}}, a_j^{\text{grad}}\) | \(\mathbb{R}_{\ge 0}\) | Quy gán phần dư chuẩn hóa & độ nhạy gradient đầu vào cảm biến \(j\) | Ánh xạ về Fan, HPC, Combustor, HPT |
residual_attr, grad_attr, top_3_rca_hit_rate |
Trụ cột 1 — Nền tảng Toán học: Autoencoder, Mô hình Sinh Ẩn & Lý thuyết Nén Mô hình#
1.1 Kiến trúc Undercomplete Autoencoder & Chứng minh Tương đương PCA (Bourlard & Kamp 1988)#
Một Autoencoder (AE) học biểu diễn tự giám sát bằng cách ghép nối bộ mã hóa tham số \(f_\phi: \mathbb{R}^{D_x} \to \mathbb{R}^{d_z}\) và bộ giải mã \(g_\theta: \mathbb{R}^{d_z} \to \mathbb{R}^{D_x}\) qua không gian ẩn \(\mathbf{h} = f_\phi(\mathbf{x})\) để cực tiểu hóa rủi ro tái tạo thực nghiệm:
Khi chọn mất mát bình phương sai số \(\ell(\mathbf{x}, \hat{\mathbf{x}}) = \lVert \mathbf{x} - \hat{\mathbf{x}} \rVert_2^2\), bài toán tương đương ước lượng hợp lý cực đại (MLE) dưới mô hình giải mã Gauss đẳng hướng \(p_\theta(\mathbf{x} \mid \mathbf{h}) = \mathcal{N}(\mathbf{x} \mid g_\theta(\mathbf{h}), \sigma_{\text{dec}}^2 \mathbf{I}_{D_x})\); còn khi dữ liệu chuẩn hóa về \([0, 1]^{D_x}\) và dùng entropy chéo nhị phân (BCE), bộ giải mã tương ứng với phân phối Bernoulli nhân tử hóa. Nếu đặt \(d_z \ge D_x\) mà không có ràng buộc điều chuẩn, cặp \((f_\phi, g_\theta)\) dễ dàng học hàm đồng nhất tầm thường \(g_\theta(f_\phi(\mathbf{x})) = \mathbf{x}\) trên tập huấn luyện và sụp đổ khả năng lọc nhiễu hay tách bất thường ngoài đa tạp \(\mathcal{M}\). Ép nút cổ chai thiếu chiều (undercomplete, \(d_z < D_x\)) buộc mạng chỉ giữ lại các phương biến thiên mang thông tin cốt lõi nhất.
Xét Autoencoder tuyến tính 1 lớp ẩn \(\mathbf{h} = \mathbf{W}_1 \mathbf{x} + \mathbf{b}_1\), \(\hat{\mathbf{x}} = \mathbf{W}_2 \mathbf{h} + \mathbf{b}_2\) (\(\mathbf{W}_1 \in \mathbb{R}^{d_z \times D_x}, \mathbf{W}_2 \in \mathbb{R}^{D_x \times d_z}\)). Đặt \(\nabla_{\mathbf{b}_2}\mathcal{L} = \mathbf{0}\) tự động đưa hàm mục tiêu về ma trận dữ liệu đã quy tâm theo cột \(\mathbf{X}_{\text{col}} \in \mathbb{R}^{D_x \times N}\):
Định lý 1.1 (Bourlard & Kamp 1988; Baldi & Hornik 1989 — Tương đương Không gian con PCA & Bất biến Cơ sở):
Cho khai triển SVD đầy đủ \(\mathbf{X}_{\text{col}} = \mathbf{U}\boldsymbol{\Sigma}\mathbf{V}^\top\) với hạng \(r \le \min(D_x, N)\), các giá trị kỳ dị \(\sigma_1 \ge \dots \ge \sigma_r > 0\), và giả sử tồn tại khe phổ \(\sigma_{d_z} > \sigma_{d_z+1}\) (\(d_z < r\)). Khi đó:
- Cực tiểu toàn cục \(\mathcal{L}^* = \frac{1}{N}\sum_{k=d_z+1}^r \sigma_k^2\) đạt được khi và chỉ khi:
\[\operatorname{col}(\mathbf{W}_2) = \operatorname{span}(\mathbf{u}_1, \dots, \mathbf{u}_{d_z}), \qquad \mathbf{W}_1 \mathbf{X}_{\text{col}} = \mathbf{R}^{-1}\mathbf{U}_{d_z}^\top \mathbf{X}_{\text{col}},\]trong đó \(\mathbf{U}_{d_z} = [\mathbf{u}_1, \dots, \mathbf{u}_{d_z}] \in \mathbb{R}^{D_x \times d_z}\) và \(\mathbf{W}_2 = \mathbf{U}_{d_z}\mathbf{R}\) với một ma trận khả nghịch \(\mathbf{R} \in \operatorname{GL}_{d_z}(\mathbb{R})\).
- Mọi nghiệm đều bất biến dưới phép đổi cơ sở khả nghịch \((\mathbf{W}_1, \mathbf{W}_2) \mapsto (\mathbf{R}^{-1}\mathbf{W}_1, \mathbf{W}_2\mathbf{R})\), do đó các trục tọa độ ẩn \(h_1, \dots, h_{d_z}\) không tự động trực giao hay xếp thứ tự theo phương sai
PCAnếu không thực hiệnSVDhậu kỳ lên \(\mathbf{W}_2^*\).
Chứng minh 4 bước:
- Bước 1 (Chặn dưới Eckart–Young–Mirsky): Mọi tích tái tạo \(\mathbf{B} := \mathbf{W}_2 \mathbf{W}_1 \mathbf{X}_{\text{col}}\) đều thỏa \(\operatorname{rank}(\mathbf{B}) \le d_z\). Theo Định lý Eckart–Young–Mirsky (Chương 02), vì \(\sigma_{d_z} > \sigma_{d_z+1}\), ma trận \(\mathbf{X}_{d_z} = \mathbf{U}_{d_z}\mathbf{U}_{d_z}^\top \mathbf{X}_{\text{col}}\) là nghiệm hạng \(\le d_z\) duy nhất đạt cực tiểu \(\lVert \mathbf{X}_{\text{col}} - \mathbf{B} \rVert_F^2 \ge \sum_{k=d_z+1}^r \sigma_k^2\).
- Bước 2 (Điều kiện cần): Tại cực tiểu toàn cục, tính duy nhất bắt buộc \(\mathbf{W}_2^* \mathbf{W}_1^* \mathbf{X}_{\text{col}} = \mathbf{X}_{d_z}\). Vì \(\operatorname{rank}(\mathbf{X}_{d_z}) = d_z\) và \(\operatorname{col}(\mathbf{W}_2^* \mathbf{W}_1^* \mathbf{X}_{\text{col}}) \subseteq \operatorname{col}(\mathbf{W}_2^*)\) (có số chiều \(\le d_z\)), suy ra \(\operatorname{col}(\mathbf{W}_2^*) = \operatorname{col}(\mathbf{U}_{d_z}) = \operatorname{span}(\mathbf{u}_1,\dots,\mathbf{u}_{d_z})\). Do cả hai cùng là cơ sở của một không gian \(d_z\) chiều, tồn tại duy nhất \(\mathbf{R} \in \operatorname{GL}_{d_z}(\mathbb{R})\) sao cho \(\mathbf{W}_2^* = \mathbf{U}_{d_z}\mathbf{R}\); nhân trái với \(\mathbf{R}^{-1}\mathbf{U}_{d_z}^\top\) cho \(\mathbf{W}_1^*\mathbf{X}_{\text{col}} = \mathbf{R}^{-1}\mathbf{U}_{d_z}^\top\mathbf{X}_{\text{col}}\).
- Bước 3 (Điều kiện đủ): Ngược lại, nếu \(\mathbf{W}_2 = \mathbf{U}_{d_z}\mathbf{R}\) khả nghịch cột, nghiệm bình phương tối thiểu cho \(\mathbf{W}_1\) là \(\mathbf{W}_1^* = (\mathbf{W}_2^\top \mathbf{W}_2)^{-1}\mathbf{W}_2^\top = \mathbf{R}^{-1}\mathbf{U}_{d_z}^\top\), phục hồi đúng \(\mathbf{W}_2\mathbf{W}_1^*\mathbf{X}_{\text{col}} = \mathbf{X}_{d_z}\).
- Bước 4 (Hệ quả hình học & điểm yên ngựa): Vì \(\mathbf{R} \in \operatorname{GL}_{d_z}(\mathbb{R})\) không bị ràng buộc trực giao (\(\mathbf{R}^\top \mathbf{R} \neq \mathbf{I}_{d_z}\)), biểu diễn \(\mathbf{h}^*\) là một tổ hợp bị kéo giãn và xoay lệch của các thành phần chính. Baldi & Hornik (1989) đồng thời chứng minh mọi điểm tới hạn khác của \(\mathcal{L}_{\text{lin}}\) đều là điểm yên ngựa chặt, không tồn tại cực tiểu địa phương giả. \(\blacksquare\) (Trong
Lab 07Test 02, góc không gian con giữaLinear AEvàPCAhội tụ về6.07e-15 radvớiae_mse = 0.00743, nhưng độ lệch trực giao \(\lVert \mathbf{W}_2^\top \mathbf{W}_2 - \mathbf{I} \rVert_F\) vẫn bằng3.30đúng như dự báo lý thuyết!)
1.2 Sparse Autoencoders (SAE): Từ Cổ điển (L1/KL) đến Giải mã Cơ chế 2024–2026#
Khi chuyển sang chế độ siêu đầy đủ (overcomplete, \(d_z > D_x\)), Sparse Autoencoder (SAE) ngăn chặn sao chép đồng nhất bằng cách buộc mỗi mẫu chỉ kích hoạt một tập nhỏ nguyên tử từ điển.
-
SAE-L1Cổ điển & Ràng buộc Chuẩn cột Giải mã: Với bộ mã hóaReLU\(\mathbf{h}(\mathbf{x}) = \operatorname{ReLU}(\mathbf{W}_1(\mathbf{x} - \mathbf{b}_{\text{pre}}) + \mathbf{b}_1)\) và giải mã \(\hat{\mathbf{x}} = \mathbf{W}_2\mathbf{h}(\mathbf{x}) + \mathbf{b}_{\text{pre}}\):\[\mathcal{L}_{\text{SAE-}L_1} = \frac{1}{N}\sum_{i=1}^N \lVert \mathbf{x}_i - \hat{\mathbf{x}}_i \rVert_2^2 + \lambda_{\text{L1}}\frac{1}{N}\sum_{i=1}^N \lVert \mathbf{h}(\mathbf{x}_i) \rVert_1.\]Bẫy suy biến tỷ lệ song tuyến tính: Nếu không kẹp chuẩn từng cột giải mã \(\lVert \mathbf{w}_{2,:,j} \rVert_2 \le 1\), tối ưu hóa dễ dàng thu nhỏ \(\mathbf{W}_1 \leftarrow c\mathbf{W}_1, \mathbf{b}_1 \leftarrow c\mathbf{b}_1\) và phóng đại \(\mathbf{W}_2 \leftarrow \frac{1}{c}\mathbf{W}_2\) (\(c \to 0^+\)): giá trị tái tạo \(\hat{\mathbf{x}}\) giữ nguyên trong khi \(\lambda_{\text{L1}}\lVert \mathbf{h} \rVert_1 \to 0\)! Đồng thời, hình phạt \(L_1\) gây ra thiên lệch co rút Tibshirani: đối với một hướng trực giao đơn vị, nghiệm tối ưu bị co bớt một lượng hằng số \(\hat{h}_j = h_j^* - \lambda_{\text{L1}}/2\), buộc
SAEphải hạ biên độ tái tạo hoặc bật thêm đặc trưng nhiễu, đồng thời làm chết hàng loạt nútReLUkhi độ lệch âm đẩy tiền kích hoạt \(\le 0\). -
SAE-KL(Ng 2011) với Kích hoạt Sigmoid: Thay vì phạt biên độ từng mẫu, đo tần suất kích hoạt trung bình trên lô \(\hat{\rho}_j = \frac{1}{N}\sum_{i=1}^N h_j(\mathbf{x}_i) \in (0, 1)\) và phạt độ phân kỳ Bernoulli so với mục tiêu thưa \(\rho\) (ví dụ0.05):\[\mathcal{L}_{\text{SAE-KL}} = \frac{1}{N}\sum_{i=1}^N \lVert \mathbf{x}_i - g_\theta(\mathbf{h}(\mathbf{x}_i)) \rVert_2^2 + \lambda_{\text{KL}}\sum_{j=1}^{d_z}\left(\rho \ln\frac{\rho}{\hat{\rho}_j} + (1-\rho)\ln\frac{1-\rho}{1-\hat{\rho}_j}\right), \quad \frac{\partial D_{\text{KL}}}{\partial \hat{\rho}_j} = \frac{\hat{\rho}_j - \rho}{\hat{\rho}_j(1-\hat{\rho}_j)}.\]Tuy giữ được mức kích hoạt trung bình tổng thể,
SAE-KLphụ thuộc kích thước mini-batch và chịu bão hòa đạo hàm của hàm sigmoid (\(\sigma'(a) \le 1/4\)). -
Bước nhảy SOTA 2024–2026 (
Mechanistic Interpretability SAEs): Theo giả thuyết chồng chập (superposition, Elhage et al. 2022), các mạng lớn nhúng \(M \gg d_{\text{model}}\) khái niệm gần trực giao vào không gian kích hoạt chật hẹp khiến mỗi neuron riêng lẻ mang đa nghĩa (polysemantic). Khi Anthropic (Templeton et al., 2024) mở rộngSAE-L1lên1M,4Mvà34Mchiều ẩn trên Claude 3 Sonnet, tỷ lệ đặc trưng chết vọt từ~2%lên~35%(4M) và~65%(34M). Bốn kiến trúc 2024–2025 đã giải quyết triệt để nút thắt này:TopK+AuxKSAE (Gao et al., OpenAI 2024): Thay phạt \(L_1\) bằng cổng giữ nguyên \(k\) kích hoạt lớn nhất \(\mathbf{h} = \operatorname{TopK}(\operatorname{ReLU}(\mathbf{W}_1(\mathbf{x}-\mathbf{b}_{\text{pre}})))\), đạt đúng \(L_0 = k\) với biên độ không bị co rút (Lab 07:amplitude ratio = 1.03vàrecon_mse = 0.058so với0.19và0.285củaL1). Để xóa sổ đặc trưng chết tới~0%trên mô hình16Mlatent, OpenAI cộng thêm mất mát phụAuxKdùng riêng các latent chết \(\mathcal{D}_{\text{dead}}\) tái tạo phần dư \(\mathbf{e} = \mathbf{x} - \hat{\mathbf{x}}\) với trọng số \(\alpha_{\text{aux}} \approx 1/32\).JumpReLUSAE (Rajamanoharan et al., Google DeepMind 2024): Giữ \(L_0\) thích nghi bằng cách học vector ngưỡng dương \(\boldsymbol{\tau}_{\text{jump}} \in \mathbb{R}_{>0}^{d_z}\) với cổng bậc thang Heaviside \(H(\cdot)\):\[\operatorname{JumpReLU}_{\boldsymbol{\tau}_{\text{jump}}}(\mathbf{a}) = \mathbf{a} \odot H(\mathbf{a} - \boldsymbol{\tau}_{\text{jump}}), \qquad \mathcal{L}_{L_0} = \lambda_{L_0}\sum_{j=1}^{d_z} H(a_j - \tau_{\text{jump},j}).\]Vì đạo hàm của \(H\) triệt tiêu hầu khắp nơi,JumpReLUdùng bộ ước lượng đi thẳng làm mượt nhân chữ nhậtKDE-STEbăng thông \(\varepsilon\): \(\frac{\widetilde{\partial} H(a_j - \tau_j)}{\partial \tau_j} = -\frac{1}{\varepsilon} K\!\left(\frac{a_j - \tau_j}{\varepsilon}\right)\), vừa giữ nguyên biên độ khi qua ngưỡng (amplitude ratio = 1.44trongLab 07), vừa cho phép điều chỉnh mật độ thông tin linh hoạt theo từng token.BatchTopK&MatryoshkaSAE (Bussmann et al., 2024–2025) &SAEBench(Karvonen et al., ICML 2025):BatchTopKchọn \(B\cdot k\) kích hoạt lớn nhất toàn batch rồi hiệu chuẩn ngưỡng suy luận \(\theta_{\text{inf}}\);MatryoshkaSAE huấn luyện đồng thời nhiều tiền tố từ điển lồng nhau \(\{m_1 < m_2 < \dots < m_K\}\) để triệt tiêu hiện tượng tách mảnh khái niệm (feature splitting) và hấp thụ đặc trưng, vượt trội trên chuẩn đánh giá đa chiềuSAEBench(Targeted Probe Perturbation — TPP).
1.3 Denoising Autoencoder (DAE) & Chứng minh Score Matching (Vincent 2011)#
Thay vì thu hẹp chiều ẩn hay ép thưa, Denoising Autoencoder (DAE) đưa đầu vào sạch \(\mathbf{x}\) qua kênh làm nhiễu \(\tilde{\mathbf{x}} \sim q_{\text{corr}}(\tilde{\mathbf{x}} \mid \mathbf{x})\) (nhiễu Gauss \(\tilde{\mathbf{x}} = \mathbf{x} + \boldsymbol{\varepsilon}\) với \(\boldsymbol{\varepsilon} \sim \mathcal{N}(\mathbf{0}, \sigma_{\text{noise}}^2 \mathbf{I}_{D_x})\) hoặc che mất kênh cảm biến Bernoulli) và huấn luyện \(r_{\phi,\theta}(\tilde{\mathbf{x}}) = g_\theta(f_\phi(\tilde{\mathbf{x}}))\) khôi phục bản sạch \(\mathbf{x}\):
Định lý 1.2 (Đồng nhất thức Tweedie & Khớp điểm Khử nhiễu — Vincent 2011; Alain & Bengio 2014):
Đặt \(\mathbf{y} := \tilde{\mathbf{x}} = \mathbf{x} + \boldsymbol{\varepsilon}\) (\(\sigma := \sigma_{\text{noise}} > 0\)) và gọi \(p_\sigma(\mathbf{y}) = \int p(\mathbf{x})q_{\text{corr}}(\mathbf{y}\mid\mathbf{x})\,d\mathbf{x}\) là mật độ biên làm mượt. Bộ khử nhiễu Bayes tối ưu \(r^*(\mathbf{y}) = \mathbb{E}[\mathbf{x} \mid \mathbf{y}]\) thỏa chính xác với mọi \(\sigma > 0\):
Chứng minh ngắn: Vì \(q_{\text{corr}}(\mathbf{y}\mid\mathbf{x}) = (2\pi\sigma^2)^{-D_x/2}\exp\!\big(-\frac{\lVert\mathbf{y}-\mathbf{x}\rVert_2^2}{2\sigma^2}\big)\) có đạo hàm \(\nabla_{\mathbf{y}} q_{\text{corr}}(\mathbf{y}\mid\mathbf{x}) = q_{\text{corr}}(\mathbf{y}\mid\mathbf{x})\frac{\mathbf{x}-\mathbf{y}}{\sigma^2}\), lấy vi phân dưới dấu tích phân \(p_\sigma(\mathbf{y})\) cho:
Chia hai vế cho \(p_\sigma(\mathbf{y}) > 0\) thu được đồng nhất thức Tweedie. Khai triển \(\frac{1}{\sigma^4}\mathbb{E}[\lVert r(\mathbf{y})-\mathbf{x}\rVert_2^2]\) chứng tỏ cực tiểu hóa DAE MSE tương đương đại số với cực tiểu hóa sai số khớp trường điểm số (Denoising Score Matching): \(\mathbb{E}_{\mathbf{y}}[\lVert \frac{r(\mathbf{y})-\mathbf{y}}{\sigma^2} - \nabla_{\mathbf{y}} \ln p_\sigma(\mathbf{y}) \rVert_2^2] + C\). Về mặt hình học, vector \(r^*(\mathbf{y}) - \mathbf{y}\) chính là trường mũi tên kéo các điểm cảm biến bị nhiễu văng ra khỏi đa tạp quay thẳng về vùng mật độ cao—nền móng trực tiếp của các mô hình khuếch tán (DDPM) hiện đại. Trong Lab 07 (Test 04), DAE cắt giảm sai số tái tạo trên dữ liệu nhiễu 3.80x (+5.8 dB).
1.4 Contractive Autoencoder (CAE, Rifai et al., ICML 2011)#
Thay vì đưa nhiễu ngẫu nhiên vào đầu vào, Contractive Autoencoder (CAE) ép trực tiếp tính bất biến cục bộ của bộ mã hóa \(\mathbf{h}(\mathbf{x}) = f_\phi(\mathbf{x})\) thông qua bình phương chuẩn Frobenius của ma trận Jacobian \(\mathbf{J}_{\mathbf{x}}\mathbf{h}(\mathbf{x}) \in \mathbb{R}^{d_z \times D_x}\):
Với bộ mã hóa 1 lớp ẩn \(\mathbf{a} = \mathbf{W}_1\mathbf{x} + \mathbf{b}_1\), \(\mathbf{h} = \psi(\mathbf{a})\), ta thu được công thức giải tích chính xác:
(Với mạng sâu \(L \ge 2\), dùng ước lượng vết Hutchinson \(\mathbb{E}_{\mathbf{v}\sim\mathcal{N}(\mathbf{0},\mathbf{I})}[\lVert \mathbf{J}_{\mathbf{x}}\mathbf{h}^\top\mathbf{v}\rVert_2^2]\) bằng VJP.) Sự giằng co giữa hai thành phần hàm mất mát tạo nên tính chất hình học đẹp: dọc theo không gian tiếp tuyến \(T_{\mathbf{x}}\mathcal{M}\), hạng tử tái tạo ép \(\mathbf{h}\) phải thay đổi để phân biệt các trạng thái khác nhau trên đa tạp, còn theo mọi phương trực giao nhiễu ngoài đa tạp \(\boldsymbol{\delta} \perp T_{\mathbf{x}}\mathcal{M}\), hình phạt Frobenius nén các giá trị kỳ dị của \(\mathbf{J}_{\mathbf{x}}\mathbf{h}\) về gần 0.
| Biến thể Autoencoder | Chế độ Chiều ẩn | Cơ chế Điều chuẩn Cốt lõi | Tác động Hình học Biểu diễn | Chế độ Hỏng hóc Chính |
|---|---|---|---|---|
| Linear AE | \(d_z < D_x\) | Không (MSE) |
Khớp không gian con PCA top-\(d_z\) sai khác \(\mathbf{R} \in \operatorname{GL}_{d_z}(\mathbb{R})\) |
Không mô hình hóa được đa tạp phi tuyến cong |
| Undercomplete Nonlinear AE | \(d_z < D_x\) | Nút cổ chai cấu trúc \(d_z \ll D_x\) | Nén đa tạp phi tuyến \(\mathcal{M} \subset \mathbb{R}^{D_x}\) | Bộ giải mã quá lớn dễ học thuộc hàm đồng nhất khi \(N\) nhỏ |
Sparse AE (SAE) |
Siêu đầy đủ (\(d_z > D_x\)) | L1 (cột \(\le 1\)) / KL / TopK+AuxK / JumpReLU |
Nguyên tử từ điển đơn nghĩa giải mã chồng chập | Nút chết (ReLU) hoặc co rút biên độ ở L1 |
Denoising AE (DAE) |
Bất kỳ | Đầu vào nhiễu \(\tilde{\mathbf{x}} \sim q_{\text{corr}}(\cdot\mid\mathbf{x})\) | Học trường vector điểm số \(\sigma_{\text{noise}}^2\nabla\ln p_{\sigma}(\mathbf{y})\) | Nhạy cảm với độ lớn \(\sigma_{\text{noise}}\) (quá lớn làm mờ đa tạp) |
Contractive AE (CAE) |
Bất kỳ (\(d_z < D_x\)) | \(\lambda_{\text{cae}}\lVert \mathbf{J}_{\mathbf{x}}\mathbf{h}(\mathbf{x}) \rVert_F^2\) | Co rút phương nhiễu vuông góc \(T_{\mathbf{x}}\mathcal{M}\), giữ phương tiếp tuyến | Chi phí Jacobian \(O(d_z)\) ở mạng sâu; giải mã không bị co |
1.5 Variational Autoencoders (VAE): Chứng minh ELBO, Tái tham số hóa & Posterior Collapse#
Khác với AE tất định chỉ gán mỗi đầu vào vào một điểm rời rạc không tạo nên mật độ xác suất chuẩn hóa trên không gian ẩn, Variational Autoencoder (VAE, Kingma & Welling 2013/2014; Rezende et al. 2014) đặt tiên nghiệm \(p(\mathbf{z}) = \mathcal{N}(\mathbf{0}, \mathbf{I}_{d_z})\) và xấp xỉ hậu nghiệm khó tính \(p_\theta(\mathbf{z}\mid\mathbf{x})\) bằng phân phối biến phân \(q_\phi(\mathbf{z}\mid\mathbf{x}) = \mathcal{N}(\boldsymbol{\mu}_\phi(\mathbf{x}), \operatorname{diag}(\boldsymbol{\sigma}_\phi^2(\mathbf{x})))\).
-
Hai Chứng minh Chính xác Cận dưới Bằng chứng (
ELBO):- Cách 1 — Phân rã
KL: Vì \(\int q_\phi(\mathbf{z}\mid\mathbf{x})\,d\mathbf{z} = 1\) và \(\ln p_\theta(\mathbf{x}) = \ln \frac{p_\theta(\mathbf{x},\mathbf{z})}{p_\theta(\mathbf{z}\mid\mathbf{x})}\) không phụ thuộc \(\mathbf{z}\):\[\begin{aligned} \ln p_\theta(\mathbf{x}) &= \int q_\phi(\mathbf{z}\mid\mathbf{x}) \ln\!\left(\frac{p_\theta(\mathbf{x},\mathbf{z})}{q_\phi(\mathbf{z}\mid\mathbf{x})} \cdot \frac{q_\phi(\mathbf{z}\mid\mathbf{x})}{p_\theta(\mathbf{z}\mid\mathbf{x})}\right) d\mathbf{z} \\ &= \underbrace{\mathbb{E}_{q_\phi(\mathbf{z}\mid\mathbf{x})}\!\left[\ln \frac{p_\theta(\mathbf{x},\mathbf{z})}{q_\phi(\mathbf{z}\mid\mathbf{x})}\right]}_{\operatorname{ELBO}(\theta,\phi;\mathbf{x})} + \underbrace{D_{\text{KL}}\big(q_\phi(\mathbf{z}\mid\mathbf{x}) \parallel p_\theta(\mathbf{z}\mid\mathbf{x})\big)}_{\ge 0}. \end{aligned}\] - Cách 2 — Bất đẳng thức Jensen: Áp dụng tính lõm chặt của \(\ln(\cdot)\):
\[\ln p_\theta(\mathbf{x}) = \ln \mathbb{E}_{q_\phi(\mathbf{z}\mid\mathbf{x})}\!\left[\frac{p_\theta(\mathbf{x},\mathbf{z})}{q_\phi(\mathbf{z}\mid\mathbf{x})}\right] \;\ge\; \mathbb{E}_{q_\phi(\mathbf{z}\mid\mathbf{x})}\!\left[\ln \frac{p_\theta(\mathbf{x},\mathbf{z})}{q_\phi(\mathbf{z}\mid\mathbf{x})}\right] = \mathbb{E}_{q_\phi}[\ln p_\theta(\mathbf{x}\mid\mathbf{z})] - D_{\text{KL}}\big(q_\phi(\mathbf{z}\mid\mathbf{x}) \parallel p(\mathbf{z})\big).\]
- Cách 1 — Phân rã
-
Dạng Đóng Chính xác cho Phân kỳ
KLGauss Đường chéo: Với \(q_\phi(z_j\mid\mathbf{x}) = \mathcal{N}(\mu_j, \sigma_j^2)\) (\(\ell_j := \ln \sigma_j^2\) bị kẹp an toàn trong[-20, 10]) và \(p(z_j) = \mathcal{N}(0, 1)\), sử dụng \(\mathbb{E}_{q_j}[(z_j-\mu_j)^2] = \sigma_j^2\) và \(\mathbb{E}_{q_j}[z_j^2] = \mu_j^2 + \sigma_j^2\):\[D_{\text{KL}}\big(\mathcal{N}(\boldsymbol{\mu}, \operatorname{diag}(\boldsymbol{\sigma}^2)) \parallel \mathcal{N}(\mathbf{0}, \mathbf{I}_{d_z})\big) = -\frac{1}{2}\sum_{j=1}^{d_z}\Big(1 + \ln\sigma_j^2 - \mu_j^2 - \sigma_j^2\Big) \ge 0.\] -
Thủ thuật Tái tham số hóa (
Reparameterization Trick) vsREINFORCE: Lấy đạo hàm trực tiếp qua nút lấy mẫu ngẫu nhiên \(\mathbf{z} \sim q_\phi(\mathbf{z}\mid\mathbf{x})\) không khả vi theo \(\phi\). Bộ ước lượng hàm điểm sốREINFORCE\(\mathbb{E}_{q_\phi}[f(\mathbf{z})\nabla_\phi\ln q_\phi(\mathbf{z}\mid\mathbf{x})]\) bỏ qua hoàn toàn độ dốc giải mã \(\nabla_{\mathbf{z}} f(\mathbf{z})\) nên có phương sai rất lớn. Tách nhiễu ra biến phụ độc lập \(\boldsymbol{\epsilon} \sim \mathcal{N}(\mathbf{0}, \mathbf{I}_{d_z})\) biến \(\mathbf{z} = \boldsymbol{\mu}_\phi(\mathbf{x}) + \boldsymbol{\sigma}_\phi(\mathbf{x}) \odot \boldsymbol{\epsilon}\) thành hàm tất định trơn theo \((\boldsymbol{\mu}, \boldsymbol{\sigma})\), truyền gradient ngược thẳng từ hàm tái tạo qua từng sample đơn lẻ (\(L=1\)) với phương sai cực thấp. -
Posterior Collapse(\(D_{\text{KL}} \to 0\)) & Ba Biện pháp Khắc phục: Khi bộ giải mã \(p_\theta(\mathbf{x}\mid\mathbf{z})\) đủ mạnh để khớp phân phối biên \(p_{\text{data}}(\mathbf{x})\) mà không cần \(\mathbf{z}\), tối ưu hóa nhanh chóng triệt tiêu thành phầnKLvề0(\(q_\phi(\mathbf{z}\mid\mathbf{x}) \equiv \mathcal{N}(\mathbf{0},\mathbf{I})\)), làm chỉ số Active Units (AU, Burda et al. 2015: \(\sum_j \mathbb{I}[\operatorname{Var}_{\mathbf{x}}(\mu_{\phi,j}(\mathbf{x})) > 0.01]\)) sụp về0. Các cơ chế giải cứu chuẩn gồm:- \(\beta\)-VAE (
Higgins et al., ICLR 2017): Nhân trọng số \(\beta_{\text{VAE}}\) vào \(D_{\text{KL}}\) (\(\beta_{\text{VAE}} < 1\) cứu tái tạo/tránh sập; \(\beta_{\text{VAE}} > 1\) ép tách rời các nhân tố ẩn độc lập). - Lịch \(\beta\)-Annealing Tuần hoàn (
Fu et al., NAACL 2019): Cho \(\beta_{\text{VAE}}(t) = \beta_{\max}\min(1, u_t / R_{\text{ramp}})\) lặp lại theo \(C\) chu kỳ để tái khởi động mã hóa trước khi siết chặt tiên nghiệm. - Sàn Tự do (
Free Bits,Kingma et al., NeurIPS 2016): Áp ngưỡng sàn theo chiều trên trung bình mini-batch \(\sum_{j=1}^{d_z} \max\!\big(\lambda_{\text{fb}},\, \bar{D}_{\text{KL},j}\big)\), triệt tiêu gradient KL mỗi khi chiều \(j\) rơi dưới \(\lambda_{\text{fb}}\) nats. TrongLab 07(Test 05),Static beta = 1.0sụp đổ xuốngAU = 0/6,KL = 0.002 nats, cònCyclical + Free Bitskhôi phụcAU = 6/6,KL = 1.09 nats.
- \(\beta\)-VAE (
1.6 Biểu diễn Rời rạc: VQ-VAE, EMA & Nâng cấp 2024–2025 (FSQ, LFQ, Rotation Trick)#
VQ-VAE (van den Oord et al., NeurIPS 2017) thay phân phối Gauss liên tục bằng từ điển rời rạc \(\mathbf{E} = [\mathbf{e}_1,\dots,\mathbf{e}_{K_{\text{vq}}}]^\top \in \mathbb{R}^{K_{\text{vq}} \times d_z}\). Vì phân phối hậu nghiệm một-nóng dưới tiên nghiệm đều \(1/K_{\text{vq}}\) có \(D_{\text{KL}} \equiv \ln K_{\text{vq}}\) không đổi, mô hình hoàn toàn tránh được Posterior Collapse. Đầu ra mã hóa \(\mathbf{z}_e(\mathbf{x})\) ánh xạ sang mã gần nhất \(\mathbf{z}_q(\mathbf{x}) = \mathbf{e}_{k^*}\) (\(k^* = \arg\min_j \lVert \mathbf{z}_e(\mathbf{x}) - \mathbf{e}_j \rVert_2\)) và truyền gradient qua phép xấp xỉ đi thẳng Straight-Through Estimator (STE) \(\mathbf{z}_{\text{ste}} = \mathbf{z}_e + \operatorname{sg}[\mathbf{z}_q - \mathbf{z}_e]\) với hàm mất mát 3 hạng tử:
Tuy nhiên, khởi tạo kém khiến đa số vector \(\mathbf{e}_j\) không bao giờ thắng lệnh argmin và nhận gradient bằng 0, gây sụp đổ bảng mã (Codebook Collapse). Cách giải quyết chuẩn gồm cập nhật bảng mã bằng trung bình trượt hàm mũ EMA (\(N_j^{(t)} = \gamma_{\text{ema}}N_j^{(t-1)} + (1-\gamma_{\text{ema}})n_j^{(t)}\), \(\mathbf{m}_j^{(t)} = \gamma_{\text{ema}}\mathbf{m}_j^{(t-1)} + (1-\gamma_{\text{ema}})\mathbf{s}_j^{(t)}\) kèm làm trơn Laplace) và khởi tạo lại mã chết (Dead-Code Reset) khi \(N_j^{(t)} < \tau_{\text{dead}}\) (Lab 07 Test 06: nâng Perplexity từ 10.15 với 11/16 mã lên 14.38 với trọn vẹn 16/16 mã sống).
Các đột phá 2024–2025 tiến thêm ba bước lớn:
FSQ(Finite Scalar Quantization, Mentzer et al., ICLR 2024): Chiếu ẩn xuống \(d_z \le 8\) chiều, chặn \(\tanh\) và làm tròn vô hướng độc lập từng chiều lên tập nguyên cố định \(L_i\), tạo bảng mã tích Đề-các ngầm \(K_{\text{vq}} = \prod_i L_i\) miễn nhiễm hoàn toàn với sụp đổ bảng mã, không cần bảng tra hay mất mát cam kết \(\beta_{\text{vq}}\).LFQ(Lookup-Free Quantization, Yu et al. /MAGVIT-v2, ICLR 2024): Lượng tử hóa nhị phân \(\{-1, +1\}^{d_z}\) (\(2^{d_z}\) mã) kèm phạt entropy \(\mathbb{E}[H(\mathbf{q})] - H(\mathbb{E}[\mathbf{q}])\) ép sử dụng đều mọi đỉnh siêu lập phương.The Rotation Trick(Fifty et al., ICLR 2025 Oral): Chỉ ra rằngSTEtruyền Jacobian đơn vị \(\mathbf{I}\) nên mù hoàn toàn trước góc lệch và tỷ lệ độ lớn giữa \(\mathbf{z}_e\) và \(\mathbf{z}_q\); thay bằng biến đổi phản xạ Householder dừng gradient \(\tilde{\mathbf{q}} = \operatorname{sg}(\frac{\lVert \mathbf{z}_q \rVert}{\lVert \mathbf{z}_e \rVert}\mathbf{R})\mathbf{z}_e\) trong \(\mathcal{O}(d_z)\) phép tính, bảo toàn thông tin góc và biên độ khi lan truyền ngược.
1.7 Toán học Bộ ba Nén Mô hình (Pruning, Knowledge Distillation, PTQ/QAT) & Mô hình Roofline#
Theo mô hình Roofline (Williams et al., 2009), hiệu năng nhân ma trận bị chặn bởi \(P(I) = \min(P_{\text{peak}}, B_{\text{mem}}\cdot I)\) với cường độ tính toán \(I = \frac{\text{FLOPs}}{\text{Bytes}}\). Với suy luận đơn mẫu Batch = 1 ở cổng biên IoT, một lớp tuyến tính \(\mathbf{W} \in \mathbb{R}^{M\times K}\) thực hiện \(2MK\) FLOPs nhưng phải đọc \(b_{\text{elem}}MK\) byte trọng số, tức \(I \approx \frac{2}{b_{\text{elem}}}\) (0.5 FLOP/B ở FP32 vs 2.0 FLOP/B ở INT8)—rơi sâu vào vùng nghẽn băng thông bộ nhớ (memory-bandwidth bound). Mọi kỹ thuật nén chỉ tăng tốc thật nếu giảm được lượng byte thực sự đọc từ DRAM/Cache hoặc khớp đơn vị phần cứng chuyên dụng:
-
Tỉa thưa Phi cấu trúc vs Có cấu trúc (
Pruning):- Phi cấu trúc (
l1_unstructured) đặt các phần tử \(|W_{ij}| < \tau_p\) về0, nhưng ma trận lưu trữ đặc vẫn giữ nguyên kích thước \(4MK\) byte (0%tiết kiệm RAM) và nhânBLASvẫn thực thi đủ \(2MK\) phép nhân–cộng; chuyển sang lưu thưaCSRlại phát sinh chỉ mụcint32và truy cập gián đoạn phá vỡ vector hóaSIMDcho đến tận mức thưa \(> 90\text{–}95\%\). Phần cứng GPU Ampere/Hopper+ chỉ tăng tốc ở mẫu bán cấu trúc2:4(50%thưa) nhờSparse Tensor Cores. - Có cấu trúc (
Structured Width/Channel Pruning) loại bỏ cả hàng/cột neuron có chuẩn nhóm \(\sqrt{\lVert \mathbf{W}_{1,k,:} \rVert_2^2 + \lVert \mathbf{W}_{2,:,k} \rVert_2^2}\) nhỏ nhất, cắt vật lý ma trận từ \(h \to h' = (1-s_p)h\), hạ tham số vàFLOPstheo tỷ lệ chính xác \((1-s_p)\) (hoặc \((1-s_p)^2\) khi cắt cả đầu vào lẫn đầu ra hai lớp liên tiếp).
- Phi cấu trúc (
-
Chưng cất Tri thức (
Knowledge Distillation — KD, Hinton et al. 2015) & Chứng minh Hệ số \(T_{\text{kd}}^2\): Cho phân phối mềm ở nhiệt độ \(T_{\text{kd}} > 0\): \(p_{T,k}^{T_{\text{kd}}} = \operatorname{softmax}(\mathbf{z}_T/T_{\text{kd}})_k\), \(p_{S,k}^{T_{\text{kd}}} = \operatorname{softmax}(\mathbf{z}_S/T_{\text{kd}})_k\). Đạo hàm phân kỳKLtheo logit học trò là:\[\frac{\partial D_{\text{KL}}(\mathbf{p}_T^{T_{\text{kd}}} \parallel \mathbf{p}_S^{T_{\text{kd}}})}{\partial z_{S,i}} = \frac{1}{T_{\text{kd}}}\big(p_{S,i}^{T_{\text{kd}}} - p_{T,i}^{T_{\text{kd}}}\big).\]Ở giới hạn nhiệt độ cao \(T_{\text{kd}} \gg \max_j |z_j|\), khai triển Taylor \(e^{z_j/T_{\text{kd}}} = 1 + \frac{z_j}{T_{\text{kd}}} + O(T_{\text{kd}}^{-2})\) thu được \(p_{S,i}^{T_{\text{kd}}} \approx \frac{1}{C}\big(1 + \frac{z_{S,i} - \bar{z}_S}{T_{\text{kd}}}\big)\), suy ra:
\[\frac{\partial D_{\text{KL}}(\mathbf{p}_T^{T_{\text{kd}}} \parallel \mathbf{p}_S^{T_{\text{kd}}})}{\partial z_{S,i}} = \frac{1}{C\, T_{\text{kd}}^2}\Big[(z_{S,i} - \bar{z}_S) - (z_{T,i} - \bar{z}_T)\Big] + O(T_{\text{kd}}^{-3}).\]Do độ lớn gradient tỷ lệ nghịch \(1/T_{\text{kd}}^2\), hàm mất mát
KDbắt buộc phải nhân bù hệ số \(T_{\text{kd}}^2\) để giữ tỷ lệ gradient \(\Theta(1)\) cân bằng với mất mát tác vụ gốc:\[\mathcal{L}_{\text{KD}} = \alpha_{\text{kd}}\,T_{\text{kd}}^2\,D_{\text{KL}}\big(\mathbf{p}_T^{T_{\text{kd}}} \parallel \mathbf{p}_S^{T_{\text{kd}}}\big) + (1-\alpha_{\text{kd}})\mathcal{L}_{\text{task}}(\mathbf{z}_S, y).\]Đối với
Autoencodervà hồi quyRUL, kết hợp thêm căn chỉnh trạng thái ẩnFitNets(Romero et al., 2015) \(\lVert \mathbf{M}\mathbf{z}_S - \mathbf{z}_T \rVert_2^2\) giúp Student mảnh hơn phục hồi sát chất lượng Teacher. -
Lượng tử hóa (
PTQ&QAT) — Biến phân Sai số \(\Delta_q^2/12\) & Đánh đổi Cắt đuôi Ngoại lai:- Affine vs Đối xứng (
Symmetric, \(z_p = 0\)): Với \(b_q\) bit (e.g.INT8đối xứng dùng \([-(2^{b_q-1}-1), 2^{b_q-1}-1] = [-127, 127]\) tránh trànSIMD-128 * -128):\[s_q = \Delta_q = \frac{\alpha_{\text{clip}}}{2^{b_q-1}-1}, \qquad q(x) = \operatorname{clip}\!\left(\operatorname{round}\!\left(\frac{x}{\Delta_q}\right),\; -127,\; 127\right), \qquad \hat{x} = \Delta_q\, q(x).\] - Cận phương sai nhiễu làm tròn: Dưới giả định sai số làm tròn phân bố đều \(e_{\text{round}} \sim \operatorname{Uniform}[-\Delta_q/2, \Delta_q/2]\) bên trong vùng không bão hòa \([-\alpha_{\text{clip}}, \alpha_{\text{clip}}]\):
\[\mathbb{E}\big[(x - \hat{x})^2 \mid \lvert x \rvert \le \alpha_{\text{clip}}\big] = \int_{-\Delta_q/2}^{\Delta_q/2} \frac{u^2}{\Delta_q}\,du = \frac{\Delta_q^2}{12} \quad (+6.02\text{ dB SNR mỗi bit tăng thêm}).\]
- Phân rã Sai số Làm tròn vs Cắt đuôi: Tổng sai số lượng tử hóa \(\mathbb{E}[(x-\hat{x})^2] \approx \frac{\Delta_q(\alpha_{\text{clip}})^2}{12}\mathbb{P}(\lvert x\rvert \le \alpha_{\text{clip}}) + \int_{\lvert x\rvert > \alpha_{\text{clip}}}(\lvert x\rvert - \alpha_{\text{clip}})^2 p(x)\,dx\) lý giải sự sụp đổ của
MinMaxdưới xung ngoại lai (±48.0), đồng thời dẫn tới các phương pháp SOTA như hiệu chuẩnPercentile/MSE/KL-Entropy,SmoothQuant(\(\mathbf{Y} = (\mathbf{X}\operatorname{diag}(\mathbf{s})^{-1})(\operatorname{diag}(\mathbf{s})\mathbf{W})\) di chuyển ngoại lai từ kích hoạt sang trọng số),AWQ/GPTQ(W4A16), vàQAT(Jacob et al., 2018) chèn nútFakeQuantizekèmSTEđể tinh chỉnh lại trọng số quanh ranh giới làm tròn.
- Affine vs Đối xứng (
Trụ cột 2 — Kiến trúc Hệ thống Production, Chẩn đoán, Bảo mật & Ngân sách Edge IoT#
2.1 Chẩn đoán Huấn luyện & Sức khỏe Biểu diễn (Analyze Model Performance)#
Không giống phân loại có nhãn thông thường, một Autoencoder có thể đạt Val Loss cực thấp nhưng vẫn vô dụng nếu rơi vào bẫy sao chép đồng nhất (tái tạo cả điểm bất thường) hoặc bẫy sụp đổ không gian ẩn. Mọi đường ống huấn luyện phải giám sát 6 chỉ số sau:
| Trục Chẩn đoán | Công thức / Thước đo | Ngưỡng Khỏe mạnh | Dấu hiệu Bệnh lý & Cách Khắc phục |
|---|---|---|---|
Động lực học Train/Val Loss |
\(\mathcal{L}_{\text{train}}, \mathcal{L}_{\text{val}}, \Delta_{\text{gen}}\) | Giảm đồng đều, \(\Delta_{\text{gen}}\) nhỏ | Bất thường cũng cho lỗi thấp \(\to\) thu hẹp \(d_z\), thêm nhiễu DAE hoặc phạt CAE |
Tách nhánh VAE Recon vs KL |
Theo dõi riêng \(\mathcal{L}_{\text{recon}}\) và \(D_{\text{KL}}\) | Cả hai ổn định dương | \(D_{\text{KL}} \to 0\) còn \(\mathcal{L}_{\text{recon}}\) đứng im \(\to\) bật Cyclical Annealing + Free Bits |
| Chuẩn Gradient \(L_2\) | \(g_t = \sqrt{\sum_\ell \lVert \nabla_{\mathbf{W}_\ell}\mathcal{L}_t \rVert_F^2}\) | Dao động mượt trong \([10^{-2}, 10^1]\) | Bùng nổ (\(g_t \gg G_{\max}\)) \(\to\) cắt chuẩn gradient; triệt tiêu \(\to\) đổi SiLU/GELU + skip |
Tỷ lệ Nút chết (ReLU/SAE) |
\(r_{\text{dead}} = \frac{1}{H}\sum_j \mathbb{I}[\text{avg}(h_j > 0) = 0]\) | \(r_{\text{dead}} < 5\%\) | \(r_{\text{dead}} > 20\%\) \(\to\) dùng TopK + AuxK / JumpReLU, chuẩn hóa cột giải mã |
VAE Active Units (AU) |
\(A_j = \operatorname{Var}_{\mathbf{x}}(\mu_{\phi,j}(\mathbf{x})) > 0.01\) | \(\text{AU} \approx d_{\mathcal{M}}\) | \(\text{AU} \ll d_z\) hoặc 0 \(\to\) không gian ẩn bị triệt tiêu về tiên nghiệm \(\mathbf{0}\) |
VQ-VAE Perplexity (PPL) |
\(\exp(-\sum_{k=1}^{K_{\text{vq}}} \hat{p}_k \ln \hat{p}_k)\) | \(\text{PPL}/K_{\text{vq}} \ge 50\%\) | \(\text{PPL} \ll K_{\text{vq}}\) \(\to\) bật cập nhật EMA + khởi tạo lại mã chết hoặc chuyển sang FSQ |
2.2 Bảo mật Chuỗi cung ứng (safetensors vs pickle) & Đóng gói Đồ thị (ONNX / AOTInductor)#
-
Vá Triệt để Lỗ hổng
CWE-502bằngsafetensors:
Mỗi tệp.safetensorsgồm đúng 3 phân đoạn tất định không chứa bất kỳ mã bytecode thực thi nào:8 byte uint64 little-endiankhai báo độ dài \(N_{\text{hdr}}\), tiếp theo là tiêu đềUTF-8 JSONánh xạ tên tensor sang{"dtype", "shape", "data_offsets": [begin, end]}, và cuối cùng là vùng đệm byte thô liên tiếp không chồng chéo và không có khoảng hở polyglot. Bộ nạp kiểm tra toàn vẹn kích thước trong \(O(T_{\text{tensors}})\) trước khi ánh xạ bộ nhớ ảommapzero-copy trên NVMe (nhanh hơn nhiều so với dựng đồ thị đối tượngpickle). Cảnh báo hạ tầng Cloud (NFS/GCSFuse): Tránh dùngmmapmặc định trực tiếp trên ổ mạng vì hàng nghìn lỗi trang4 KBtuần tự có thể làm chậm khởi động Pod gấp5x–15x; hãy đồng bộ tệp về NVMe cục bộ hoặc đọc tuần tự vào RAM. -
Tách Rời Runtime Python bằng
ONNX+onnxruntimeCPU &AOTInductor:
Khi triển khai sang cổng biên công nghiệp hoặc dịch vụ C++,ONNXlưu đồ thị tính toán tĩnh độc lập khung huấn luyện đểonnxruntime(ORT) thực thi hợp nhất toán tử (ORT_ENABLE_ALL:Gemm + SiLU, gấp hằng số) bằng nhânMLAS(AVX2/AVX-512/NEON) không vướng Python GIL. TrongPyTorch 2.9–2.15+:torch.onnx.export(..., dynamo=True)là mặc định mới dựa trêntorch.export+onnxscript; nếu thiếuonnxscript, phải truyền tường minhdynamo=False(nhưng chỉ an toàn cho đồ thị tĩnh không rẽ nhánh điều kiện theo dữ liệu).- Khi đồ thị có toán tử tùy biến khó dịch sang
ONNX, có thể dùngtorch.export.export\(\to\)aoti_compile_and_package(.pt2) để biên dịch thẳng sang mã máy C++ không cần thông dịch viên Python.
2.3 Kiến trúc 3 Tầng IoT Predictive Maintenance Chống Rò rỉ (C-MAPSS Fleet)#
Trong bảo trì dự đoán đội động cơ tuabin (GE Predix, Airbus Skywise, Rolls-Royce TotalCare, NASA C-MAPSS), kiến trúc chuẩn công nghiệp gồm một màng lọc chống rò rỉ nghiêm ngặt kết nối 3 tầng quyết định nối tiếp:
- Tách nhóm Theo
Engine-ID& Trừ nền Nhân quả: Toàn bộ tậptrain / cal / testphải tách tuyệt đối theoengine_id(0trùng lặp động cơ). Độ lệch chế tạo từng máy được loại bằng phép trừ nền chỉ trên 15 chu kỳ đầu (t <= 15), và các bộ chuẩn hóa z-score theo chế độ vận hành chỉ được học trên chu kỳ khỏe của tậptrain. - Tầng 1 — Phát hiện Bất thường
Healthy-Only AE/VAE& Ngưỡng Bayes: Chỉ huấn luyện AE trên chu kỳ khỏe (RUL >= 65) để học cấu trúc tương quan nhiệt–áp suất bình thường; dùng điểm bất thường thô hiệu chuẩn bằng hồi quy Platt trên tậpD_calđộc lập (ECE-10 < 0.03), rồi kích hoạt cảnh báo tại ngưỡng chi phí Bayes tối ưu:\[t^* = \frac{c_{\text{FP}}}{c_{\text{FP}} + c_{\text{FN}}} = \frac{800}{800 + 50{,}000} = 0.01575.\] - Tầng 2 — Dự báo Tuổi thọ Còn lại (
RUL) Cắt ngọn & Hàm điểm NASAPHM08: Nhãn mục tiêu cắt ngọn theo mảnh tuyến tính \(\tilde{y} = \min(\text{RUL}, \text{RUL}_{\max})\) với \(\text{RUL}_{\max} = 125\) nhằm tránh lãng phí dung lượng khớp nhiễu ngẫu nhiên ở vùng khỏe sớm. Đánh giá bằngRMSEvà hàm phạt bất đối xứngPHM08(\(d_i^{\text{rul}} = \widehat{\text{RUL}}_i - \text{RUL}_i\)), phạt lũy thừa nặng hơn nhiều khi dự báo trễ (\(d_i^{\text{rul}} \ge 0\)):\[s_i(d_i^{\text{rul}}) = \begin{cases} \exp\!\left(-\dfrac{d_i^{\text{rul}}}{13}\right) - 1, & d_i^{\text{rul}} < 0 \quad (\text{cảnh báo sớm}), \\[6pt] \exp\!\left(+\dfrac{d_i^{\text{rul}}}{10}\right) - 1, & d_i^{\text{rul}} \ge 0 \quad (\text{bỏ sót trễ}). \end{cases}\] - Tầng 3 — Quy gán Nguyên nhân Gốc rễ (
RCA) về Phân hệ Vật lý: Kết hợp phần dư tái tạo chuẩn hóa theo phương sai khỏe \(a_j^{\text{res}}(\mathbf{x}) = \frac{(x_j - \hat{x}_j)^2}{\sigma_{j,\text{healthy}}^2 + \varepsilon}\) với độ nhạy gradient đầu vào \(a_j^{\text{grad}}(\mathbf{x}) = \lvert \frac{\partial S_{\text{anom}}}{\partial x_j} x_j \rvert\) (hoặcInterventional SHAPtrong phân hệ cảm biếnFan,HPC,Combustor,HPT), chọn ra Top-3 cảm biến nghi vấn hàng đầu để lập lệnh bảo trì đích danh.
2.4 Ngân sách Hệ thống Edge (Latency, Memory, Cost) & 10 Chống Bẫy CI/CD#
Trên cổng biên công nghiệp (ARM Cortex-A72, Intel Atom x6000E, 100 Hz – 1 kHz telemetry), ngân sách triển khai bắt buộc gồm: dung lượng gói trọng số/đồ thị < 200 KB (trú gọn trong bộ nhớ đệm L2 CPU), độ trễ p99 đơn mẫu < 5.0 ms (0.017–1.8 ms trong ORT C++ đơn luồng), vòng lặp khóa liên động PLC < 50 ms, sai số hiệu chuẩn ECE-10 < 0.03, và tỷ lệ định vị Top-3 RCA >= 85%.
| # | Phản mẫu Sản xuất (Anti-Pattern) |
Cơ chế Hỏng hóc Thầm lặng | Cổng Kiểm toán Tự động CI | Biện pháp Sửa dứt điểm |
|---|---|---|---|---|
1 |
Lưu/nạp trọng số qua .pt / pickle / joblib (CWE-502) |
Thực thi mã từ xa qua __reduce__; vượt mặt picklescan và weights_only=True (CVE-2025-32434) |
Quét AST cấm mọi import pickle/joblib/dill + kiểm tra tệp nhị phân |
Dùng safetensors cho trọng số và ONNX cho đồ thị thực thi |
2 |
Dùng safetensors mmap trực tiếp trên NFS / GCSFuse |
Hàng nghìn lỗi trang 4 KB ngẫu nhiên làm treo khởi động Pod 5x–15x |
Kiểm thử độ trễ cold-start p99 trên ổ gắn mạng |
Sao chép tạm về NVMe cục bộ hoặc đọc tuần tự vào RAM |
3 |
torch.onnx.export(..., dynamo=False) khi có nhánh động |
Đóng băng duy nhất nhánh đi qua tensor mẫu; dynamo=True lỗi thiếu onnxscript |
Kiểm thử parity nhiều hình dạng đầu vào khẳng định max_diff < 1e-4 |
Cài onnxscript cho đồ thị động, hoặc giữ DAG tĩnh + cố định kích thước biên |
4 |
Tỉa thưa phi cấu trúc 80% để giảm RAM/tăng tốc CPU |
Hook mặt nạ làm chậm 2.1x–2.5x; sau remove() vẫn chiếm 100% RAM & GEMM đặc |
Đo độ trễ p99 và kích thước buffer thực tế trên CPU biên |
Dùng Structured Width Pruning + FitNets KD |
5 |
Lượng tử hóa INT8 bằng MinMax khi cảm biến có xung EMI |
Một xung ±48 đẩy \(\Delta_q\) giãn rộng, ép tín hiệu bình thường vào 11 mức (14.8 dB) |
Kiểm thử SQNR và PR-AUC trên tập có chèn xung nhiễu |
Dùng hiệu chuẩn Percentile 99.5% / MSE hoặc tinh chỉnh QAT |
6 |
Chạy PyTorch + Python GIL ở Batch-1 trên cổng PLC |
Tiêu tốn > 600 MB runtime, vượt xa trần < 200 KB L2 & < 5 ms p99 |
Kiểm thử phần cứng vòng lặp (< 5 ms, artifact < 200 KB) |
Xuất Student INT8 sang ONNX + ORT C++ đơn luồng |
7 |
Tách ngẫu nhiên theo dòng chu kỳ (Leaky Cycle Split) |
Chu kỳ kề nhau và eng_bias bị rò rỉ (RMSE 8.92 giả \(\to\) 34.23 thực tế) |
Khẳng định set(train_id).isdisjoint(test_id) (0 trùng lặp) |
Bắt buộc Engine-ID GroupSplit + trừ nền t <= 15 |
8 |
Hồi quy RUL tuyến tính không cắt ngọn RUL_max = 125 |
Mô hình tiêu tốn năng lực khớp nhiễu ở vùng khỏe sớm, làm tệ điểm PHM08 |
So sánh Late-Life RMSE (RUL <= 50) và tổng điểm PHM08 |
Cắt ngọn RUL_max = 125 và tối ưu nhạy trễ |
9 |
Chọn ngưỡng đối xứng mean + 3*std hoặc p = 0.50 |
mean+3*std gây bão báo giả (231 FP); p=0.50 bỏ sót 28 FN (1.41M USD) |
Kiểm tra ECE < 0.03 và tổng chi phí thực trên D_cal tách rời |
Hiệu chuẩn Platt + ngưỡng Bayes \(t^* = \frac{c_{\text{FP}}}{c_{\text{FP}}+c_{\text{FN}}}\) |
10 |
Bắn cảnh báo bất thường không kèm quy gán RCA |
Kỹ thuật viên không biết tháo Fan, HPC hay HPT, gây mệt mỏi cảnh báo |
Đánh giá Top-3 RCA Hit Rate >= 85% trên động cơ có nhãn lỗi |
Kết hợp phần dư chuẩn hóa \(\sigma_{j,\text{healthy}}^2\) và gradient đầu vào |
Trụ cột 3 — Stack Công nghệ 2026 & Mã Mẫu Python Thực thi được#
Đoạn mã độc lập dưới đây chạy trực tiếp trong môi trường Python 3.12+ của dự án (D:\FSDS-SOTA-Curriculum\.venv với torch 2.15.0+cpu, safetensors 0.8.0, onnx 1.23.2, onnxruntime 1.32.0, pydantic 2.14.4), chứng minh trọn vẹn quy trình: (1) xác thực hợp đồng bằng Pydantic v2 (extra="forbid"), (2) cắt tỉa kênh có cấu trúc 128 -> 48, (3) lưu/nạp safetensors không pickle kèm kiểm tra phân đoạn 8 byte <Q + JSON (max_diff = 0.0), (4) xuất ONNX (dynamo=False) kiểm chứng onnx.checker và onnxruntime CPU (max_diff = 2.98e-08 < 1e-4), và (5) lượng tử hóa đối xứng INT8 (3.431x INT8, 9.092x tổng cộng) cùng phép giải cứu SQNR (14.79 -> 41.49 dB) dưới xung nhiễu ±48.0 EMI:
from __future__ import annotations
import io
import json
import struct
import warnings
import numpy as np
import onnx
import onnxruntime as ort
from pydantic import BaseModel, ConfigDict, Field
from safetensors.torch import load as safetensors_load
from safetensors.torch import save as safetensors_save
import torch
import torch.nn as nn
class EdgeExportContract(BaseModel):
"""Hợp đồng kiểm chứng đóng gói và nén biên (Zero-Pickle)."""
model_config = ConfigDict(extra="forbid")
n_sensors: int = Field(ge=4)
teacher_hidden: int = Field(ge=16)
student_hidden: int = Field(ge=8)
latent_dim: int = Field(ge=2)
percentile_q: float = Field(gt=90.0, lt=100.0)
seed: int = 42
class SensorAutoencoder(nn.Module):
"""Kiến trúc Autoencoder cảm biến IoT tối ưu cho xuất ONNX tĩnh."""
def __init__(self, n_sensors: int, hidden_dim: int, latent_dim: int) -> None:
super().__init__()
self.fc1 = nn.Linear(n_sensors, hidden_dim)
self.act1 = nn.SiLU()
self.fc2 = nn.Linear(hidden_dim, latent_dim)
self.fc3 = nn.Linear(latent_dim, hidden_dim)
self.act2 = nn.SiLU()
self.fc4 = nn.Linear(hidden_dim, n_sensors)
def forward(self, x: torch.Tensor) -> torch.Tensor:
z = self.fc2(self.act1(self.fc1(x)))
return self.fc4(self.act2(self.fc3(z)))
def structured_prune_ae(teacher: SensorAutoencoder, keep_hidden: int) -> SensorAutoencoder:
"""Cắt tỉa có cấu trúc theo chuẩn nhóm L2 và thu gọn kích thước ma trận vật lý."""
with torch.no_grad():
enc_score = torch.linalg.vector_norm(teacher.fc1.weight, dim=1) + torch.linalg.vector_norm(
teacher.fc2.weight, dim=0
)
dec_score = torch.linalg.vector_norm(teacher.fc3.weight, dim=1) + torch.linalg.vector_norm(
teacher.fc4.weight, dim=0
)
enc_idx = torch.topk(enc_score, k=keep_hidden, largest=True).indices.sort().values
dec_idx = torch.topk(dec_score, k=keep_hidden, largest=True).indices.sort().values
student = SensorAutoencoder(teacher.fc1.in_features, keep_hidden, teacher.fc2.out_features)
student.fc1.weight.copy_(teacher.fc1.weight[enc_idx, :])
student.fc1.bias.copy_(teacher.fc1.bias[enc_idx])
student.fc2.weight.copy_(teacher.fc2.weight[:, enc_idx])
student.fc2.bias.copy_(teacher.fc2.bias)
student.fc3.weight.copy_(teacher.fc3.weight[dec_idx, :])
student.fc3.bias.copy_(teacher.fc3.bias[dec_idx])
student.fc4.weight.copy_(teacher.fc4.weight[:, dec_idx])
student.fc4.bias.copy_(teacher.fc4.bias)
return student.eval()
def symmetric_int8_sqnr_db(x: np.ndarray, clip_alpha: float) -> tuple[float, int]:
"""Tính SQNR (dB) và số mức INT8 khả dụng trên dải tín hiệu vận hành chuẩn."""
scale = max(float(clip_alpha), 1e-8) / 127.0
q = np.clip(np.round(x / scale), -127, 127).astype(np.int8)
x_hat = q.astype(np.float32) * scale
normal_mask = np.abs(x) <= 2.0
active_bins = int(np.unique(q[normal_mask]).size)
sig_pow = float(np.mean(x[normal_mask] ** 2))
err_pow = float(np.mean((x[normal_mask] - x_hat[normal_mask]) ** 2)) + 1e-12
sqnr = 10.0 * float(np.log10(sig_pow / err_pow))
return sqnr, active_bins
def run_pillar3_specimen(cfg: EdgeExportContract) -> dict[str, float | int]:
"""Thực thi trọn vẹn pipeline đóng gói safetensors, ONNX dynamo=False và INT8 PTQ."""
torch.manual_seed(cfg.seed)
rng = np.random.default_rng(cfg.seed)
teacher = SensorAutoencoder(cfg.n_sensors, cfg.teacher_hidden, cfg.latent_dim).eval()
student = structured_prune_ae(teacher, cfg.student_hidden)
# 1. Lưu & nạp bằng safetensors + kiểm tra phân đoạn 8-byte uint64 + JSON (zero pickle)
sf_bytes = safetensors_save(student.state_dict())
hdr_len = struct.unpack("<Q", sf_bytes[:8])[0]
hdr_json = json.loads(sf_bytes[8 : 8 + hdr_len].decode("utf-8"))
assert len(hdr_json) == len(student.state_dict())
reloaded = SensorAutoencoder(cfg.n_sensors, cfg.student_hidden, cfg.latent_dim).eval()
reloaded.load_state_dict(safetensors_load(sf_bytes))
sf_max_diff = max(
float((p1.detach() - p2.detach()).abs().max())
for p1, p2 in zip(student.parameters(), reloaded.parameters(), strict=True)
)
assert sf_max_diff < 1e-6
# 2. Xuất ONNX (dynamo=False trên môi trường không cài onnxscript) & kiểm chứng ORT CPU
onnx_buf = io.BytesIO()
dummy_x = torch.randn(1, cfg.n_sensors, dtype=torch.float32)
with warnings.catch_warnings():
warnings.simplefilter("ignore", DeprecationWarning)
torch.onnx.export(
reloaded,
(dummy_x,),
onnx_buf,
dynamo=False,
input_names=["sensors"],
output_names=["recon"],
dynamic_axes={"sensors": {0: "batch"}, "recon": {0: "batch"}},
opset_version=17,
)
onnx_model = onnx.load_model_from_string(onnx_buf.getvalue())
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_buf.getvalue(), sess_options=opts, providers=["CPUExecutionProvider"])
test_batch = torch.randn(16, cfg.n_sensors, dtype=torch.float32)
with torch.no_grad():
pt_out = reloaded(test_batch).numpy()
ort_out = session.run(None, {"sensors": test_batch.numpy()})[0]
ort_max_diff = float(np.max(np.abs(pt_out - ort_out)))
assert ort_max_diff < 1e-4
# 3. Nén INT8 (>= 3.0x) & giải cứu SQNR khi có 0.3% xung nhiễu EMI ±48.0
teacher_fp32_bytes = sum(p.numel() * 4 for p in teacher.parameters())
student_fp32_bytes = sum(p.numel() * 4 for p in reloaded.parameters())
student_int8_bytes = sum(
p.numel() * (1 if p.ndim == 2 else 4) + (4 if p.ndim == 2 else 0)
for p in reloaded.parameters()
)
int8_ratio = student_fp32_bytes / student_int8_bytes
assert int8_ratio >= 3.0
calib = rng.normal(0.0, 0.6, size=(4000, cfg.n_sensors)).astype(np.float32)
calib[rng.random(calib.shape) < 0.003] = 48.0
sqnr_minmax, bins_minmax = symmetric_int8_sqnr_db(calib, float(np.max(np.abs(calib))))
sqnr_pct, bins_pct = symmetric_int8_sqnr_db(calib, float(np.percentile(np.abs(calib), cfg.percentile_q)))
assert sqnr_pct > sqnr_minmax + 10.0
return {
"safetensors_bytes": len(sf_bytes),
"safetensors_max_diff": sf_max_diff,
"onnx_bytes": len(onnx_buf.getvalue()),
"ort_max_diff": ort_max_diff,
"teacher_fp32_bytes": teacher_fp32_bytes,
"student_fp32_bytes": student_fp32_bytes,
"student_int8_bytes": student_int8_bytes,
"int8_compression_ratio": round(int8_ratio, 3),
"total_compression_ratio": round(teacher_fp32_bytes / student_int8_bytes, 3),
"sqnr_minmax_db": round(sqnr_minmax, 2),
"bins_minmax": bins_minmax,
"sqnr_percentile_db": round(sqnr_pct, 2),
"bins_percentile": bins_pct,
}
if __name__ == "__main__":
summary = run_pillar3_specimen(
EdgeExportContract(
n_sensors=16,
teacher_hidden=128,
student_hidden=48,
latent_dim=6,
percentile_q=99.5,
seed=42,
)
)
print(json.dumps(summary, indent=2))
raise SystemExit(0)
(Kết quả thực thi trực tiếp trong .venv với exit 0: safetensors_bytes = 9480, safetensors_max_diff = 0.0, onnx_bytes = 9988, ort_max_diff = 2.98e-08, int8_compression_ratio = 3.431, total_compression_ratio = 9.092, sqnr_minmax_db = 14.79 (11 bins) \(\to\) sqnr_percentile_db = 41.49 (255 bins).)
Trụ cột 4 — Phòng thí nghiệm Thực chiến (Lab 07: iot_ae_pdm_lab) & Rubric Đánh giá Chống Rò rỉ#
4.1 Kiến trúc Hai Tầng (Two-Tier) của Lab 07#
Toàn bộ mã nguồn thực nghiệm đặt tại labs/lab-07-iot-predictive-maintenance-rul-rca/README.md dưới gói iot_ae_pdm_lab:
- Tầng 1 (
Reference Corethuần Python/NumPy —autoencoders_and_compression.py): Hiện thực từ gốcfit_linear_ae_numpyđối chứngcompute_pca_basis(SVD),fit_denoising_ae_numpy, chuẩn Frobenius Jacobiancontractive_jacobian_penalty_sigmoid, và lượng tử hóa đối xứng tự hiệu chuẩn. - Tầng 2 (
PyTorch 2.x CPU,safetensors,ONNX/ORT,scikit-learn& Đường ống 3 Tầng IoT PdM —autoencoders_and_compression.py+pdm_pipeline.py): Hiện thực đầy đủSparse AE(l1,topk,jumprelu),VAE(sụp đổ tĩnh vsCyclical Annealing + Free Bits),VQ-VAE(STE,EMA, khôi phục mã chết), xuất/nạpsafetensors+ONNX (dynamo=False)trênCPUExecutionProvider, tỉa thưa cấu trúc +FitNetsKD +INT8PTQ, và đường ống 3 tầng mô phỏng đội động cơ16cảm biến trên4phân hệ (Fan,HPC,Combustor,HPT).
4.2 Kết quả Thực nghiệm Chuẩn hóa (seed=42, artifacts/ch15_lab07_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 |
|---|---|---|---|
| Linear AE vs PCA | NumPy ALS (\(d_z < D_x\)) vs PCA |
Góc không gian con 6.07e-15 rad; AE MSE = 0.00743 (EY = 0.00743); lệch trực giao 3.30 |
Khớp định lý Bourlard–Kamp (< 1e-3 rad) |
Sparse AE (SAE) |
L1 vs TopK vs JumpReLU |
Biên độ: L1 = 0.19 | TopK = 1.03 (MSE = 0.058, \(L_0 = 3.0\)) | JumpReLU = 1.44 |
TopK & JumpReLU loại bỏ co rút Tibshirani |
| VAE Posterior Collapse | Static \(\beta=1\) vs Cyclical + Free Bits |
Static: AU = 0/6 (KL = 0.002) \(\to\) Cyclical: AU = 6/6 (KL = 1.09 nats) |
Giải cứu toàn bộ 6 chiều ẩn (AU >= 2) |
| VQ-VAE Codebook | No-EMA vs EMA + Dead Reset | No-EMA: PPL = 10.15 (11/16) \(\to\) EMA: PPL = 14.38 (16/16 mã sống) |
Chống sụp đổ bảng mã (+41.6% PPL) |
| An toàn & Nén Edge | safetensors / ONNX / INT8 |
sf diff = 0.00e+00; ORT diff = 3.81e-06 (0.020 ms); Unstruct 80% = 1.00x vs INT8 = 3.43x (9.09x tổng) |
0 pickle, vượt ngưỡng >= 3.0x |
Bẫy Outlier EMI ±48 |
MinMax vs Percentile 99.5% / MSE |
MinMax = 14.80 dB (11 bins) \(\to\) Percentile = 41.57 dB (255 bins, +26.8 dB), MSE = 42.48 dB |
Ngăn sụp đổ lượng tử hóa dưới xung nhiễu |
Rò rỉ Engine-ID PdM |
Leaky Cycle Split vs Engine-ID GroupSplit |
Leaky: 45 động cơ trùng (8.92 -> 34.23 live) vs Honest: 0 trùng lặp (10.36) |
Bắt buộc tách tuyệt đối theo engine_id |
| Tầng 1 Ngưỡng Bayes | mean+3*std / p=0.50 / Bayes \(t^*=0.0157\) |
PR-AUC = 0.997, ECE = 0.0050; Chi phí: 184,800 / 1,408,800 \(\to\) 123,600 USD (-33.1% / -91.2%) |
Giảm tối đa chi phí hỏng hóc bỏ sót |
Tầng 2 RUL & Tầng 3 RCA |
RUL_max=125 PHM08 & Edge INT8 Student |
RUL RMSE = 7.24 (PHM08 = 2,698 vs uncapped 4,639); Top-3 RCA = 100.0%; Edge INT8 3.36x (11.23x tổng, PR-AUC = 0.988, RUL = 7.23, RCA = 100.0%, 0.017 ms) |
Đạt trọn vẹn SLA Edge < 5 ms, RCA >= 85%, >= 3.0x |
4.3 Hợp đồng 16 Bài kiểm thử Tự động (tests/test_iot_ae_pdm_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à chặn miền sai trên mọi cấu hình AE, Compression, PdM |
2 |
test_02_linear_ae_pca_subspace_equivalence |
Linear AE hội tụ về không gian con PCA (angle < 1e-3 rad) và khớp sai số Eckart–Young |
3 |
test_03_sparse_ae_l1_vs_topk_and_jumprelu_no_shrinkage |
TopK đạt đúng \(L_0 = k\), tránh co rút biên độ của L1 và giữ tỷ lệ latent chết thấp |
4 |
test_04_denoising_ae_manifold_denoising_snr |
DAE giảm MSE so với đầu vào nhiễu tối thiểu > 2.5x |
5 |
test_05_vae_elbo_kl_collapse_vs_cyclical_annealing |
Chứng minh Posterior Collapse ở Static beta=1 vs phục hồi AU >= 2, KL > 0.25 ở Cyclical + Free Bits |
6 |
test_06_vqvae_ema_codebook_perplexity_vs_collapse |
Kiểm tra gradient STE truyền về encoder và EMA + Reset cho PPL cao hơn hẳn không EMA |
7 |
test_07_safetensors_zero_pickle_roundtrip_parity |
Kiểm tra header 8-byte <Q + JSON của safetensors (0 pickle) và sai số tái nạp < 1e-6 |
8 |
test_08_onnx_dynamo_false_and_ort_cpu_parity |
Xuất torch.onnx.export(..., dynamo=False) và đối chứng onnxruntime CPU (max_abs_diff < 1e-4) |
9 |
test_09_structured_vs_unstructured_pruning_and_kd_scaling |
Unstructured 80% giữ 1.0x RAM (0% tiết kiệm), Structured cắt ma trận vật lý, FitNets KD phục hồi sai số |
10 |
test_10_int8_ptq_outlier_trap_minmax_vs_percentile_mse |
Percentile/MSE cứu >= +10 dB SQNR dưới xung ±48 EMI; gói INT8 đạt nén >= 3.0x |
11 |
test_11_cmapss_fleet_engine_group_split_zero_leakage_vs_leaky_cycle |
Khẳng định 0 trùng lặp engine_id, trừ nền/chuẩn hóa chỉ trên tập train khỏe, vạch trần Leaky Cycle Split |
12 |
test_12_stage1_healthy_only_anomaly_cal_and_bayes_cost |
PR-AUC >= 0.85, ECE-10 < 0.06, ngưỡng Bayes \(t^*\) rẻ hơn hẳn mean+3*std và p=0.50 |
13 |
test_13_stage2_capped_rul_and_nasa_phm08_asymmetry |
Xác nhận cắt ngọn RUL_max=125, bất đối xứng s(+d) > s(-d) của PHM08, và RMSE < 25 chu kỳ |
14 |
test_14_stage3_rca_subsystem_attribution_ge_85pct |
Quy gán RCA đạt top_3_rca_hit_rate >= 85% across các chế độ lỗi HPC, Fan, HPT |
15 |
test_15_compressed_edge_student_end_to_end_and_cli_workbench_schema |
Student INT8 nén >= 3.0x giữ nguyên chất lượng PdM, chạy CLI --quick và xác thực 6 KPI, 4 bar, 4 table |
16 |
test_16_security_only_ast_deserialization_guard |
Quét AST toàn bộ src/, scripts/, tests/ cấm tuyệt đối mọi import giải tuần tự hóa nguy hiểm |
Trụ cột 5 — Văn liệu Nền tảng, Hệ thống Ôn tập & Thang chấm Rubric#
5.1 Sáu Công trình Học thuật Nền tảng & SOTA (1988–2026)#
- Bourlard, H., & Kamp, Y. (1988) & Kingma, D. P., & Welling, M. (2013/2014). Auto-association by multilayer perceptrons and singular value decomposition (Biological Cybernetics) & Auto-Encoding Variational Bayes (
ICLR 2014). (Nền tảng tương đươngPCAdưới bất biến \(\operatorname{GL}_{d_z}(\mathbb{R})\), cận dướiELBO, và thủ thuật tái tham số hóa.) - Vincent, P. et al. (2010/2011) & van den Oord, A., Vinyals, O., & Kavukcuoglu, K. (2017). A connection between score matching and denoising autoencoders (Neural Computation) & Neural Discrete Representation Learning (
NeurIPS 2017). (Liên kếtDAEvới trường điểm số Tweedie và kiến trúcVQ-VAESTE+EMA.) - Gao, L. et al. (OpenAI, 2024) & Rajamanoharan, S. et al. (Google DeepMind, 2024). Scaling and evaluating sparse autoencoders (
arXiv:2406.04093,TopK + AuxK) & Jumping Ahead: Improving Reconstruction Fidelity with JumpReLU Sparse Autoencoders (arXiv:2407.14435). (Giải quyết co rút biên độ \(L_1\) và hồi sinh đặc trưng chết ở quy mô hàng triệu latent.) - Bussmann, B. et al. (2025) & Karvonen, A. et al. (ICML 2025). Learning Multi-Level Features with Matryoshka Sparse Autoencoders (
arXiv:2503.17547) & SAEBench (arXiv:2503.09532). (Từ điển phân cấp chống tách mảnh/hấp thụ đặc trưng và đánh giáSAEqua tác vụ xuôi dòngTPP.) - Mentzer, F. et al. (ICLR 2024) & Fifty, C. et al. (ICLR 2025 Oral). Finite Scalar Quantization: VQ-VAE Made Simple (
FSQ) & Restructuring Vector Quantization with the Rotation Trick (arXiv:2410.06424). (Lượng tử hóa vô hướng miễn nhiễm sụp đổ bảng mã và phép biến đổi Householder bảo toàn góc gradient.) - Hinton, G. et al. (2015), Xiao, G. et al. (ICML 2023) (
SmoothQuant), Lin, J. et al. (MLSys 2024) (AWQ), & Saxena, A. et al. (PHM 2008). (Nền tảng chưng cất tri thức \(T_{\text{kd}}^2\), nén lượng tử hóa bền vững ngoại lai, và chuẩn đánh giá bất đối xứngNASA C-MAPSS.)
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(Linear AEvsPCA): Không gian cột \(\mathbf{W}_2^*\) trùng khít không gian conPCA(6.07e-15 radtrongLab 07), nhưng từng trục ẩn bị xoay kéo bởi ma trận khả nghịch \(\mathbf{R} \in \operatorname{GL}_{d_z}(\mathbb{R})\) (orthogonality deviation = 3.30) nên không tự trực giao theo thứ tự eigenvector.Q2(SAE& SOTA 2024–2026):SAE-L1buộc phải chuẩn hóa cột giải mã \(\lVert \mathbf{W}_{2,:,j} \rVert_2 \le 1\) để chặn suy biến tỷ lệ và chịu co rút biên độ (0.19);TopK + AuxK(1.03) vàJumpReLU(1.44,KDE-STE) giữ nguyên biên độ và hồi sinh latent chết;Matryoshkachống phân mảnh khái niệm.Q3(DAE&CAE):DAEhọc trường điểm số Tweedie \(\frac{r^*(\mathbf{y})-\mathbf{y}}{\sigma_{\text{noise}}^2} = \nabla_{\mathbf{y}} \ln p_\sigma(\mathbf{y})\) (tăngSNRkhử nhiễu3.80xtrongLab 07);CAEnén chuẩn Frobenius Jacobian \(\sum [h_i(1-h_i)]^2 \lVert \mathbf{w}_{1,i} \rVert_2^2\) vuông góc đa tạp nhưng giữ nguyên phương tiếp tuyến.Q4(VAE&VQ-VAE): Bộ giải mã mạnh +Static beta = 1làm sụpAU = 0/6(KL = 0.002), được cứu lênAU = 6/6(KL = 1.09) bằngCyclical Annealing + Free Bits;VQ-VAE EMA + ResetnângPPLtừ10.15 -> 14.38, cònFSQmiễn nhiễm sụp đổ không cần bảng tra.Q5(safetensors&ONNX): Ngay cảweights_only=Truetrên PyTorch<= 2.5.1từng dínhCVE-2025-32434;safetensorsloại bỏpickle(diff = 0.00e+00, lưu ý tránhmmaptrực tiếp quaNFS/GCSFuse), còn xuấtONNXthiếuonnxscriptphải dùngdynamo=Falsecho DAG tĩnh (ORTCPU3.81e-06,0.020 ms).Q6(Nén Edge & Bẫy Ngoại lai): Tỉa thưa phi cấu trúc80%giữ1.00xRAM (0%tiết kiệm, quênprune.remove()chậm gấp2.1x–2.5x); Structured + FitNets (\(T_{\text{kd}}^2\)) +INT8nén3.43x INT8(9.09xtổng), vàPercentile 99.5%/MSEcứu+26.8 dB SQNR(14.80 -> 41.57 dB) dưới xung±48 EMI.Q7(Engine-ID GroupSplit& Bayest*): Tách chu kỳ ngẫu nhiên làm lộ45động cơ dùng chung (8.92 -> 34.23live);Engine-ID GroupSplitgiữ0trùng lặp (10.36), đạtPR-AUC = 0.997,ECE = 0.0050, và ngưỡng Bayes \(t^* = 0.0157\) (123,600 USD) tiết kiệm-33.1%vsmean+3*stdvà-91.2%vsp = 0.50.Q8(RUL PHM08,RCA& EdgeINT8): Cắt ngọnRUL_max = 125hạPHM08từ4,639 -> 2,698(RMSE = 7.24); quy gán phần dư chuẩn hóa + gradient đạt100.0% Top-3 RCA, và StudentINT8nén3.36x(11.23xtổng) giữ nguyên100.0% RCAở0.017 ms.
5.3 Sáu Bài tập Lập trình & Chứng minh Trọng số (Bài tập 1..6)#
-
Bài tập 1 (
15%) — Chứng minh Định lý Bourlard–Kamp & Bất biến \(\operatorname{GL}_{d_z}(\mathbb{R})\):Chứng minh đầy đủ bằng Định lý Eckart–Young–Mirsky tại sao \(\operatorname{col}(\mathbf{W}_2^*) = \operatorname{span}(\mathbf{u}_1,\dots,\mathbf{u}_{d_z})\) khi \(\sigma_{d_z} > \sigma_{d_z+1}\), giải thích ý nghĩa bất biến \(\mathbf{R} \in \operatorname{GL}_{d_z}(\mathbb{R})\), và chạy
fit_linear_ae_numpy(Test 02) kiểm chứng góc không gian con6.07e-15 radcùng độ lệch trực giao3.30. -
Bài tập 2 (
15%) — Toán họcSparse AE: Chuẩn cột Giải mã, Thiên lệchL1&TopK/JumpReLU:Chứng minh hiện tượng trôi tỷ lệ \(\mathbf{W}_1 \leftarrow c\mathbf{W}_1, \mathbf{W}_2 \leftarrow \mathbf{W}_2/c\) khi bỏ ràng buộc cột giải mã, dẫn xuất công thức soft-thresholding của thiên lệch co rút Tibshirani, rồi chạy
train_sparse_ae_comparison(Test 03) đối chứngL1(0.19) vsTopK(1.03) vsJumpReLU(1.44). -
Bài tập 3 (
20%) — Dẫn xuấtELBO,KLGauss,Tweedie DAE& Giải cứuPosterior Collapse:Viết lại cả hai chứng minh
ELBO, tích phân dạng đóng \(D_{\text{KL}}(\mathcal{N}(\boldsymbol{\mu},\operatorname{diag}(\boldsymbol{\sigma}^2)) \parallel \mathcal{N}(\mathbf{0},\mathbf{I}))\), và đồng nhất thức Tweedie choDAE; thực thifit_denoising_ae_numpy,train_vae_collapse_vs_annealed, vàtrain_vqvae_ema_vs_no_ema(Tests 04, 05, 06). -
Bài tập 4 (
20%) — Chuỗi cung ứngsafetensors/ONNX, Chứng minh \(T_{\text{kd}}^2\) & Giải cứuINT8Ngoại lai:Thực hiện khai triển Taylor chứng minh gradient
KLco lại \(\Theta(T_{\text{kd}}^{-2})\) khi \(T_{\text{kd}} \gg |z|\) và tính tích phân phương sai làm tròn \(\Delta_q^2/12\); chạyTests 07, 08, 09, 10kiểm chứngsafetensors(0.00e+00),ONNX (dynamo=False)(3.81e-06), ảo giác1.00xcủa tỉa phi cấu trúc vs3.43xINT8(9.09xtổng) và cú nhảy+26.8 dBcủaPercentile 99.5%. -
Bài tập 5 (
15%) — Kiểm toán Rò rỉEngine-ID& Chứng minh Ngưỡng Bayes Chi phí Bất đối xứng:Chứng minh quy tắc quyết định cực tiểu hóa rủi ro kỳ vọng \(t^* = \frac{c_{\text{FP}}}{c_{\text{FP}}+c_{\text{FN}}}\), giải thích vì sao tách chu kỳ ngẫu nhiên gây rò rỉ lớp 3 & lớp 4, rồi chạy
split_fleet_by_engine_id,run_leaky_cycle_split_contrast,fit_stage1_healthy_detector, vàcalibrate_and_threshold_bayes(Tests 11, 12). -
Bài tập 6 (
15%) — Đường ống 3 TầngAnomaly -> RUL (PHM08) -> RCA& Kiểm định Toàn trình (16/16 Pytest):Phân tích độ bất đối xứng của đạo hàm hàm điểm
PHM08tại \(d=0\), giải thích vai trò chuẩn hóa phương sai khỏe \(\sigma_{j,\text{healthy}}^2\) trongRCA, chạy trọn bộTests 13, 14, 15, 16,ruff,mypy, và xuấtartifacts/ch15_lab07_results.jsonquascripts/run_lab_demo.py.
5.4 Thang chấm Rubric (UCL MSc Grading Rubric)#
| Cấp độ Đạt chuẩn | Tiêu chí Lý thuyết & Chứng minh Toán học | Tiêu chí Hệ thống, Chống Rò rỉ & Thực nghiệm Lab 07 |
|---|---|---|
Distinction (70% – 100%) |
Chứng minh trọn vẹn Định lý Bourlard–Kamp, ELBO + KL Gauss, Tweedie DAE, hệ số \(T_{\text{kd}}^2\) trong KD, phương sai \(\Delta_q^2/12\) và ngưỡng Bayes \(t^*\); không nhầm ký hiệu \(\psi\)/\(\phi\), \(d_i^{\text{rul}}\), hay \(z_p\)/\(\mathbf{z}\) |
Vượt 16/16 pytest (0 lỗi ruff/mypy), 0 trùng lặp Engine-ID, PR-AUC >= 0.99, ECE < 0.01, Top-3 RCA = 100%, xuất chuẩn safetensors + ONNX (dynamo=False) parity < 1e-4, nén INT8 >= 3.0x và xử lý chuẩn bẫy xung EMI ±48 |
Merit (60% – 69%) |
Nắm chắc các công thức VAE, VQ-VAE, Pruning, KD, PTQ và mô hình PHM08, nhưng thiếu vài bước trung gian trong chứng minh Taylor \(T_{\text{kd}}^2\) hoặc bất biến \(\operatorname{GL}_{d_z}(\mathbb{R})\) |
Chạy đủ các thử nghiệm Lab 07 đạt mọi ngưỡng nghiệm thu (< 1e-3 rad, AU >= 2, >= 3.0x, Top-3 RCA >= 85%), còn thiếu sót nhỏ ở phân tích Roofline \(B=1\) hoặc bẫy NFS mmap |
Pass / Cần khắc phục (< 60%) |
Dùng pickle/torch.save làm định dạng triển khai, nhầm tỉa thưa phi cấu trúc với tăng tốc CPU thật, dùng MinMax PTQ dưới xung nhiễu, hoặc tách ngẫu nhiên theo dòng chu kỳ trên chuỗi cảm biến động cơ |
Để lọt trùng lặp engine_id > 0, bỏ qua hiệu chuẩn hoặc dùng ngưỡng đối xứng p = 0.50, Top-3 RCA < 85%, hoặc chưa vượt hết 16/16 pytest |
VAE Active Units & VQ-VAE Codebook Perplexity Rescue
Edge Compression Byte Footprint (KB) & INT8 Student Size
PdM Fleet Maintenance Cost by Decision Policy (Lower is Better, USD)
Leaky Cycle Split vs Honest Engine-ID RMSE & Top-3 RCA Hit Rate
Autoencoder Families & Representation Diagnostics
| Architecture | Key Metric | Observed Value | Target Gate |
|---|---|---|---|
| Linear AE (NumPy ALS) | Principal Angle vs PCA | 6.07e-15 rad | < 1e-3 rad (PASS) |
| Sparse AE (L1 vs TopK vs JumpReLU) | Amplitude Ratio (No Shrinkage) | L1=0.19 | TopK=1.03 | Jump=1.44 | TopK/Jump > L1 (PASS) |
| Denoising AE (Gaussian sigma=0.45) | Denoising MSE Gain | 3.80x (+5.8 dB) | > 2.5x vs noisy (PASS) |
| VAE (Static vs Cyclical + Free Bits) | Active Units (AU / 6) & KL | Static AU=0 (0.00) -> Cyclical AU=6 (1.09) | AU >= 2, KL > 0.25 (PASS) |
| VQ-VAE (No-EMA vs EMA + Dead Reset) | Codebook Perplexity (PPL) | No-EMA 10.15 -> EMA 14.38 | EMA > No-EMA (PASS) |
Supply-Chain-Safe Serialization & Edge Compression
| Artifact / Regime | Weight Size | Compression | Parity / SQNR |
|---|---|---|---|
| Teacher FP32 (TorchSensorAE) | 23640 B | 1.00x | MSE 0.0737 |
| Safetensors Round-Trip (0 pickle) | 24272 B | Zero-copy mmap | Max Diff 0.00e+00 (< 1e-6) |
| ONNX (dynamo=False) + ORT CPU | 24715 B | p50 0.020 ms | Max Diff 3.81e-06 (< 1e-4) |
| Unstructured 80% Magnitude Mask | 23640 B | 1.00x (0% saved) | Dense BLAS mirage |
| Structured + KD + INT8 Percentile 99.5% | 2600 B | 3.43x INT8 (9.09x total) | SQNR 41.6 dB vs MinMax 14.8 dB |
IoT PdM Leakage Audit, Bayes Thresholding & Stage 2 PHM08
| PdM Policy / Split | PR-AUC / ECE | FP / FN | Fleet Cost / Score |
|---|---|---|---|
| Leaky Cycle Split (Class 3+4) | 45 shared engines | — | Offline 8.92 -> Live 34.23 RMSE |
| Honest Engine-ID GroupSplit | 0 shared engines | — | Honest RMSE 10.36 cyc |
| Stage 1 Heuristic (mean + 3*std) | PR-AUC 0.997 | FP=231 / FN=0 | 184,800 USD |
| Stage 1 Symmetric (p = 0.50) | ECE-10 0.0050 | FP=11 / FN=28 | 1,408,800 USD |
| Stage 1 Bayes Optimal (t*=0.0157) | PR-AUC 0.997 | ECE 0.0050 | FP=92 / FN=1 | 123,600 USD (BEST) |
| Stage 2 Capped RUL (RUL_max=125) | Late RMSE 5.41 cyc | All RMSE 7.24 cyc | PHM08=2698 (vs Uncap 4639) |
Stage 3 Subsystem Root Cause Analysis (RCA) & Edge INT8 Student
| Fault Mode / Model | Target Subsystem | Top-3 Sensors | Top-3 RCA Hit Rate |
|---|---|---|---|
| Fan_imbalance | Fan | s03_NRf, s01_Nf, s02_T24 | 100.0% (Top-1 Sub 100.0%) |
| HPC_degradation | HPC | s06_P30, s07_Ps30, s05_T30 | 100.0% (Top-1 Sub 100.0%) |
| Turbine_thermal_erosion | HPT | s13_T50, s14_W31, s15_W32 | 100.0% (Top-1 Sub 99.5%) |
| Compressed INT8 Edge Student | All 4 Subsystems | PR-AUC 0.988 | RUL 7.2 cyc | 100.0% (3.36x INT8, 0.017 ms) |
02-track-1-data-science-and-ai/part-03-deep-learning-and-modern-cv/labs/lab-07-iot-predictive-maintenance-rul-rca
[build-system]
requires = ["setuptools>=68.0"]
build-backend = "setuptools.build_meta"
[project]
name = "iot-ae-pdm-lab"
version = "0.1.0"
description = "Lab 07: Autoencoders (Linear/Sparse/DAE/VAE/VQ-VAE), Safe Serialization (safetensors/ONNX), Edge Compression (Pruning/KD/INT8 PTQ) & Leakage-Proof IoT Predictive Maintenance (Anomaly -> RUL -> RCA) (T1-P3-U02)."
readme = "README.md"
requires-python = ">=3.12"
dependencies = [
"numpy>=1.26",
"onnx>=1.16",
"onnxruntime>=1.18",
"pydantic>=2.0",
"safetensors>=0.4",
"scikit-learn>=1.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 07 (`T1-P3-U02`): Autoencoders, Safe Serialization, Edge Compression & IoT Predictive Maintenance."""
from __future__ import annotations
from iot_ae_pdm_lab.autoencoders_and_compression import (
CompressionConfig,
DAEConfig,
LinearAEConfig,
SparseAEConfig,
TorchSensorAE,
VAEConfig,
VQVAEBottleneck,
VQVAEConfig,
calibrate_clipping_threshold,
compress_student_to_int8_bundle,
compute_active_units,
compute_codebook_perplexity,
compute_pca_basis,
contractive_jacobian_penalty_sigmoid,
cyclical_beta_schedule,
distill_student_ae,
evaluate_int8_sqnr,
export_and_verify_onnx_parity,
fit_denoising_ae_numpy,
fit_linear_ae_numpy,
gaussian_kl_divergence,
load_state_dict_safetensors,
quantize_symmetric_int8_tensor,
save_state_dict_safetensors,
structured_width_prune_ae,
subspace_principal_angle_rad,
train_sparse_ae_comparison,
train_vae_collapse_vs_annealed,
train_vqvae_ema_vs_no_ema,
unstructured_magnitude_prune_mask,
)
from iot_ae_pdm_lab.pdm_pipeline import (
ALL_SENSORS,
FAULT_TO_SUBSYSTEM,
SENSOR_TO_SUBSYSTEM,
SUBSYSTEM_SENSOR_MAP,
FleetSimConfig,
PdMCostConfig,
TorchRULRegressor,
calibrate_and_threshold_bayes,
cap_rul_targets,
compress_and_evaluate_edge_pdm,
compute_ece,
compute_pr_roc_auc,
compute_rca_sensor_attribution,
evaluate_rca_subsystem_hit_rate,
fit_stage1_healthy_detector,
fit_stage2_rul_predictor,
nasa_phm08_score,
run_full_ch15_lab07_benchmarks,
run_leaky_cycle_split_contrast,
score_anomaly_ae,
simulate_turbofan_fleet,
split_fleet_by_engine_id,
)
__all__ = [
"ALL_SENSORS",
"CompressionConfig",
"DAEConfig",
"FAULT_TO_SUBSYSTEM",
"FleetSimConfig",
"LinearAEConfig",
"PdMCostConfig",
"SENSOR_TO_SUBSYSTEM",
"SUBSYSTEM_SENSOR_MAP",
"SparseAEConfig",
"TorchRULRegressor",
"TorchSensorAE",
"VAEConfig",
"VQVAEBottleneck",
"VQVAEConfig",
"calibrate_and_threshold_bayes",
"calibrate_clipping_threshold",
"cap_rul_targets",
"compress_and_evaluate_edge_pdm",
"compress_student_to_int8_bundle",
"compute_active_units",
"compute_codebook_perplexity",
"compute_ece",
"compute_pca_basis",
"compute_pr_roc_auc",
"compute_rca_sensor_attribution",
"contractive_jacobian_penalty_sigmoid",
"cyclical_beta_schedule",
"distill_student_ae",
"evaluate_int8_sqnr",
"evaluate_rca_subsystem_hit_rate",
"export_and_verify_onnx_parity",
"fit_denoising_ae_numpy",
"fit_linear_ae_numpy",
"fit_stage1_healthy_detector",
"fit_stage2_rul_predictor",
"gaussian_kl_divergence",
"load_state_dict_safetensors",
"nasa_phm08_score",
"quantize_symmetric_int8_tensor",
"run_full_ch15_lab07_benchmarks",
"run_leaky_cycle_split_contrast",
"save_state_dict_safetensors",
"score_anomaly_ae",
"simulate_turbofan_fleet",
"split_fleet_by_engine_id",
"structured_width_prune_ae",
"subspace_principal_angle_rad",
"train_sparse_ae_comparison",
"train_vae_collapse_vs_annealed",
"train_vqvae_ema_vs_no_ema",
"unstructured_magnitude_prune_mask",
]
"""Tier 1 & Tier 2 implementations of Autoencoders, Safe Serialization, and Edge Compression.
Covers:
1. Linear AE vs PCA subspace equivalence (Bourlard-Kamp) in pure NumPy.
2. Sparse AE (L1 with unit-norm decoder, TopK+AuxK, JumpReLU with KDE-STE).
3. Denoising AE (DAE) & Contractive AE (CAE) analytical sigmoid Jacobian penalty.
4. Variational AE (VAE) ELBO, diagonal Gaussian KL, Cyclical Beta-Annealing & Free Bits.
5. Discrete VQ-VAE bottleneck (STE, commitment loss, EMA updates, dead-code reset).
6. Supply-chain-safe serialization (`safetensors` header verification, `ONNX dynamo=False` + ORT CPU).
7. Edge compression trio: unstructured mirage vs structured width pruning, FitNets + T_kd^2 KD,
and symmetric INT8 PTQ with MinMax vs Percentile/MSE outlier rescue.
"""
from __future__ import annotations
import copy
import json
import struct
import time
import warnings
from pathlib import Path
from typing import Any, Literal
import numpy as np
import onnx
import onnxruntime as ort
import torch
import torch.nn as nn
import torch.nn.functional as F
from pydantic import BaseModel, ConfigDict, Field, model_validator
from safetensors.torch import load_file as safetensors_load_file
from safetensors.torch import save_file as safetensors_save_file
from scipy.linalg import subspace_angles
# ---------------------------------------------------------------------------
# Strict Pydantic v2 Configuration Contracts (ConfigDict(extra="forbid"))
# ---------------------------------------------------------------------------
class LinearAEConfig(BaseModel):
"""Configuration for undercomplete Linear Autoencoder vs PCA equivalence."""
model_config = ConfigDict(extra="forbid")
input_dim: int = Field(default=16, ge=2)
latent_dim: int = Field(default=4, ge=1)
epochs: int = Field(default=250, ge=50)
lr: float = Field(default=0.05, gt=0.0)
seed: int = 42
@model_validator(mode="after")
def _validate_undercomplete(self) -> LinearAEConfig:
if self.latent_dim >= self.input_dim:
raise ValueError("LinearAE must be undercomplete: require latent_dim < input_dim.")
return self
class SparseAEConfig(BaseModel):
"""Configuration for overcomplete Sparse Autoencoders (L1, TopK, JumpReLU)."""
model_config = ConfigDict(extra="forbid")
input_dim: int = Field(default=16, ge=4)
latent_dim: int = Field(default=32, ge=8)
sparsity_mode: Literal["l1", "topk", "jumprelu"] = "topk"
l1_lambda: float = Field(default=0.12, ge=0.0)
topk: int = Field(default=4, ge=1)
jumprelu_theta: float = Field(default=0.35, gt=0.0)
lr: float = Field(default=0.012, gt=0.0)
epochs: int = Field(default=120, ge=20)
seed: int = 42
@model_validator(mode="after")
def _validate_overcomplete_and_k(self) -> SparseAEConfig:
if self.latent_dim <= self.input_dim:
raise ValueError("SparseAE must be overcomplete: require latent_dim > input_dim.")
if self.topk >= self.latent_dim:
raise ValueError("SparseAE topk must satisfy topk < latent_dim.")
return self
class DAEConfig(BaseModel):
"""Configuration for Denoising Autoencoder trained under Gaussian noise."""
model_config = ConfigDict(extra="forbid")
input_dim: int = Field(default=16, ge=4)
latent_dim: int = Field(default=8, ge=2)
noise_std: float = Field(default=0.45, gt=0.0)
epochs: int = Field(default=180, ge=20)
lr: float = Field(default=0.02, gt=0.0)
seed: int = 42
class VAEConfig(BaseModel):
"""Configuration for Variational Autoencoder with static or cyclical KL annealing."""
model_config = ConfigDict(extra="forbid")
input_dim: int = Field(default=16, ge=4)
latent_dim: int = Field(default=6, ge=2)
hidden_dim: int = Field(default=48, ge=8)
beta_max: float = Field(default=1.0, gt=0.0)
annealing_mode: Literal["static", "cyclical"] = "cyclical"
n_cycles: int = Field(default=4, ge=1)
ramp_ratio: float = Field(default=0.5, gt=0.0, le=1.0)
free_bits_lambda: float = Field(default=0.20, ge=0.0)
epochs: int = Field(default=60, ge=20)
lr: float = Field(default=0.005, gt=0.0)
seed: int = 42
class VQVAEConfig(BaseModel):
"""Configuration for VQ-VAE discrete bottleneck (EMA vs non-EMA)."""
model_config = ConfigDict(extra="forbid")
input_dim: int = Field(default=16, ge=4)
latent_dim: int = Field(default=4, ge=2)
num_codes: int = Field(default=16, ge=4)
commitment_beta: float = Field(default=0.25, gt=0.0)
use_ema: bool = True
ema_decay: float = Field(default=0.90, gt=0.0, lt=1.0)
dead_code_threshold: float = Field(default=1.0, ge=0.0)
epochs: int = Field(default=80, ge=20)
lr: float = Field(default=0.006, gt=0.0)
seed: int = 42
class CompressionConfig(BaseModel):
"""Configuration for Structured Pruning, FitNets KD, and Symmetric INT8 PTQ."""
model_config = ConfigDict(extra="forbid")
prune_ratio: float = Field(default=0.625, gt=0.0, lt=1.0)
kd_temperature: float = Field(default=4.0, gt=0.0)
kd_alpha: float = Field(default=0.5, ge=0.0, le=1.0)
quant_bits: Literal[8] = 8
quant_calibration: Literal["minmax", "percentile", "mse"] = "percentile"
percentile_q: float = Field(default=99.5, gt=90.0, lt=100.0)
seed: int = 42
# ---------------------------------------------------------------------------
# Tier 1 Core: Linear AE vs PCA Subspace Equivalence (Bourlard-Kamp 1988)
# ---------------------------------------------------------------------------
def compute_pca_basis(x_data: np.ndarray, latent_dim: int) -> dict[str, Any]:
"""Compute exact centered SVD PCA basis and Eckart-Young optimal MSE."""
x_arr = np.asarray(x_data, dtype=np.float64)
mean_vec = np.mean(x_arr, axis=0)
x_centered = x_arr - mean_vec
# Column-major sample matrix X_col in R^(D_x x N) so left singular vectors span feature space.
x_col = x_centered.T
u_mat, singular_vals, _ = np.linalg.svd(x_col, full_matrices=False)
u_dz = u_mat[:, :latent_dim]
n_samples, input_dim = x_arr.shape
eckart_young_mse = float(np.sum(singular_vals[latent_dim:] ** 2) / (n_samples * input_dim))
return {
"mean": mean_vec,
"x_centered": x_centered,
"u_dz": u_dz,
"singular_vals": singular_vals,
"eckart_young_mse": eckart_young_mse,
}
def subspace_principal_angle_rad(basis_a: np.ndarray, basis_b: np.ndarray) -> float:
"""Return the maximum principal angle (radians) between column spans of basis_a and basis_b."""
a = np.asarray(basis_a, dtype=np.float64)
b = np.asarray(basis_b, dtype=np.float64)
if a.shape[0] != b.shape[0]:
raise ValueError(f"Row dimensions must match for subspace angle: {a.shape} vs {b.shape}")
angles = subspace_angles(a, b)
return float(np.max(angles)) if angles.size > 0 else 0.0
def fit_linear_ae_numpy(x_data: np.ndarray, cfg: LinearAEConfig) -> dict[str, Any]:
"""Fit a pure NumPy undercomplete Linear AE via alternating least squares and verify PCA span."""
x_arr = np.asarray(x_data, dtype=np.float64)
if x_arr.shape[1] != cfg.input_dim:
raise ValueError(f"Expected input_dim={cfg.input_dim}, got {x_arr.shape[1]}")
pca = compute_pca_basis(x_arr, cfg.latent_dim)
x_centered = pca["x_centered"]
x_col = x_centered.T # (D_x, N)
u_dz = pca["u_dz"]
rng = np.random.default_rng(cfg.seed)
w_dec = rng.normal(0.0, 0.5, size=(cfg.input_dim, cfg.latent_dim))
reg = 1e-10 * np.eye(cfg.latent_dim, dtype=np.float64)
w_enc = np.linalg.solve(w_dec.T @ w_dec + reg, w_dec.T)
# Alternating least squares converges to the Bourlard-Kamp global minimum while retaining
# arbitrary GL_{d_z}(R) gauge mixing inside the principal subspace.
for _ in range(cfg.epochs):
w_enc = np.linalg.solve(w_dec.T @ w_dec + reg, w_dec.T)
h_mat = w_enc @ x_col # (d_z, N)
hh_t = h_mat @ h_mat.T + reg
w_dec = np.linalg.solve(hh_t, h_mat @ x_col.T).T
# Prevent ill-conditioned scaling drift while preserving non-orthogonal GL(R) gauge
col_norms = np.maximum(np.linalg.norm(w_dec, axis=0, keepdims=True), 1e-8)
w_dec = w_dec / col_norms
w_enc = np.linalg.solve(w_dec.T @ w_dec + reg, w_dec.T)
x_hat = (w_dec @ (w_enc @ x_col)).T
ae_mse = float(np.mean((x_centered - x_hat) ** 2))
angle_rad = subspace_principal_angle_rad(w_dec, u_dz)
# Measure deviation of W_dec columns from orthogonality to illustrate GL_{d_z}(R) gauge freedom
gram = w_dec.T @ w_dec
orth_dev = float(np.linalg.norm(gram - np.eye(cfg.latent_dim), ord="fro"))
return {
"ae_mse": ae_mse,
"eckart_young_mse": pca["eckart_young_mse"],
"mse_abs_diff": abs(ae_mse - pca["eckart_young_mse"]),
"subspace_principal_angle_rad": angle_rad,
"orthogonality_deviation_fro": orth_dev,
"singular_gap_ratio": float(
pca["singular_vals"][cfg.latent_dim - 1] / max(pca["singular_vals"][cfg.latent_dim], 1e-12)
),
"w_enc": w_enc,
"w_dec": w_dec,
"u_dz": u_dz,
}
# ---------------------------------------------------------------------------
# Tier 2: Sparse Autoencoders (L1 Unit-Norm, TopK+AuxK, JumpReLU KDE-STE)
# ---------------------------------------------------------------------------
class _HeavisideKDESTE(torch.autograd.Function):
"""Differentiable L0 Heaviside indicator with rectangle-kernel STE on threshold tau."""
@staticmethod
def forward(
ctx: Any, pre_act: torch.Tensor, tau: torch.Tensor, bandwidth: float
) -> torch.Tensor:
ctx.save_for_backward(pre_act, tau)
ctx.bandwidth = bandwidth
return (pre_act > tau).to(pre_act.dtype)
@staticmethod
def backward(
ctx: Any, grad_output: torch.Tensor
) -> tuple[torch.Tensor, torch.Tensor, None]:
pre_act, tau = ctx.saved_tensors
eps = ctx.bandwidth
rect = ((pre_act - tau).abs() <= 0.5 * eps).to(pre_act.dtype) / eps
grad_pre = grad_output * rect
grad_tau = -(grad_output * rect).sum(dim=0)
return grad_pre, grad_tau, None
class _JumpReLUAutograd(torch.autograd.Function):
"""JumpReLU activation z * H(z - tau) with KDE-STE derivative w.r.t. tau."""
@staticmethod
def forward(
ctx: Any, pre_act: torch.Tensor, tau: torch.Tensor, bandwidth: float
) -> torch.Tensor:
mask = (pre_act > tau).to(pre_act.dtype)
ctx.save_for_backward(pre_act, tau, mask)
ctx.bandwidth = bandwidth
return F.relu(pre_act) * mask
@staticmethod
def backward(
ctx: Any, grad_output: torch.Tensor
) -> tuple[torch.Tensor, torch.Tensor, None]:
pre_act, tau, mask = ctx.saved_tensors
eps = ctx.bandwidth
rect = ((pre_act - tau).abs() <= 0.5 * eps).to(pre_act.dtype) / eps
grad_pre = grad_output * mask
grad_tau = -(grad_output * tau * rect).sum(dim=0)
return grad_pre, grad_tau, None
def _compute_active_amplitude_ratio(
x_centered: np.ndarray, h_acts: np.ndarray, w_dec: np.ndarray
) -> float:
"""Compare active latent magnitudes against unpenalized OLS refits on active supports.
Under L1 regularization, Tibshirani shrinkage depresses amplitudes (< 0.90);
TopK and JumpReLU avoid amplitude shrinkage (~ 1.00).
"""
ratios: list[float] = []
n_check = min(len(x_centered), 256)
for idx in range(n_check):
active = np.flatnonzero(h_acts[idx] > 1e-6)
if active.size == 0:
continue
w_sub = w_dec[:, active] # (D_x, |S|)
gram = w_sub.T @ w_sub + 1e-4 * np.eye(active.size, dtype=np.float64)
h_ols = np.linalg.solve(gram, w_sub.T @ x_centered[idx])
denom = float(np.sum(np.maximum(h_ols, 0.0)))
if denom > 1e-4:
ratios.append(float(np.sum(h_acts[idx, active]) / denom))
return float(np.mean(ratios)) if ratios else 0.0
def train_sparse_ae_comparison(x_data: np.ndarray, cfg: SparseAEConfig) -> dict[str, Any]:
"""Train an overcomplete Sparse AE under 'l1', 'topk', or 'jumprelu' sparsity mode."""
x_arr = np.asarray(x_data, dtype=np.float32)
if x_arr.shape[1] != cfg.input_dim:
raise ValueError(f"Expected input_dim={cfg.input_dim}, got {x_arr.shape[1]}")
x_mean = x_arr.mean(axis=0, keepdims=True)
x_centered = x_arr - x_mean
x_t = torch.from_numpy(x_centered)
torch.manual_seed(cfg.seed)
w_enc = nn.Parameter(torch.randn(cfg.latent_dim, cfg.input_dim) * 0.15)
b_enc = nn.Parameter(torch.full((cfg.latent_dim,), 0.05 if cfg.sparsity_mode == "topk" else 0.0))
w_dec = nn.Parameter(torch.randn(cfg.input_dim, cfg.latent_dim) * 0.25)
b_dec = nn.Parameter(torch.zeros(cfg.input_dim))
with torch.no_grad():
w_dec.div_(torch.linalg.vector_norm(w_dec, dim=0, keepdim=True).clamp_min(1e-8))
params: list[torch.Tensor] = [w_enc, b_enc, w_dec, b_dec]
log_tau = nn.Parameter(torch.full((cfg.latent_dim,), float(np.log(cfg.jumprelu_theta))))
if cfg.sparsity_mode == "jumprelu":
params.append(log_tau)
optimizer = torch.optim.Adam(params, lr=cfg.lr)
bandwidth = 0.20
for _ in range(cfg.epochs):
optimizer.zero_grad()
pre_act = F.linear(x_t - b_dec, w_enc, b_enc)
if cfg.sparsity_mode == "l1":
h = F.relu(pre_act)
x_hat = F.linear(h, w_dec, b_dec)
recon_loss = F.mse_loss(x_hat, x_t)
sparsity_loss = cfg.l1_lambda * h.sum(dim=-1).mean()
loss = recon_loss + sparsity_loss
elif cfg.sparsity_mode == "topk":
# Ensure positive pre-activations via soft shift if needed while preserving TopK order
pre_pos = F.relu(pre_act) + 1e-4
top_vals, top_idx = torch.topk(pre_pos, k=cfg.topk, dim=-1)
h = torch.zeros_like(pre_act).scatter(-1, top_idx, top_vals)
x_hat = F.linear(h, w_dec, b_dec)
recon_loss = F.mse_loss(x_hat, x_t)
# AuxK resurrection term for inactive latents across batch
fire_counts = (h > 1e-5).float().mean(dim=0)
dead_mask = (fire_counts < 0.01).float()
aux_loss = torch.tensor(0.0)
if dead_mask.sum() > 0:
dead_pre = F.relu(pre_act) * dead_mask.unsqueeze(0)
k_aux = min(cfg.topk * 2, int(dead_mask.sum().item()))
aux_vals, aux_idx = torch.topk(dead_pre, k=k_aux, dim=-1)
h_aux = torch.zeros_like(pre_act).scatter(-1, aux_idx, aux_vals)
residual = (x_t - x_hat).detach()
aux_hat = F.linear(h_aux, w_dec)
aux_loss = 0.05 * F.mse_loss(aux_hat, residual)
loss = recon_loss + aux_loss
else: # "jumprelu"
tau = torch.exp(log_tau).clamp(0.05, 3.0)
h = _JumpReLUAutograd.apply(pre_act, tau, bandwidth)
l0_proxy = _HeavisideKDESTE.apply(pre_act, tau, bandwidth).sum(dim=-1).mean()
x_hat = F.linear(h, w_dec, b_dec)
recon_loss = F.mse_loss(x_hat, x_t)
loss = recon_loss + 0.018 * l0_proxy
loss.backward()
optimizer.step()
# Mandatory unit-norm decoder column projection blocking bilinear rescaling degeneracy
with torch.no_grad():
w_dec.div_(torch.linalg.vector_norm(w_dec, dim=0, keepdim=True).clamp_min(1e-8))
with torch.no_grad():
pre_eval = F.linear(x_t - b_dec, w_enc, b_enc)
if cfg.sparsity_mode == "l1":
h_eval = F.relu(pre_eval)
elif cfg.sparsity_mode == "topk":
pre_pos = F.relu(pre_eval) + 1e-4
top_vals, top_idx = torch.topk(pre_pos, k=cfg.topk, dim=-1)
h_eval = torch.zeros_like(pre_eval).scatter(-1, top_idx, top_vals)
else:
tau = torch.exp(log_tau).clamp(0.05, 3.0)
h_eval = F.relu(pre_eval) * (pre_eval > tau).to(pre_eval.dtype)
x_hat_eval = F.linear(h_eval, w_dec, b_dec)
recon_mse = float(F.mse_loss(x_hat_eval, x_t).item())
h_np = h_eval.cpu().numpy().astype(np.float64)
w_dec_np = w_dec.detach().cpu().numpy().astype(np.float64)
active_mask = h_np > 1e-5
mean_l0 = float(np.mean(np.sum(active_mask, axis=1)))
firing_freq = np.mean(active_mask, axis=0)
dead_latent_fraction = float(np.mean(firing_freq < 1e-3))
amp_ratio = _compute_active_amplitude_ratio(x_centered.astype(np.float64), h_np, w_dec_np)
return {
"sparsity_mode": cfg.sparsity_mode,
"recon_mse": recon_mse,
"mean_l0": mean_l0,
"dead_latent_fraction": dead_latent_fraction,
"active_amplitude_ratio": amp_ratio,
}
# ---------------------------------------------------------------------------
# Tier 1 Core: Denoising Autoencoder (DAE) & Contractive Jacobian Penalty
# ---------------------------------------------------------------------------
def contractive_jacobian_penalty_sigmoid(w_enc: np.ndarray, h: np.ndarray) -> float:
"""Compute exact Frobenius Jacobian squared norm for a sigmoid encoder:
||J_x h(x)||_F^2 = sum_i [h_i (1 - h_i)]^2 * ||w_enc[i, :]||_2^2
"""
w_arr = np.asarray(w_enc, dtype=np.float64)
h_arr = np.asarray(h, dtype=np.float64)
if w_arr.ndim != 2:
raise ValueError(f"Expected 2D w_enc (latent_dim, input_dim), got {w_arr.shape}")
row_norms_sq = np.sum(w_arr**2, axis=1)
dh_sq = (h_arr * (1.0 - h_arr)) ** 2
if dh_sq.ndim == 1:
return float(np.sum(dh_sq * row_norms_sq))
return float(np.mean(np.sum(dh_sq * row_norms_sq[None, :], axis=1)))
def _fit_numpy_ae_adam(
x_train_clean: np.ndarray,
latent_dim: int,
noise_std: float,
epochs: int,
lr: float,
seed: int,
weight_decay: float = 1e-3,
) -> tuple[dict[str, np.ndarray], np.ndarray, np.ndarray]:
"""Train a 1-hidden-layer tanh/linear Autoencoder in pure NumPy using Adam."""
rng = np.random.default_rng(seed)
x_mean = np.mean(x_train_clean, axis=0)
x_scale = np.maximum(np.std(x_train_clean, axis=0), 1e-6)
x_norm = (x_train_clean - x_mean) / x_scale
noise_norm = noise_std / x_scale
n_samples, input_dim = x_norm.shape
scale1 = 0.25 / np.sqrt(input_dim)
scale2 = 0.50 / np.sqrt(latent_dim)
params = {
"w1": rng.normal(0.0, scale1, size=(latent_dim, input_dim)),
"b1": np.zeros(latent_dim, dtype=np.float64),
"w2": rng.normal(0.0, scale2, size=(input_dim, latent_dim)),
"b2": np.zeros(input_dim, dtype=np.float64),
}
m = {k: np.zeros_like(v) for k, v in params.items()}
v = {k: np.zeros_like(v) for k, v in params.items()}
beta1, beta2, eps = 0.9, 0.999, 1e-8
for step in range(1, epochs + 1):
jitter = rng.normal(0.0, 1.0, size=x_norm.shape) * noise_norm if noise_std > 0 else 0.0
x_in = x_norm + jitter
z = x_in @ params["w1"].T + params["b1"]
h = np.tanh(z)
x_hat = h @ params["w2"].T + params["b2"]
diff = (x_hat - x_norm) * (2.0 / (n_samples * input_dim))
grad_w2 = diff.T @ h + weight_decay * params["w2"]
grad_b2 = np.sum(diff, axis=0)
dh = diff @ params["w2"]
dz = dh * (1.0 - h**2)
grad_w1 = dz.T @ x_in + weight_decay * params["w1"]
grad_b1 = np.sum(dz, axis=0)
grads = {"w1": grad_w1, "b1": grad_b1, "w2": grad_w2, "b2": grad_b2}
for k, g in grads.items():
m[k] = beta1 * m[k] + (1.0 - beta1) * g
v[k] = beta2 * v[k] + (1.0 - beta2) * (g**2)
m_hat = m[k] / (1.0 - beta1**step)
v_hat = v[k] / (1.0 - beta2**step)
params[k] -= lr * m_hat / (np.sqrt(v_hat) + eps)
return params, x_mean, x_scale
def fit_denoising_ae_numpy(x_clean: np.ndarray, cfg: DAEConfig) -> dict[str, Any]:
"""Fit a pure NumPy Denoising AE under Gaussian corruption and contrast with unregularized AE."""
x_arr = np.asarray(x_clean, dtype=np.float64)
if x_arr.shape[1] != cfg.input_dim:
raise ValueError(f"Expected input_dim={cfg.input_dim}, got {x_arr.shape[1]}")
split_idx = int(0.75 * len(x_arr))
x_train = x_arr[:split_idx]
x_test = x_arr[split_idx:]
# Use effective corruption matching data scale so DAE contracts orthogonal manifold noise
eff_noise = max(cfg.noise_std, 0.55 * float(np.mean(np.std(x_train, axis=0))))
dae_params, x_mean, x_scale = _fit_numpy_ae_adam(
x_train, cfg.latent_dim, eff_noise, max(cfg.epochs, 360), max(cfg.lr, 0.03), cfg.seed, 2e-4
)
# Unregularized overcomplete AE trained cleanly without noise passes Gaussian noise through
unreg_params, u_mean, u_scale = _fit_numpy_ae_adam(
x_train,
max(cfg.input_dim * 2, cfg.latent_dim * 2),
0.0,
max(cfg.epochs, 360),
max(cfg.lr, 0.03),
cfg.seed + 1,
0.0,
)
rng = np.random.default_rng(cfg.seed + 999)
x_test_noisy = x_test + rng.normal(0.0, eff_noise, size=x_test.shape)
def _forward(
p: dict[str, np.ndarray], mu: np.ndarray, sc: np.ndarray, x_in: np.ndarray
) -> np.ndarray:
x_n = (x_in - mu) / sc
h_val = np.tanh(x_n @ p["w1"].T + p["b1"])
return (h_val @ p["w2"].T + p["b2"]) * sc + mu
dae_recon = _forward(dae_params, x_mean, x_scale, x_test_noisy)
unreg_recon = _forward(unreg_params, u_mean, u_scale, x_test_noisy)
noisy_input_mse = float(np.mean((x_test_noisy - x_test) ** 2))
dae_recon_mse = float(np.mean((dae_recon - x_test) ** 2))
unreg_noisy_mse = float(np.mean((unreg_recon - x_test) ** 2))
denoising_gain_ratio = noisy_input_mse / max(dae_recon_mse, 1e-12)
snr_gain_db = 10.0 * float(np.log10(max(denoising_gain_ratio, 1e-12)))
# Analytical sigmoid Jacobian diagnostic on encoder weights
x_test_n = (x_test - x_mean) / x_scale
h_sig = 1.0 / (
1.0 + np.exp(-np.clip(x_test_n @ dae_params["w1"].T + dae_params["b1"], -20.0, 20.0))
)
cae_penalty = contractive_jacobian_penalty_sigmoid(dae_params["w1"], h_sig)
return {
"noisy_input_mse": noisy_input_mse,
"dae_recon_mse": dae_recon_mse,
"unregularized_ae_noisy_mse": unreg_noisy_mse,
"denoising_gain_ratio": denoising_gain_ratio,
"snr_gain_db": snr_gain_db,
"contractive_jacobian_norm": cae_penalty,
}
# ---------------------------------------------------------------------------
# Tier 2: Variational AE (ELBO, Gaussian KL, Cyclical Beta & Free Bits)
# ---------------------------------------------------------------------------
def gaussian_kl_divergence(mu: torch.Tensor, logvar: torch.Tensor) -> torch.Tensor:
"""Compute exact closed-form KL(q(z|x) || N(0, I)) with log-variance stability clamp [-20, 10]."""
logvar_c = torch.clamp(logvar, min=-20.0, max=10.0)
kl_per_dim = -0.5 * (1.0 + logvar_c - mu.pow(2) - torch.exp(logvar_c))
return torch.sum(kl_per_dim, dim=-1)
def cyclical_beta_schedule(
step: int, total_steps: int, n_cycles: int, ramp_ratio: float, beta_max: float
) -> float:
"""Fu et al. (NAACL 2019) cyclical KL annealing schedule in [0, beta_max]."""
if total_steps <= 0:
return float(beta_max)
period = max(float(total_steps) / max(n_cycles, 1), 1.0)
tau = (float(step) % period) / period
return float(beta_max * min(1.0, tau / max(ramp_ratio, 1e-8)))
def compute_active_units(mu_all: np.ndarray, threshold: float = 0.01) -> int:
"""Burda et al. (2015) Active Units metric: count dims where Var_x(mu_j(x)) > threshold."""
mu_arr = np.asarray(mu_all, dtype=np.float64)
return int(np.sum(np.var(mu_arr, axis=0) > threshold))
class _TabularVAE(nn.Module):
"""MLP Variational Autoencoder with reparameterization trick."""
def __init__(self, input_dim: int, hidden_dim: int, latent_dim: int) -> None:
super().__init__()
self.enc_net = nn.Sequential(
nn.Linear(input_dim, hidden_dim),
nn.SiLU(),
nn.Linear(hidden_dim, hidden_dim),
nn.SiLU(),
)
self.fc_mu = nn.Linear(hidden_dim, latent_dim)
self.fc_logvar = nn.Linear(hidden_dim, latent_dim)
self.dec_net = nn.Sequential(
nn.Linear(latent_dim, hidden_dim),
nn.SiLU(),
nn.Linear(hidden_dim, hidden_dim),
nn.SiLU(),
nn.Linear(hidden_dim, input_dim),
)
def encode(self, x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
h = self.enc_net(x)
return self.fc_mu(h), torch.clamp(self.fc_logvar(h), min=-20.0, max=10.0)
def reparameterize(self, mu: torch.Tensor, logvar: torch.Tensor) -> torch.Tensor:
std = torch.exp(0.5 * logvar)
eps = torch.randn_like(std)
return mu + std * eps
def forward(self, x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
mu, logvar = self.encode(x)
z = self.reparameterize(mu, logvar)
return self.dec_net(z), mu, logvar
def _train_single_vae(x_tensor: torch.Tensor, cfg: VAEConfig) -> dict[str, Any]:
"""Train one VAE under either static beta or cyclical beta-annealing + Free Bits."""
torch.manual_seed(cfg.seed)
model = _TabularVAE(cfg.input_dim, cfg.hidden_dim, cfg.latent_dim)
optimizer = torch.optim.Adam(model.parameters(), lr=cfg.lr)
# Under standard observation noise scaling (sigma_x^2 = D_x / 2.2), static beta=1.0
# from epoch 0 collapses the encoder before meaningful latents form.
recon_scale = 2.2
batch_size = min(128, len(x_tensor))
steps_per_epoch = max(1, (len(x_tensor) + batch_size - 1) // batch_size)
total_steps = cfg.epochs * steps_per_epoch
step = 0
for _ in range(cfg.epochs):
perm = torch.randperm(len(x_tensor))
for start in range(0, len(x_tensor), batch_size):
batch = x_tensor[perm[start : start + batch_size]]
beta_t = (
cfg.beta_max
if cfg.annealing_mode == "static"
else cyclical_beta_schedule(
step, total_steps, cfg.n_cycles, cfg.ramp_ratio, cfg.beta_max
)
)
optimizer.zero_grad()
x_hat, mu, logvar = model(batch)
recon = 0.5 * recon_scale * F.mse_loss(x_hat, batch, reduction="mean")
kl_per_dim_batch = -0.5 * (
1.0 + logvar - mu.pow(2) - torch.exp(logvar)
) # (B, d_z)
kl_dim_means = kl_per_dim_batch.mean(dim=0)
if cfg.free_bits_lambda > 0.0:
kl_term = torch.clamp(kl_dim_means, min=cfg.free_bits_lambda).sum()
else:
kl_term = kl_dim_means.sum()
loss = recon + beta_t * kl_term
loss.backward()
optimizer.step()
step += 1
model.eval()
with torch.no_grad():
mu_all, logvar_all = model.encode(x_tensor)
x_recon = model.dec_net(mu_all)
recon_mse = float(F.mse_loss(x_recon, x_tensor).item())
kl_nats = float(gaussian_kl_divergence(mu_all, logvar_all).mean().item())
mu_np = mu_all.cpu().numpy()
au = compute_active_units(mu_np, threshold=0.01)
return {
"annealing_mode": cfg.annealing_mode,
"recon_mse": recon_mse,
"kl_nats": kl_nats,
"active_units": au,
"latent_dim": cfg.latent_dim,
"per_dim_var": [round(float(v), 4) for v in np.var(mu_np, axis=0)],
}
def train_vae_collapse_vs_annealed(
x_data: np.ndarray,
latent_dim: int = 6,
beta_max: float = 1.0,
free_bits_lambda: float = 0.2,
epochs: int = 60,
seed: int = 42,
) -> dict[str, Any]:
"""Contrast static-beta posterior collapse against cyclical annealing + Free Bits rescue."""
x_arr = np.asarray(x_data, dtype=np.float32)
x_std = (x_arr - x_arr.mean(axis=0, keepdims=True)) / np.maximum(
x_arr.std(axis=0, keepdims=True), 1e-6
)
x_t = torch.from_numpy(x_std)
input_dim = int(x_arr.shape[1])
cfg_static = VAEConfig(
input_dim=input_dim,
latent_dim=latent_dim,
hidden_dim=48,
beta_max=beta_max,
annealing_mode="static",
free_bits_lambda=0.0,
epochs=epochs,
seed=seed,
)
cfg_cyclical = VAEConfig(
input_dim=input_dim,
latent_dim=latent_dim,
hidden_dim=48,
beta_max=beta_max,
annealing_mode="cyclical",
n_cycles=4,
ramp_ratio=0.5,
free_bits_lambda=free_bits_lambda,
epochs=epochs,
seed=seed,
)
static_res = _train_single_vae(x_t, cfg_static)
cyclical_res = _train_single_vae(x_t, cfg_cyclical)
return {
"static": static_res,
"cyclical": cyclical_res,
"au_gain": int(cyclical_res["active_units"]) - int(static_res["active_units"]),
"kl_gain_nats": float(cyclical_res["kl_nats"]) - float(static_res["kl_nats"]),
}
# ---------------------------------------------------------------------------
# Tier 2: Discrete VQ-VAE (STE, Commitment Loss, EMA + Dead-Code Reset)
# ---------------------------------------------------------------------------
def compute_codebook_perplexity(indices: np.ndarray, num_codes: int) -> float:
"""Compute discrete codebook utilization perplexity exp(-sum p_k log p_k) in [1, K]."""
flat = np.asarray(indices, dtype=np.int64).ravel()
if flat.size == 0:
return 1.0
counts = np.bincount(flat, minlength=num_codes).astype(np.float64)
probs = counts / np.sum(counts)
probs = probs[probs > 0.0]
return float(np.exp(-np.sum(probs * np.log(probs))))
class VQVAEBottleneck(nn.Module):
"""Vector-Quantized bottleneck with Straight-Through Estimator and optional EMA updates."""
def __init__(
self,
num_codes: int,
latent_dim: int,
commitment_beta: float = 0.25,
use_ema: bool = True,
ema_decay: float = 0.90,
dead_code_threshold: float = 1.0,
) -> None:
super().__init__()
self.num_codes = num_codes
self.latent_dim = latent_dim
self.commitment_beta = commitment_beta
self.use_ema = use_ema
self.ema_decay = ema_decay
self.dead_code_threshold = dead_code_threshold
# Wide initial codebook naturally induces index collapse unless EMA + dead-code reset is active.
init_emb = torch.randn(num_codes, latent_dim) * 1.4
self.embedding = nn.Parameter(init_emb, requires_grad=not use_ema)
self.register_buffer("ema_cluster_size", torch.zeros(num_codes))
self.register_buffer("ema_w", init_emb.clone())
def forward(
self, z_e: torch.Tensor
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
z_norm_sq = torch.sum(z_e.pow(2), dim=-1, keepdim=True)
e_norm_sq = torch.sum(self.embedding.pow(2), dim=-1).unsqueeze(0)
distances = z_norm_sq + e_norm_sq - 2.0 * torch.matmul(z_e, self.embedding.t())
indices = torch.argmin(distances, dim=-1)
z_q = F.embedding(indices, self.embedding)
if self.training and self.use_ema:
with torch.no_grad():
one_hot = F.one_hot(indices, num_classes=self.num_codes).to(z_e.dtype)
counts = one_hot.sum(dim=0)
dw = torch.matmul(one_hot.t(), z_e.detach())
ema_cluster_size: torch.Tensor = self.ema_cluster_size # type: ignore[assignment]
ema_w: torch.Tensor = self.ema_w # type: ignore[assignment]
ema_cluster_size.mul_(self.ema_decay).add_(counts, alpha=1.0 - self.ema_decay)
ema_w.mul_(self.ema_decay).add_(dw, alpha=1.0 - self.ema_decay)
n_total = ema_cluster_size.sum().clamp_min(1e-5)
smoothed = (
(ema_cluster_size + 1e-5)
/ (n_total + self.num_codes * 1e-5)
* n_total
)
self.embedding.data.copy_(ema_w / smoothed.unsqueeze(1).clamp_min(1e-5))
# Dead-code reset: teleport dormant codes to active encoder outputs
dead_ids = torch.nonzero(
ema_cluster_size < self.dead_code_threshold, as_tuple=False
).squeeze(-1)
if dead_ids.numel() > 0 and z_e.shape[0] > 0:
rand_idx = torch.randint(0, z_e.shape[0], (dead_ids.numel(),), device=z_e.device)
replacements = z_e.detach()[rand_idx] + 0.02 * torch.randn(
dead_ids.numel(), self.latent_dim, device=z_e.device
)
self.embedding.data[dead_ids] = replacements
ema_w[dead_ids] = replacements
ema_cluster_size[dead_ids] = max(self.dead_code_threshold, 1.0)
vq_loss = self.commitment_beta * F.mse_loss(z_e, z_q.detach())
else:
codebook_loss = F.mse_loss(z_q, z_e.detach())
commit_loss = self.commitment_beta * F.mse_loss(z_e, z_q.detach())
vq_loss = codebook_loss + commit_loss
z_ste = z_e + (z_q - z_e).detach()
return z_ste, vq_loss, indices, z_q
class _TabularVQVAE(nn.Module):
def __init__(self, cfg: VQVAEConfig) -> None:
super().__init__()
self.encoder = nn.Sequential(
nn.Linear(cfg.input_dim, 32),
nn.SiLU(),
nn.Linear(32, cfg.latent_dim),
)
self.bottleneck = VQVAEBottleneck(
num_codes=cfg.num_codes,
latent_dim=cfg.latent_dim,
commitment_beta=cfg.commitment_beta,
use_ema=cfg.use_ema,
ema_decay=cfg.ema_decay,
dead_code_threshold=cfg.dead_code_threshold,
)
self.decoder = nn.Sequential(
nn.Linear(cfg.latent_dim, 32),
nn.SiLU(),
nn.Linear(32, cfg.input_dim),
)
def forward(self, x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
z_e = self.encoder(x)
z_ste, vq_loss, indices, _ = self.bottleneck(z_e)
x_hat = self.decoder(z_ste)
return x_hat, vq_loss, indices, z_e
def _train_single_vqvae(x_t: torch.Tensor, cfg: VQVAEConfig) -> dict[str, Any]:
torch.manual_seed(cfg.seed)
model = _TabularVQVAE(cfg)
optimizer = torch.optim.Adam(model.parameters(), lr=cfg.lr)
batch_size = min(128, len(x_t))
ste_grad_norm = 0.0
for _ in range(cfg.epochs):
perm = torch.randperm(len(x_t))
for start in range(0, len(x_t), batch_size):
batch = x_t[perm[start : start + batch_size]]
optimizer.zero_grad()
x_hat, vq_loss, _, _ = model(batch)
loss = F.mse_loss(x_hat, batch) + vq_loss
loss.backward()
enc_grad = model.encoder[0].weight.grad
if enc_grad is not None:
ste_grad_norm = float(torch.linalg.vector_norm(enc_grad).item())
optimizer.step()
model.eval()
with torch.no_grad():
x_hat, _, indices, _ = model(x_t)
recon_mse = float(F.mse_loss(x_hat, x_t).item())
idx_np = indices.cpu().numpy()
ppl = compute_codebook_perplexity(idx_np, cfg.num_codes)
active_codes = int(np.unique(idx_np).size)
return {
"use_ema": cfg.use_ema,
"perplexity": ppl,
"active_codes": active_codes,
"num_codes": cfg.num_codes,
"recon_mse": recon_mse,
"ste_grad_norm": ste_grad_norm,
}
def train_vqvae_ema_vs_no_ema(
x_data: np.ndarray, cfg_ema: VQVAEConfig, cfg_no_ema: VQVAEConfig
) -> dict[str, Any]:
"""Contrast EMA + dead-code reset VQ-VAE against non-EMA codebook collapse."""
x_arr = np.asarray(x_data, dtype=np.float32)
x_std = (x_arr - x_arr.mean(axis=0, keepdims=True)) / np.maximum(
x_arr.std(axis=0, keepdims=True), 1e-6
)
x_t = torch.from_numpy(x_std)
ema_res = _train_single_vqvae(x_t, cfg_ema)
no_ema_res = _train_single_vqvae(x_t, cfg_no_ema)
return {
"ema": ema_res,
"no_ema": no_ema_res,
"perplexity_gain_ratio": float(ema_res["perplexity"]) / max(float(no_ema_res["perplexity"]), 1e-6),
}
# ---------------------------------------------------------------------------
# Tier 2: TorchSensorAE, Safe Serialization (safetensors), ONNX & ORT CPU Parity
# ---------------------------------------------------------------------------
class TorchSensorAE(nn.Module):
"""Symmetric PyTorch 2.x MLP Autoencoder for IoT sensor telemetry."""
def __init__(self, input_dim: int = 16, hidden_dim: int = 64, latent_dim: int = 6) -> None:
super().__init__()
self.input_dim = input_dim
self.hidden_dim = hidden_dim
self.latent_dim = latent_dim
self.fc1 = nn.Linear(input_dim, hidden_dim)
self.act1 = nn.SiLU()
self.fc2 = nn.Linear(hidden_dim, latent_dim)
self.fc3 = nn.Linear(latent_dim, hidden_dim)
self.act2 = nn.SiLU()
self.fc4 = nn.Linear(hidden_dim, input_dim)
def encode(self, x: torch.Tensor) -> torch.Tensor:
return self.fc2(self.act1(self.fc1(x)))
def decode(self, z: torch.Tensor) -> torch.Tensor:
return self.fc4(self.act2(self.fc3(z)))
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.decode(self.encode(x))
def save_state_dict_safetensors(model: nn.Module, path: Path) -> dict[str, Any]:
"""Serialize model tensors via safetensors and audit its 8-byte <Q + JSON binary layout."""
out_path = Path(path)
out_path.parent.mkdir(parents=True, exist_ok=True)
tensors = {k: v.detach().cpu().contiguous() for k, v in model.state_dict().items()}
safetensors_save_file(tensors, str(out_path), metadata={"format": "pt", "lab": "iot_ae_pdm_lab"})
raw = out_path.read_bytes()
if len(raw) < 10:
raise ValueError("Invalid safetensors payload: fewer than 10 bytes.")
hdr_len = int(struct.unpack("<Q", raw[:8])[0])
hdr_json = json.loads(raw[8 : 8 + hdr_len].decode("utf-8"))
tensor_keys = sorted(k for k in hdr_json if k != "__metadata__")
if tensor_keys != sorted(tensors.keys()):
raise ValueError("Safetensors header keys do not match model state_dict.")
return {
"path": str(out_path),
"file_bytes": len(raw),
"header_bytes": hdr_len,
"num_tensors": len(tensors),
"tensor_names": tensor_keys,
}
def load_state_dict_safetensors(model: nn.Module, path: Path) -> float:
"""Load safetensors weights into model and return max absolute tensor discrepancy."""
loaded = safetensors_load_file(str(path), device="cpu")
model.load_state_dict(loaded, strict=True)
current = model.state_dict()
max_diff = max(
float((current[k].detach().cpu() - loaded[k]).abs().max().item()) for k in loaded
)
return max_diff
def export_and_verify_onnx_parity(
model: nn.Module, sample_batch: torch.Tensor, onnx_path: Path
) -> dict[str, float]:
"""Export model via torch.onnx.export(..., dynamo=False), check ONNX, and verify ORT CPU parity."""
out_path = Path(onnx_path)
out_path.parent.mkdir(parents=True, exist_ok=True)
model_eval = model.eval()
batch_cpu = sample_batch.detach().cpu().to(torch.float32)
with warnings.catch_warnings():
warnings.simplefilter("ignore", DeprecationWarning)
torch.onnx.export(
model_eval,
(batch_cpu[:1],),
str(out_path),
dynamo=False,
input_names=["sensors"],
output_names=["recon"],
dynamic_axes={"sensors": {0: "batch"}, "recon": {0: "batch"}},
opset_version=17,
)
onnx_model = onnx.load(str(out_path))
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(str(out_path), sess_options=opts, providers=["CPUExecutionProvider"])
with torch.no_grad():
pt_out = model_eval(batch_cpu).numpy()
batch_np = batch_cpu.numpy()
ort_out = np.asarray(session.run(None, {"sensors": batch_np})[0], dtype=np.float32)
max_abs_diff = float(np.max(np.abs(pt_out - ort_out)))
if max_abs_diff >= 1e-4:
raise AssertionError(f"ONNX Runtime parity failed: max_abs_diff={max_abs_diff:.6e} >= 1e-4")
single_np = batch_np[:1]
for _ in range(15):
session.run(None, {"sensors": single_np})
latencies_ms: list[float] = []
for _ in range(60):
t0 = time.perf_counter()
session.run(None, {"sensors": single_np})
latencies_ms.append((time.perf_counter() - t0) * 1000.0)
return {
"onnx_bytes": float(out_path.stat().st_size),
"max_abs_diff": max_abs_diff,
"ort_latency_ms": float(np.median(latencies_ms)),
}
# ---------------------------------------------------------------------------
# Tier 2: Edge Compression (Pruning, FitNets + T_kd^2 KD, Symmetric INT8 PTQ)
# ---------------------------------------------------------------------------
def _count_linear_flops(model: TorchSensorAE) -> int:
return 2 * (
model.fc1.in_features * model.fc1.out_features
+ model.fc2.in_features * model.fc2.out_features
+ model.fc3.in_features * model.fc3.out_features
+ model.fc4.in_features * model.fc4.out_features
)
def unstructured_magnitude_prune_mask(model: nn.Module, sparsity: float = 0.80) -> dict[str, float]:
"""Apply unstructured magnitude pruning and measure dense buffer footprint (always 1.0x)."""
pruned = copy.deepcopy(model).cpu()
weights_2d = [p for p in pruned.parameters() if p.ndim == 2]
all_abs = torch.cat([w.detach().abs().flatten() for w in weights_2d])
threshold = float(torch.quantile(all_abs, sparsity).item())
zero_count = 0
total_2d = 0
with torch.no_grad():
for w in weights_2d:
mask = (w.abs() >= threshold).to(w.dtype)
w.mul_(mask)
zero_count += int((w == 0).sum().item())
total_2d += w.numel()
dense_bytes = float(sum(p.numel() * p.element_size() for p in pruned.parameters()))
return {
"target_sparsity": float(sparsity),
"actual_weight_sparsity": zero_count / max(total_2d, 1),
"original_fp32_bytes": dense_bytes,
"dense_buffer_bytes": dense_bytes,
"dense_compression_ratio": 1.0,
"dense_bytes_saved_pct": 0.0,
}
def structured_width_prune_ae(
teacher: TorchSensorAE, keep_ratio: float = 0.375
) -> tuple[TorchSensorAE, dict[str, float]]:
"""Physically slice hidden layer neurons by joint incoming/outgoing L2 norms."""
keep_hidden = max(4, int(round(teacher.hidden_dim * keep_ratio)))
with torch.no_grad():
enc_score = torch.linalg.vector_norm(teacher.fc1.weight, dim=1) + torch.linalg.vector_norm(
teacher.fc2.weight, dim=0
)
dec_score = torch.linalg.vector_norm(teacher.fc3.weight, dim=1) + torch.linalg.vector_norm(
teacher.fc4.weight, dim=0
)
enc_idx = torch.topk(enc_score, k=keep_hidden, largest=True).indices.sort().values
dec_idx = torch.topk(dec_score, k=keep_hidden, largest=True).indices.sort().values
student = TorchSensorAE(teacher.input_dim, keep_hidden, teacher.latent_dim)
student.fc1.weight.copy_(teacher.fc1.weight[enc_idx, :])
student.fc1.bias.copy_(teacher.fc1.bias[enc_idx])
student.fc2.weight.copy_(teacher.fc2.weight[:, enc_idx])
student.fc2.bias.copy_(teacher.fc2.bias)
student.fc3.weight.copy_(teacher.fc3.weight[dec_idx, :])
student.fc3.bias.copy_(teacher.fc3.bias[dec_idx])
student.fc4.weight.copy_(teacher.fc4.weight[:, dec_idx])
student.fc4.bias.copy_(teacher.fc4.bias)
t_params = sum(p.numel() for p in teacher.parameters())
s_params = sum(p.numel() for p in student.parameters())
t_bytes = float(t_params * 4)
s_bytes = float(s_params * 4)
t_flops = float(_count_linear_flops(teacher))
s_flops = float(_count_linear_flops(student))
return student.eval(), {
"teacher_hidden": float(teacher.hidden_dim),
"student_hidden": float(keep_hidden),
"teacher_params": float(t_params),
"student_params": float(s_params),
"param_compression_ratio": t_params / max(s_params, 1),
"memory_compression_ratio": t_bytes / max(s_bytes, 1.0),
"flop_compression_ratio": t_flops / max(s_flops, 1.0),
}
def distill_student_ae(
teacher: TorchSensorAE,
student: TorchSensorAE,
x_train: np.ndarray,
cfg: CompressionConfig,
epochs: int = 80,
) -> dict[str, float]:
"""Distill teacher knowledge into compact student via FitNets latent hint + T_kd^2 KL."""
torch.manual_seed(cfg.seed)
teacher_eval = teacher.eval()
x_t = torch.from_numpy(np.asarray(x_train, dtype=np.float32))
with torch.no_grad():
t_recon = teacher_eval(x_t)
t_latent = teacher_eval.encode(x_t)
teacher_mse = float(F.mse_loss(t_recon, x_t).item())
student.eval()
student_before_mse = float(F.mse_loss(student(x_t), x_t).item())
hint_proj = nn.Linear(student.latent_dim, teacher.latent_dim)
student.train()
optimizer = torch.optim.Adam(list(student.parameters()) + list(hint_proj.parameters()), lr=0.008)
t_kd = cfg.kd_temperature
for _ in range(epochs):
optimizer.zero_grad()
s_latent = student.encode(x_t)
s_recon = student.decode(s_latent)
hard_loss = F.mse_loss(s_recon, x_t)
soft_recon_loss = F.mse_loss(s_recon, t_recon)
hint_loss = F.mse_loss(hint_proj(s_latent), t_latent)
# Temperature-scaled per-sensor error distribution KL with T_kd^2 gradient compensation
t_err_logits = -((x_t - t_recon).pow(2)) / t_kd
s_err_logits = -((x_t - s_recon).pow(2)) / t_kd
kd_kl = (t_kd**2) * F.kl_div(
F.log_softmax(s_err_logits, dim=-1),
F.softmax(t_err_logits, dim=-1),
reduction="batchmean",
)
loss = (
(1.0 - cfg.kd_alpha) * hard_loss
+ cfg.kd_alpha * (0.65 * soft_recon_loss + 0.35 * hint_loss)
+ 0.05 * kd_kl
)
loss.backward()
optimizer.step()
student.eval()
with torch.no_grad():
s_latent_end = student.encode(x_t)
s_recon_end = student.decode(s_latent_end)
student_after_mse = float(F.mse_loss(s_recon_end, x_t).item())
hint_mse_end = float(F.mse_loss(hint_proj(s_latent_end), t_latent).item())
return {
"teacher_recon_mse": teacher_mse,
"student_before_kd_mse": student_before_mse,
"student_after_kd_mse": student_after_mse,
"latent_hint_mse": hint_mse_end,
"kd_temperature": float(t_kd),
}
def quantize_symmetric_int8_tensor(
arr: np.ndarray, clip_alpha: float
) -> tuple[np.ndarray, float, np.ndarray]:
"""Symmetric INT8 quantization in [-127, 127] with zero_point = 0."""
x = np.asarray(arr, dtype=np.float32)
scale = max(float(clip_alpha), 1e-8) / 127.0
q = np.clip(np.round(x / scale), -127, 127).astype(np.int8)
deq = (q.astype(np.float32) * scale).astype(np.float32)
return q, scale, deq
def calibrate_clipping_threshold(
arr: np.ndarray,
method: Literal["minmax", "percentile", "mse"],
percentile_q: float = 99.5,
) -> float:
"""Calibrate symmetric clipping bound alpha_clip for INT8 PTQ."""
abs_arr = np.abs(np.asarray(arr, dtype=np.float32))
max_val = float(np.max(abs_arr))
if max_val <= 1e-8:
return 1e-4
if method == "minmax":
return max_val
if method == "percentile":
return max(float(np.percentile(abs_arr, percentile_q)), 1e-6)
# Robust MSE-optimal clipping search on the operational bulk (excluding extreme >99.6% EMI spikes)
bulk_cap = float(np.percentile(abs_arr, 99.6))
arr_f = np.asarray(arr, dtype=np.float32)
arr_bulk = arr_f[abs_arr <= bulk_cap]
if arr_bulk.size == 0:
arr_bulk = arr_f
pct_grid = [float(np.percentile(abs_arr, q)) for q in np.linspace(90.0, 99.6, 35)]
lin_grid = [float(a) for a in np.linspace(0.25 * bulk_cap, bulk_cap, 35)]
candidates = sorted({max(c, 1e-6) for c in pct_grid + lin_grid})
best_alpha = bulk_cap
best_mse = float("inf")
for alpha in candidates:
_, _, deq = quantize_symmetric_int8_tensor(arr_bulk, alpha)
mse = float(np.mean((arr_bulk - deq) ** 2))
if mse < best_mse:
best_mse = mse
best_alpha = alpha
return best_alpha
def evaluate_int8_sqnr(
arr: np.ndarray, clip_alpha: float, normal_bound: float = 2.5
) -> dict[str, float]:
"""Compute normal-band SQNR (dB) and active integer bin count under symmetric INT8."""
x = np.asarray(arr, dtype=np.float32)
q, scale, deq = quantize_symmetric_int8_tensor(x, clip_alpha)
normal_mask = np.abs(x) <= normal_bound
if not np.any(normal_mask):
normal_mask = np.ones_like(x, dtype=bool)
active_bins = int(np.unique(q[normal_mask]).size)
sig_pow = float(np.mean(x[normal_mask] ** 2))
err_pow = float(np.mean((x[normal_mask] - deq[normal_mask]) ** 2)) + 1e-12
sqnr_db = 10.0 * float(np.log10(max(sig_pow, 1e-12) / err_pow))
return {
"clip_alpha": float(clip_alpha),
"step_size": float(scale),
"sqnr_db": sqnr_db,
"active_normal_bins": float(active_bins),
}
def _silu_np(x: np.ndarray) -> np.ndarray:
sig = 1.0 / (1.0 + np.exp(-np.clip(x, -30.0, 30.0)))
return (x * sig).astype(np.float32)
def compress_student_to_int8_bundle(
student: TorchSensorAE, calib_x: np.ndarray, cfg: CompressionConfig
) -> dict[str, Any]:
"""Quantize student linear weights & activations to INT8 and measure footprint & MSE."""
student_eval = student.eval()
x_cal = np.asarray(calib_x, dtype=np.float32)
fp32_weight_bytes = sum(p.numel() * 4 for p in student_eval.parameters())
int8_bundle_bytes = sum(
p.numel() * (1 if p.ndim == 2 else 4) + (4 if p.ndim == 2 else 0)
for p in student_eval.parameters()
)
compression_ratio = float(fp32_weight_bytes / max(int8_bundle_bytes, 1))
# Quantize weights symmetrically
q_weights: dict[str, dict[str, Any]] = {}
for name, layer in (
("fc1", student_eval.fc1),
("fc2", student_eval.fc2),
("fc3", student_eval.fc3),
("fc4", student_eval.fc4),
):
w_np = layer.weight.detach().cpu().numpy().astype(np.float32)
b_np = layer.bias.detach().cpu().numpy().astype(np.float32)
w_alpha = float(np.max(np.abs(w_np)))
q_w, w_scale, deq_w = quantize_symmetric_int8_tensor(w_np, w_alpha)
q_weights[name] = {
"q_weight": q_w,
"scale": w_scale,
"deq_weight": deq_w,
"bias": b_np,
}
# Calibrate activation clipping ranges on calibration batch
with torch.no_grad():
x_t = torch.from_numpy(x_cal)
h1_cal = student_eval.act1(student_eval.fc1(x_t)).numpy()
z_cal = student_eval.fc2(torch.from_numpy(h1_cal)).numpy()
h2_cal = student_eval.act2(student_eval.fc3(torch.from_numpy(z_cal))).numpy()
fp32_recon = student_eval(x_t).numpy()
alpha_in = calibrate_clipping_threshold(x_cal, cfg.quant_calibration, cfg.percentile_q)
alpha_h1 = calibrate_clipping_threshold(h1_cal, cfg.quant_calibration, cfg.percentile_q)
alpha_z = calibrate_clipping_threshold(z_cal, cfg.quant_calibration, cfg.percentile_q)
alpha_h2 = calibrate_clipping_threshold(h2_cal, cfg.quant_calibration, cfg.percentile_q)
def predict_int8_fn(x_in: np.ndarray) -> np.ndarray:
_, _, x_q = quantize_symmetric_int8_tensor(x_in, alpha_in)
pre1 = x_q @ q_weights["fc1"]["deq_weight"].T + q_weights["fc1"]["bias"]
_, _, h1_q = quantize_symmetric_int8_tensor(_silu_np(pre1), alpha_h1)
z_raw = h1_q @ q_weights["fc2"]["deq_weight"].T + q_weights["fc2"]["bias"]
_, _, z_q = quantize_symmetric_int8_tensor(z_raw, alpha_z)
pre2 = z_q @ q_weights["fc3"]["deq_weight"].T + q_weights["fc3"]["bias"]
_, _, h2_q = quantize_symmetric_int8_tensor(_silu_np(pre2), alpha_h2)
return (h2_q @ q_weights["fc4"]["deq_weight"].T + q_weights["fc4"]["bias"]).astype(np.float32)
int8_recon = predict_int8_fn(x_cal)
fp32_recon_mse = float(np.mean((fp32_recon - x_cal) ** 2))
int8_recon_mse = float(np.mean((int8_recon - x_cal) ** 2))
return {
"fp32_weight_bytes": int(fp32_weight_bytes),
"int8_bundle_bytes": int(int8_bundle_bytes),
"compression_ratio": compression_ratio,
"fp32_recon_mse": fp32_recon_mse,
"int8_recon_mse": int8_recon_mse,
"quant_mse_delta": abs(int8_recon_mse - fp32_recon_mse),
"activation_clip_alphas": {
"input": alpha_in,
"act1": alpha_h1,
"latent": alpha_z,
"act2": alpha_h2,
},
"predict_int8": predict_int8_fn,
}
"""Tier 2 Leakage-Proof 3-Stage IoT Predictive Maintenance Pipeline (Anomaly -> RUL -> RCA).
Covers:
1. C-MAPSS-style 16-sensor turbofan fleet simulation across 4 subsystems (Fan, HPC, Combustor, HPT)
and 3 physical fault modes with multi-regime operational shifts and per-engine manufacturing bias.
2. Strict Engine-ID GroupSplit (0 overlap) + causal early-cycle taring + train-only scaling vs
leaky random cycle-split contrast.
3. Stage 1: Healthy-Only AE anomaly detector, Platt probability calibration on disjoint D_cal,
ECE-10, PR-AUC/ROC-AUC, and asymmetric Bayes cost threshold t* = c_FP / (c_FP + c_FN).
4. Stage 2: Piece-wise linear RUL capping (RUL_max = 125) and official NASA PHM08 asymmetric score.
5. Stage 3: Variance-normalized Residual + Reverse-Mode Input Gradient RCA attribution (>= 85% Top-3).
6. Edge Compressed Student PdM (>= 3.0x byte compression, ORT CPU < 5 ms, preserved PR-AUC/RUL/RCA).
"""
from __future__ import annotations
import tempfile
from pathlib import Path
from typing import Any, Literal
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from pydantic import BaseModel, ConfigDict, Field
from sklearn.ensemble import HistGradientBoostingRegressor
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import average_precision_score, roc_auc_score
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from iot_ae_pdm_lab.autoencoders_and_compression import (
CompressionConfig,
DAEConfig,
LinearAEConfig,
SparseAEConfig,
TorchSensorAE,
VQVAEConfig,
calibrate_clipping_threshold,
compress_student_to_int8_bundle,
distill_student_ae,
evaluate_int8_sqnr,
export_and_verify_onnx_parity,
fit_denoising_ae_numpy,
fit_linear_ae_numpy,
load_state_dict_safetensors,
quantize_symmetric_int8_tensor,
save_state_dict_safetensors,
structured_width_prune_ae,
train_sparse_ae_comparison,
train_vae_collapse_vs_annealed,
train_vqvae_ema_vs_no_ema,
unstructured_magnitude_prune_mask,
)
# ---------------------------------------------------------------------------
# Physical Subsystem & Sensor Contract (16 Sensors across 4 Subsystems)
# ---------------------------------------------------------------------------
SUBSYSTEM_SENSOR_MAP: dict[str, tuple[str, ...]] = {
"Fan": ("s01_Nf", "s02_T24", "s03_NRf", "s04_BPR"),
"HPC": ("s05_T30", "s06_P30", "s07_Ps30", "s08_Nc"),
"Combustor": ("s09_phi", "s10_Wf", "s11_T35", "s12_Pcomb"),
"HPT": ("s13_T50", "s14_W31", "s15_W32", "s16_htBleed"),
}
ALL_SENSORS: tuple[str, ...] = tuple(
sensor for sensors in SUBSYSTEM_SENSOR_MAP.values() for sensor in sensors
)
SENSOR_TO_SUBSYSTEM: dict[str, str] = {
sensor: sub for sub, sensors in SUBSYSTEM_SENSOR_MAP.items() for sensor in sensors
}
FAULT_TO_SUBSYSTEM: dict[str, str] = {
"HPC_degradation": "HPC",
"Fan_imbalance": "Fan",
"Turbine_thermal_erosion": "HPT",
"Combustor_coking": "Combustor",
}
PRIMARY_FAULT_MODES: tuple[str, ...] = (
"HPC_degradation",
"Fan_imbalance",
"Turbine_thermal_erosion",
)
# ---------------------------------------------------------------------------
# Strict Pydantic v2 Configuration Contracts (ConfigDict(extra="forbid"))
# ---------------------------------------------------------------------------
class FleetSimConfig(BaseModel):
"""Configuration for C-MAPSS-like multi-regime turbofan fleet simulator."""
model_config = ConfigDict(extra="forbid")
n_train_engines: int = Field(default=30, ge=12)
n_cal_engines: int = Field(default=15, ge=6)
n_test_engines: int = Field(default=18, ge=8)
n_sensors: Literal[16] = 16
n_regimes: int = Field(default=3, ge=2)
min_life_cycles: int = Field(default=150, ge=140)
max_life_cycles: int = Field(default=220, ge=160)
rul_max: Literal[125] = 125
imminent_horizon: int = Field(default=30, ge=5)
healthy_rul_min: int = Field(default=65, ge=35)
seed: int = 42
class PdMCostConfig(BaseModel):
"""Asymmetric maintenance cost contract & Bayes optimal decision threshold."""
model_config = ConfigDict(extra="forbid")
cost_fp_usd: float = Field(default=800.0, gt=0.0)
cost_fn_usd: float = Field(default=50_000.0, gt=0.0)
rul_max: Literal[125] = 125
imminent_horizon: int = Field(default=30, ge=5)
@property
def bayes_threshold(self) -> float:
"""Exact Bayes cost-optimal probability cutoff c_FP / (c_FP + c_FN)."""
return float(self.cost_fp_usd / (self.cost_fp_usd + self.cost_fn_usd))
# ---------------------------------------------------------------------------
# Turbofan Fleet Simulation & Strict Engine-ID Splitting
# ---------------------------------------------------------------------------
def _build_fault_signature_vectors() -> dict[str, np.ndarray]:
"""Deterministic physical degradation directions per fault mode (+ mild coupling)."""
sigs: dict[str, np.ndarray] = {}
# Fan: s01..s04
fan = np.zeros(16, dtype=np.float64)
fan[0:4] = np.array([2.5, 2.2, 2.4, -2.3])
fan[4:6] = np.array([0.35, -0.30]) # mild secondary HPC coupling
sigs["Fan_imbalance"] = fan
# HPC: s05..s08
hpc = np.zeros(16, dtype=np.float64)
hpc[4:8] = np.array([2.6, -2.4, -2.5, 2.3])
hpc[12:14] = np.array([0.35, -0.25]) # mild secondary HPT coupling
sigs["HPC_degradation"] = hpc
# HPT: s13..s16
hpt = np.zeros(16, dtype=np.float64)
hpt[12:16] = np.array([2.6, -2.3, -2.4, 2.5])
hpt[8:10] = np.array([0.30, 0.35]) # mild secondary Combustor coupling
sigs["Turbine_thermal_erosion"] = hpt
return sigs
def simulate_turbofan_fleet(cfg: FleetSimConfig) -> dict[str, Any]:
"""Simulate multi-regime run-to-failure trajectories for a fleet of turbofan engines."""
rng = np.random.default_rng(cfg.seed)
total_engines = cfg.n_train_engines + cfg.n_cal_engines + cfg.n_test_engines
# Shared low-rank healthy operating manifold & gentle progressive wear direction below RUL_max
w_health = rng.normal(0.0, 0.55, size=(3, cfg.n_sensors))
w_wear = rng.normal(0.0, 0.35, size=(1, cfg.n_sensors))
regime_offsets = rng.normal(0.0, 2.8, size=(cfg.n_regimes, cfg.n_sensors))
regime_scales = rng.uniform(0.85, 1.25, size=(cfg.n_regimes, cfg.n_sensors))
fault_sigs = _build_fault_signature_vectors()
engine_ids_list: list[np.ndarray] = []
cycles_list: list[np.ndarray] = []
regimes_list: list[np.ndarray] = []
fault_modes_list: list[np.ndarray] = []
subsystems_list: list[np.ndarray] = []
rul_raw_list: list[np.ndarray] = []
rul_capped_list: list[np.ndarray] = []
imminent_list: list[np.ndarray] = []
sensors_list: list[np.ndarray] = []
for eid in range(total_engines):
life = int(rng.integers(cfg.min_life_cycles, cfg.max_life_cycles + 1))
fault_mode = PRIMARY_FAULT_MODES[eid % len(PRIMARY_FAULT_MODES)]
true_sub = FAULT_TO_SUBSYSTEM[fault_mode]
f_vec = fault_sigs[fault_mode]
# Unit-specific manufacturing baseline offset (exploited by leaky cycle splits)
eng_bias = rng.normal(0.0, 0.65, size=(1, cfg.n_sensors))
onset_rul = float(rng.uniform(52.0, min(62.0, float(cfg.healthy_rul_min) - 2.0)))
cycles = np.arange(1, life + 1, dtype=np.int64)
rul_raw = (life - cycles).astype(np.float64)
rul_capped = np.minimum(rul_raw, float(cfg.rul_max))
is_imminent = (rul_raw <= cfg.imminent_horizon).astype(np.int64)
op_regimes = rng.integers(0, cfg.n_regimes, size=life, dtype=np.int64)
# Smooth temporal operational load variation on 3D healthy manifold
t_norm = cycles[:, None] / float(life)
phase = rng.uniform(0.0, 2.0 * np.pi, size=(1, 3))
z_health = 0.65 * np.sin(2.0 * np.pi * t_norm * 2.0 + phase) + rng.normal(
0.0, 0.25, size=(life, 3)
)
healthy_signal = z_health @ w_health
# Subtle uniform early wear across [0, RUL_max] + sharp fault-mode escalation past onset_rul
early_wear_frac = np.clip((float(cfg.rul_max) - rul_raw) / float(cfg.rul_max), 0.0, 1.0)
early_wear = (1.15 * early_wear_frac)[:, None] * w_wear
wear_frac = np.clip((onset_rul - rul_raw) / max(onset_rul, 1.0), 0.0, 1.2)
deg_mag = (wear_frac**1.45)[:, None] * f_vec[None, :]
# Sensor noise
noise = rng.normal(0.0, 0.14, size=(life, cfg.n_sensors))
latent_plus_fault = eng_bias + healthy_signal + early_wear + deg_mag + noise
sensors = regime_offsets[op_regimes] + regime_scales[op_regimes] * latent_plus_fault
engine_ids_list.append(np.full(life, eid, dtype=np.int64))
cycles_list.append(cycles)
regimes_list.append(op_regimes)
fault_modes_list.append(np.full(life, fault_mode, dtype=object))
subsystems_list.append(np.full(life, true_sub, dtype=object))
rul_raw_list.append(rul_raw)
rul_capped_list.append(rul_capped)
imminent_list.append(is_imminent)
sensors_list.append(sensors.astype(np.float32))
return {
"engine_id": np.concatenate(engine_ids_list),
"cycle": np.concatenate(cycles_list),
"op_regime": np.concatenate(regimes_list),
"fault_mode": np.concatenate(fault_modes_list),
"true_subsystem": np.concatenate(subsystems_list),
"rul_raw": np.concatenate(rul_raw_list),
"rul_capped": np.concatenate(rul_capped_list),
"is_imminent": np.concatenate(imminent_list),
"sensors": np.vstack(sensors_list),
"sensor_names": ALL_SENSORS,
}
def _causal_tare_and_ema(
x_reg_std: np.ndarray, engine_ids: np.ndarray, tare_window: int = 15, ema_alpha: float = 0.35
) -> tuple[np.ndarray, np.ndarray]:
"""Apply strictly causal per-engine early-cycle taring and forward-only EMA smoothing."""
x_tared = np.zeros_like(x_reg_std, dtype=np.float32)
x_ema = np.zeros_like(x_reg_std, dtype=np.float32)
for eid in np.unique(engine_ids):
idx = np.flatnonzero(engine_ids == eid)
unit_x = x_reg_std[idx]
running_sum = np.zeros(unit_x.shape[1], dtype=np.float64)
ema_state = np.zeros(unit_x.shape[1], dtype=np.float64)
for pos, row in enumerate(unit_x):
if pos < tare_window:
running_sum += row
# Shrunk causal prefix baseline removes eng_bias while preserving t=0 signal
baseline = running_sum / float(pos + 1.5)
else:
baseline = running_sum / float(tare_window)
tared_row = row - baseline
x_tared[idx[pos]] = tared_row.astype(np.float32)
if pos == 0:
ema_state = tared_row.copy()
else:
ema_state = ema_alpha * tared_row + (1.0 - ema_alpha) * ema_state
x_ema[idx[pos]] = ema_state.astype(np.float32)
return x_tared, x_ema
def split_fleet_by_engine_id(fleet_data: dict[str, Any], cfg: FleetSimConfig) -> dict[str, Any]:
"""Perform strict Engine-ID GroupSplit (0 overlap) + train-healthy-only regime scaling."""
unique_eids = np.unique(fleet_data["engine_id"])
rng = np.random.default_rng(cfg.seed + 7)
shuffled_eids = rng.permutation(unique_eids)
n_tr = cfg.n_train_engines
n_cal = cfg.n_cal_engines
train_eids = set(shuffled_eids[:n_tr].tolist())
cal_eids = set(shuffled_eids[n_tr : n_tr + n_cal].tolist())
test_eids = set(shuffled_eids[n_tr + n_cal :].tolist())
if not (
train_eids.isdisjoint(cal_eids)
and train_eids.isdisjoint(test_eids)
and cal_eids.isdisjoint(test_eids)
):
raise RuntimeError("Engine-ID GroupSplit integrity check failed: overlap detected.")
eids = fleet_data["engine_id"]
masks = {
"train": np.isin(eids, list(train_eids)),
"cal": np.isin(eids, list(cal_eids)),
"test": np.isin(eids, list(test_eids)),
}
# Fit regime-conditioned z-score statistics STRICTLY on train healthy cycles
train_healthy_mask = masks["train"] & (fleet_data["rul_raw"] >= cfg.healthy_rul_min)
regime_stats: dict[int, tuple[np.ndarray, np.ndarray]] = {}
for r in range(cfg.n_regimes):
r_mask = train_healthy_mask & (fleet_data["op_regime"] == r)
if not np.any(r_mask):
r_mask = train_healthy_mask
sub_x = fleet_data["sensors"][r_mask].astype(np.float64)
mean_r = np.mean(sub_x, axis=0)
std_r = np.maximum(np.std(sub_x, axis=0), 1e-4)
regime_stats[r] = (mean_r, std_r)
def _transform_split(mask: np.ndarray) -> dict[str, Any]:
s_raw = fleet_data["sensors"][mask].astype(np.float64)
regs = fleet_data["op_regime"][mask]
x_reg_std = np.zeros_like(s_raw, dtype=np.float64)
for r, (m_r, std_r) in regime_stats.items():
r_idx = regs == r
if np.any(r_idx):
x_reg_std[r_idx] = (s_raw[r_idx] - m_r) / std_r
sub_eids = fleet_data["engine_id"][mask]
x_tared, x_ema = _causal_tare_and_ema(x_reg_std, sub_eids)
rul_raw = fleet_data["rul_raw"][mask]
return {
"engine_id": sub_eids,
"cycle": fleet_data["cycle"][mask],
"op_regime": regs,
"fault_mode": fleet_data["fault_mode"][mask],
"true_subsystem": fleet_data["true_subsystem"][mask],
"rul_raw": rul_raw,
"rul_capped": fleet_data["rul_capped"][mask],
"is_imminent": fleet_data["is_imminent"][mask],
"is_healthy": rul_raw >= cfg.healthy_rul_min,
"x_reg_std": x_reg_std.astype(np.float32),
"x_scaled": x_tared,
"x_causal_ema": x_ema,
}
return {
"train": _transform_split(masks["train"]),
"cal": _transform_split(masks["cal"]),
"test": _transform_split(masks["test"]),
"engine_sets": {
"train": sorted(train_eids),
"cal": sorted(cal_eids),
"test": sorted(test_eids),
},
"overlap_count": 0,
"regime_stats_fit_split": "train_healthy_only",
}
def _causal_ema_raw(
x_arr: np.ndarray, engine_ids: np.ndarray, ema_alpha: float = 0.35
) -> np.ndarray:
"""Compute forward-only per-engine EMA without taring eng_bias (for leaky cycle baseline)."""
out = np.zeros_like(x_arr, dtype=np.float32)
for eid in np.unique(engine_ids):
idx = np.flatnonzero(engine_ids == eid)
state = np.zeros(x_arr.shape[1], dtype=np.float64)
for pos, row in enumerate(x_arr[idx]):
state = row.astype(np.float64) if pos == 0 else ema_alpha * row + (1.0 - ema_alpha) * state
out[idx[pos]] = state.astype(np.float32)
return out
def run_leaky_cycle_split_contrast(
fleet_data: dict[str, Any], cfg: FleetSimConfig | None = None, seed: int = 42
) -> dict[str, float]:
"""Contrast random cycle-split (Class 3+4 leakage) against honest Engine-ID GroupSplit."""
sim_cfg = cfg or FleetSimConfig(seed=seed)
split_data = split_fleet_by_engine_id(fleet_data, sim_cfg)
# Compute untared EMA features on train+cal pool so leaky cycle split exploits both
# per-engine manufacturing bias (eng_bias) and adjacent-cycle temporal smoothness.
x_pool_raw = np.vstack([split_data["train"]["x_reg_std"], split_data["cal"]["x_reg_std"]])
eids_pool = np.concatenate([split_data["train"]["engine_id"], split_data["cal"]["engine_id"]])
x_pool_ema = _causal_ema_raw(x_pool_raw, eids_pool)
y_pool = np.concatenate([split_data["train"]["rul_capped"], split_data["cal"]["rul_capped"]])
# Class 3 leakage: fit scaler across entire pool before splitting
leaky_scaler = StandardScaler().fit(x_pool_ema)
x_pool_scaled = leaky_scaler.transform(x_pool_ema)
# Class 4 leakage: random cycle split shares same engine_id across train & test!
x_tr_l, x_te_l, y_tr_l, y_te_l, eid_tr_l, eid_te_l = train_test_split(
x_pool_scaled,
y_pool,
eids_pool,
test_size=0.30,
random_state=seed,
)
leaky_overlap = len(set(eid_tr_l.tolist()) & set(eid_te_l.tolist()))
leaky_reg = HistGradientBoostingRegressor(max_iter=180, max_depth=8, random_state=seed)
leaky_reg.fit(x_tr_l, y_tr_l)
pred_leaky_offline = leaky_reg.predict(x_te_l)
leaky_cycle_rmse = float(np.sqrt(np.mean((y_te_l - pred_leaky_offline) ** 2)))
x_unseen_ema = _causal_ema_raw(split_data["test"]["x_reg_std"], split_data["test"]["engine_id"])
x_unseen = leaky_scaler.transform(x_unseen_ema)
y_unseen = split_data["test"]["rul_capped"]
pred_leaky_live = leaky_reg.predict(x_unseen)
leaky_live_unseen_rmse = float(np.sqrt(np.mean((y_unseen - pred_leaky_live) ** 2)))
# Honest Engine-ID GroupSplit on causally tared + train-standardized features
honest_reg = HistGradientBoostingRegressor(max_iter=120, max_depth=6, random_state=seed)
honest_reg.fit(split_data["train"]["x_causal_ema"], split_data["train"]["rul_capped"])
pred_honest = honest_reg.predict(split_data["test"]["x_causal_ema"])
honest_engine_rmse = float(
np.sqrt(np.mean((split_data["test"]["rul_capped"] - pred_honest) ** 2))
)
return {
"leaky_shared_engine_count": float(leaky_overlap),
"honest_shared_engine_count": 0.0,
"leaky_cycle_rmse": leaky_cycle_rmse,
"leaky_live_unseen_rmse": leaky_live_unseen_rmse,
"honest_engine_rmse": honest_engine_rmse,
"offline_illusions_gap_rmse": honest_engine_rmse - leaky_cycle_rmse,
}
# ---------------------------------------------------------------------------
# Stage 1: Healthy-Only AE Anomaly Detection, Calibration & Bayes Decision
# ---------------------------------------------------------------------------
def compute_pr_roc_auc(y_true: np.ndarray, y_score: np.ndarray) -> dict[str, float]:
"""Compute PR-AUC and ROC-AUC safely."""
yt = np.asarray(y_true, dtype=np.int64)
ys = np.asarray(y_score, dtype=np.float64)
return {
"pr_auc": float(average_precision_score(yt, ys)),
"roc_auc": float(roc_auc_score(yt, ys)),
}
def compute_ece(y_true: np.ndarray, y_prob: np.ndarray, n_bins: int = 10) -> float:
"""Compute Expected Calibration Error (ECE-10) over uniform probability bins."""
yt = np.asarray(y_true, dtype=np.float64)
yp = np.clip(np.asarray(y_prob, dtype=np.float64), 0.0, 1.0)
edges = np.linspace(0.0, 1.0, n_bins + 1)
ece = 0.0
n = float(len(yt))
for i in range(n_bins):
lo, hi = edges[i], edges[i + 1]
in_bin = (yp >= lo) & (yp <= hi if i == n_bins - 1 else yp < hi)
if np.any(in_bin):
acc = float(np.mean(yt[in_bin]))
conf = float(np.mean(yp[in_bin]))
ece += (float(np.sum(in_bin)) / n) * abs(acc - conf)
return float(ece)
def score_anomaly_ae(
ae_model: TorchSensorAE, x_scaled: np.ndarray, healthy_err_std: np.ndarray
) -> np.ndarray:
"""Compute normalized per-sample reconstruction anomaly score."""
ae_model.eval()
x_t = torch.from_numpy(np.asarray(x_scaled, dtype=np.float32))
with torch.no_grad():
x_hat = ae_model(x_t).numpy()
norm_res = (x_scaled - x_hat) / np.maximum(healthy_err_std[None, :], 1e-4)
return np.mean(norm_res**2, axis=1).astype(np.float64)
def fit_stage1_healthy_detector(
split_data: dict[str, Any],
latent_dim: int = 6,
hidden_dim: int = 64,
epochs: int = 60,
seed: int = 42,
) -> dict[str, Any]:
"""Train a Healthy-Only AE strictly on healthy training cycles (rul_raw >= healthy_rul_min)."""
tr = split_data["train"]
x_healthy = tr["x_scaled"][tr["is_healthy"]]
torch.manual_seed(seed)
model = TorchSensorAE(input_dim=x_healthy.shape[1], hidden_dim=hidden_dim, latent_dim=latent_dim)
optimizer = torch.optim.Adam(model.parameters(), lr=0.004)
x_t = torch.from_numpy(x_healthy.astype(np.float32))
batch_size = min(128, len(x_t))
for _ in range(epochs):
perm = torch.randperm(len(x_t))
for start in range(0, len(x_t), batch_size):
batch = x_t[perm[start : start + batch_size]]
optimizer.zero_grad()
recon = model(batch)
loss = F.mse_loss(recon, batch)
loss.backward()
optimizer.step()
model.eval()
with torch.no_grad():
recon_h = model(x_t).numpy()
err_h = x_healthy - recon_h
healthy_err_std = np.maximum(np.std(err_h, axis=0), 0.08).astype(np.float32)
train_scores = score_anomaly_ae(model, x_healthy, healthy_err_std)
return {
"model": model,
"healthy_err_std": healthy_err_std,
"train_healthy_scores": train_scores,
"train_healthy_mean": float(np.mean(train_scores)),
"train_healthy_std": float(np.std(train_scores)),
}
def _eval_threshold_policy(
y_true: np.ndarray, y_pred: np.ndarray, cost_cfg: PdMCostConfig
) -> dict[str, float]:
yt = np.asarray(y_true, dtype=np.int64)
yp = np.asarray(y_pred, dtype=np.int64)
fp = int(np.sum((yt == 0) & (yp == 1)))
fn = int(np.sum((yt == 1) & (yp == 0)))
tp = int(np.sum((yt == 1) & (yp == 1)))
tn = int(np.sum((yt == 0) & (yp == 0)))
total_cost = float(fp * cost_cfg.cost_fp_usd + fn * cost_cfg.cost_fn_usd)
return {
"fp": float(fp),
"fn": float(fn),
"tp": float(tp),
"tn": float(tn),
"total_cost_usd": total_cost,
"mean_cost_per_cycle_usd": total_cost / max(len(yt), 1),
}
def calibrate_and_threshold_bayes(
detector: dict[str, Any], split_data: dict[str, Any], cost_cfg: PdMCostConfig
) -> dict[str, Any]:
"""Fit Platt scaling on disjoint D_cal engines and compare 3*std, p=0.50, and Bayes t*."""
model: TorchSensorAE = detector["model"]
h_std: np.ndarray = detector["healthy_err_std"]
cal = split_data["cal"]
test = split_data["test"]
s_cal = score_anomaly_ae(model, cal["x_scaled"], h_std)
s_test = score_anomaly_ae(model, test["x_scaled"], h_std)
y_cal = cal["is_imminent"].astype(np.int64)
y_test = test["is_imminent"].astype(np.int64)
# Fit Platt logistic calibration strictly on disjoint calibration engines
cal_feat = np.log1p(np.maximum(s_cal, 0.0)).reshape(-1, 1)
test_feat = np.log1p(np.maximum(s_test, 0.0)).reshape(-1, 1)
platt = LogisticRegression(C=10.0)
platt.fit(cal_feat, y_cal)
p_test = platt.predict_proba(test_feat)[:, 1]
auc_metrics = compute_pr_roc_auc(y_test, s_test)
ece_10 = compute_ece(y_test, p_test, n_bins=10)
naive_cutoff_score = detector["train_healthy_mean"] + 3.0 * detector["train_healthy_std"]
pred_naive_3std = (s_test >= naive_cutoff_score).astype(np.int64)
pred_sym_p50 = (p_test >= 0.50).astype(np.int64)
pred_bayes = (p_test >= cost_cfg.bayes_threshold).astype(np.int64)
res_3std = _eval_threshold_policy(y_test, pred_naive_3std, cost_cfg)
res_p50 = _eval_threshold_policy(y_test, pred_sym_p50, cost_cfg)
res_bayes = _eval_threshold_policy(y_test, pred_bayes, cost_cfg)
cost_vs_3std_cut_pct = (
100.0
* (res_3std["total_cost_usd"] - res_bayes["total_cost_usd"])
/ max(res_3std["total_cost_usd"], 1.0)
)
cost_vs_p50_cut_pct = (
100.0
* (res_p50["total_cost_usd"] - res_bayes["total_cost_usd"])
/ max(res_p50["total_cost_usd"], 1.0)
)
return {
"pr_auc": auc_metrics["pr_auc"],
"roc_auc": auc_metrics["roc_auc"],
"ece_10": ece_10,
"bayes_threshold": cost_cfg.bayes_threshold,
"naive_3std_score_cutoff": float(naive_cutoff_score),
"policies": {
"naive_3std": res_3std,
"symmetric_p50": res_p50,
"bayes_optimal": res_bayes,
},
"bayes_cost_reduction_vs_3std_pct": float(cost_vs_3std_cut_pct),
"bayes_cost_reduction_vs_p50_pct": float(cost_vs_p50_cut_pct),
"platt_calibrator": platt,
"test_scores": s_test,
"test_probs": p_test,
}
# ---------------------------------------------------------------------------
# Stage 2: Piece-Wise Linear RUL (RUL_max = 125) & NASA PHM08 Score
# ---------------------------------------------------------------------------
def cap_rul_targets(rul_raw: np.ndarray, rul_max: int = 125) -> np.ndarray:
"""Apply C-MAPSS piece-wise linear ceiling RUL = min(RUL_raw, RUL_max)."""
return np.minimum(np.asarray(rul_raw, dtype=np.float64), float(rul_max))
def nasa_phm08_score(y_true: np.ndarray, y_pred: np.ndarray) -> float:
"""Official NASA PHM08 asymmetric RUL scoring function:
d_i = y_pred_i - y_true_i
s_i = exp(-d_i / 13) - 1 if d_i < 0 (early prediction)
= exp(+d_i / 10) - 1 if d_i >= 0 (late prediction — penalized harsher)
"""
yt = np.asarray(y_true, dtype=np.float64)
yp = np.asarray(y_pred, dtype=np.float64)
d = yp - yt
terms = np.where(
d < 0.0,
np.exp(np.clip(-d / 13.0, -50.0, 40.0)) - 1.0,
np.exp(np.clip(d / 10.0, -50.0, 40.0)) - 1.0,
)
return float(np.sum(terms))
class TorchRULRegressor(nn.Module):
"""Compact PyTorch 2.x MLP for edge-deployable RUL prediction."""
def __init__(self, input_dim: int = 16, hidden_dim: int = 64) -> None:
super().__init__()
self.input_dim = input_dim
self.hidden_dim = hidden_dim
self.fc1 = nn.Linear(input_dim, hidden_dim)
self.act1 = nn.SiLU()
self.fc2 = nn.Linear(hidden_dim, hidden_dim // 2)
self.act2 = nn.SiLU()
self.fc3 = nn.Linear(hidden_dim // 2, 1)
def forward(self, x: torch.Tensor) -> torch.Tensor:
h = self.act1(self.fc1(x))
h = self.act2(self.fc2(h))
return F.relu(self.fc3(h)).squeeze(-1)
def _train_rul_mlp(
x_tr: np.ndarray, y_tr: np.ndarray, hidden_dim: int = 64, epochs: int = 80, seed: int = 42
) -> TorchRULRegressor:
torch.manual_seed(seed)
model = TorchRULRegressor(input_dim=x_tr.shape[1], hidden_dim=hidden_dim)
optimizer = torch.optim.Adam(model.parameters(), lr=0.006, weight_decay=1e-4)
x_t = torch.from_numpy(x_tr.astype(np.float32))
y_t = torch.from_numpy(y_tr.astype(np.float32))
batch_size = min(128, len(x_t))
for _ in range(epochs):
perm = torch.randperm(len(x_t))
for start in range(0, len(x_t), batch_size):
idx = perm[start : start + batch_size]
optimizer.zero_grad()
pred = model(x_t[idx])
# Smooth MSE + mild late-prediction asymmetric nudge matching PHM08 safety
err = pred - y_t[idx]
asym_w = torch.where(err > 0.0, 1.35, 1.0)
loss = torch.mean(asym_w * err.pow(2))
loss.backward()
optimizer.step()
return model.eval()
def fit_stage2_rul_predictor(
split_data: dict[str, Any],
rul_max: int = 125,
hidden_dim: int = 64,
epochs: int = 80,
seed: int = 42,
) -> dict[str, Any]:
"""Train Stage 2 RUL predictor with capped RUL_max=125 and contrast against uncapped targets."""
tr = split_data["train"]
te = split_data["test"]
y_tr_cap = cap_rul_targets(tr["rul_raw"], rul_max=rul_max)
y_te_cap = cap_rul_targets(te["rul_raw"], rul_max=rul_max)
capped_model = _train_rul_mlp(
tr["x_causal_ema"], y_tr_cap, hidden_dim=hidden_dim, epochs=epochs, seed=seed
)
uncapped_model = _train_rul_mlp(
tr["x_causal_ema"], tr["rul_raw"], hidden_dim=hidden_dim, epochs=epochs, seed=seed + 1
)
x_te_t = torch.from_numpy(te["x_causal_ema"].astype(np.float32))
with torch.no_grad():
pred_cap = np.clip(capped_model(x_te_t).numpy(), 0.0, float(rul_max))
pred_uncap = np.clip(uncapped_model(x_te_t).numpy(), 0.0, float(rul_max))
late_mask = te["rul_raw"] <= 50.0
test_rul_rmse = float(np.sqrt(np.mean((y_te_cap - pred_cap) ** 2)))
late_life_rmse = float(np.sqrt(np.mean((y_te_cap[late_mask] - pred_cap[late_mask]) ** 2)))
phm08_total = nasa_phm08_score(y_te_cap, pred_cap)
uncap_late_rmse = float(np.sqrt(np.mean((y_te_cap[late_mask] - pred_uncap[late_mask]) ** 2)))
uncap_phm08_total = nasa_phm08_score(y_te_cap, pred_uncap)
return {
"model": capped_model,
"rul_max": rul_max,
"test_rul_rmse": test_rul_rmse,
"late_life_rmse": late_life_rmse,
"phm08_score": phm08_total,
"mean_phm08_per_cycle": phm08_total / max(len(y_te_cap), 1),
"uncapped_late_life_rmse": uncap_late_rmse,
"uncapped_phm08_score": uncap_phm08_total,
"test_predictions": pred_cap,
}
# ---------------------------------------------------------------------------
# Stage 3: Root Cause Analysis (Per-Sensor Residual + Reverse-Mode Gradient)
# ---------------------------------------------------------------------------
def compute_rca_sensor_attribution(
ae_model: TorchSensorAE, x_scaled: np.ndarray, healthy_err_std: np.ndarray
) -> dict[str, np.ndarray]:
"""Combine variance-normalized residual energy and input gradient sensitivity for RCA."""
ae_model.eval()
x_t = torch.tensor(x_scaled, dtype=torch.float32, requires_grad=True)
std_t = torch.tensor(healthy_err_std, dtype=torch.float32).clamp_min(1e-4)
x_hat = ae_model(x_t)
res_norm = ((x_t - x_hat) / std_t.unsqueeze(0)).pow(2)
s_anom = res_norm.mean(dim=-1).sum()
grad_x = torch.autograd.grad(s_anom, x_t)[0]
grad_attr = (grad_x * x_t).abs()
res_np = res_norm.detach().cpu().numpy().astype(np.float64)
grad_np = grad_attr.detach().cpu().numpy().astype(np.float64)
res_share = res_np / np.maximum(np.sum(res_np, axis=1, keepdims=True), 1e-8)
grad_share = grad_np / np.maximum(np.sum(grad_np, axis=1, keepdims=True), 1e-8)
combined = 0.65 * res_share + 0.35 * grad_share
return {
"residual_attr": res_np,
"grad_attr": grad_np,
"combined_attr": combined,
}
def evaluate_rca_subsystem_hit_rate(
attr_scores: np.ndarray,
true_subsystems: np.ndarray,
fault_modes: np.ndarray,
is_imminent: np.ndarray,
) -> dict[str, Any]:
"""Evaluate Top-3 Sensor Subsystem Hit Rate & Top-1 Subsystem Accuracy on faulted cycles."""
fault_idx = np.flatnonzero(is_imminent == 1)
if fault_idx.size == 0:
raise ValueError("No faulted (is_imminent == 1) samples provided for RCA evaluation.")
sensor_sub_list = [SENSOR_TO_SUBSYSTEM[s] for s in ALL_SENSORS]
sub_names = list(SUBSYSTEM_SENSOR_MAP.keys())
sub_sensor_indices = {
sub: [i for i, s_sub in enumerate(sensor_sub_list) if s_sub == sub] for sub in sub_names
}
top3_hits = 0
top1_sub_hits = 0
by_mode: dict[str, dict[str, Any]] = {}
for mode in np.unique(fault_modes[fault_idx]):
m_str = str(mode)
m_indices = fault_idx[fault_modes[fault_idx] == mode]
m_top3_hits = 0
m_top1_hits = 0
sensor_freq = np.zeros(len(ALL_SENSORS), dtype=np.int64)
for idx in m_indices:
scores = attr_scores[idx]
top3 = np.argsort(scores)[::-1][:3]
for s_i in top3:
sensor_freq[s_i] += 1
true_sub = str(true_subsystems[idx])
if any(sensor_sub_list[s_i] == true_sub for s_i in top3):
top3_hits += 1
m_top3_hits += 1
sub_sums = {sub: float(np.sum(scores[idxs])) for sub, idxs in sub_sensor_indices.items()}
pred_sub = max(sub_sums, key=lambda k: sub_sums[k])
if pred_sub == true_sub:
top1_sub_hits += 1
m_top1_hits += 1
top3_common = [ALL_SENSORS[int(i)] for i in np.argsort(sensor_freq)[::-1][:3]]
by_mode[m_str] = {
"target_subsystem": FAULT_TO_SUBSYSTEM.get(m_str, str(true_subsystems[m_indices[0]])),
"n_cycles": int(m_indices.size),
"top_3_rca_hit_rate": float(m_top3_hits / m_indices.size),
"top_1_subsystem_acc": float(m_top1_hits / m_indices.size),
"top_3_sensors": top3_common,
}
return {
"n_faulted_cycles": int(fault_idx.size),
"top_3_rca_hit_rate": float(top3_hits / fault_idx.size),
"top_1_subsystem_acc": float(top1_sub_hits / fault_idx.size),
"by_fault_mode": by_mode,
}
# ---------------------------------------------------------------------------
# Edge Compression of End-to-End 3-Stage PdM Student (Pruning + KD + INT8 + ORT)
# ---------------------------------------------------------------------------
def _structured_prune_rul_net(teacher: TorchRULRegressor, keep_ratio: float) -> TorchRULRegressor:
keep_h1 = max(8, int(round(teacher.hidden_dim * keep_ratio)))
keep_h2 = max(4, keep_h1 // 2)
with torch.no_grad():
s1 = torch.linalg.vector_norm(teacher.fc1.weight, dim=1) + torch.linalg.vector_norm(
teacher.fc2.weight, dim=0
)
idx1 = torch.topk(s1, k=keep_h1, largest=True).indices.sort().values
s2 = torch.linalg.vector_norm(teacher.fc2.weight[:, idx1], dim=1) + torch.linalg.vector_norm(
teacher.fc3.weight, dim=0
)
idx2 = torch.topk(s2, k=keep_h2, largest=True).indices.sort().values
student = TorchRULRegressor(teacher.input_dim, keep_h1)
student.fc1.weight.copy_(teacher.fc1.weight[idx1, :])
student.fc1.bias.copy_(teacher.fc1.bias[idx1])
student.fc2.weight.copy_(teacher.fc2.weight[idx2, :][:, idx1])
student.fc2.bias.copy_(teacher.fc2.bias[idx2])
student.fc3.weight.copy_(teacher.fc3.weight[:, idx2])
student.fc3.bias.copy_(teacher.fc3.bias)
return student.eval()
def compress_and_evaluate_edge_pdm(
stage1_detector: dict[str, Any],
stage2_rul: dict[str, Any],
stage1_eval: dict[str, Any],
split_data: dict[str, Any],
cfg: CompressionConfig,
epochs: int = 50,
) -> dict[str, Any]:
"""Compress Stage 1 AE & Stage 2 RUL via width pruning + KD + INT8 PTQ and validate on test."""
teacher_ae: TorchSensorAE = stage1_detector["model"]
teacher_rul: TorchRULRegressor = stage2_rul["model"]
h_std: np.ndarray = stage1_detector["healthy_err_std"]
tr = split_data["train"]
cal = split_data["cal"]
te = split_data["test"]
keep_ratio = 1.0 - cfg.prune_ratio
student_ae, ae_prune_stats = structured_width_prune_ae(teacher_ae, keep_ratio=keep_ratio)
distill_student_ae(teacher_ae, student_ae, tr["x_scaled"][tr["is_healthy"]], cfg, epochs=epochs)
int8_ae_bundle = compress_student_to_int8_bundle(student_ae, cal["x_scaled"], cfg)
# Distill Stage 2 RUL student via mini-batch KD
student_rul = _structured_prune_rul_net(teacher_rul, keep_ratio=keep_ratio)
x_tr_ema = torch.from_numpy(tr["x_causal_ema"].astype(np.float32))
y_cap_arr = cap_rul_targets(tr["rul_raw"], rul_max=stage2_rul["rul_max"]).astype(np.float32)
y_tr_cap = torch.from_numpy(y_cap_arr)
with torch.no_grad():
t_rul_soft = teacher_rul(x_tr_ema)
opt = torch.optim.Adam(student_rul.parameters(), lr=0.008)
batch_size = min(128, len(x_tr_ema))
student_rul.train()
for _ in range(epochs):
perm = torch.randperm(len(x_tr_ema))
for start in range(0, len(x_tr_ema), batch_size):
idx = perm[start : start + batch_size]
opt.zero_grad()
s_pred = student_rul(x_tr_ema[idx])
loss = 0.5 * F.mse_loss(s_pred, y_tr_cap[idx]) + 0.5 * F.mse_loss(
s_pred, t_rul_soft[idx]
)
loss.backward()
opt.step()
student_rul.eval()
# Quantize Stage 2 student RUL weights to symmetric INT8
rul_fp32_bytes = sum(p.numel() * 4 for p in student_rul.parameters())
rul_int8_bytes = sum(
p.numel() * (1 if p.ndim == 2 else 4) + (4 if p.ndim == 2 else 0)
for p in student_rul.parameters()
)
q_rul_weights: dict[str, tuple[np.ndarray, np.ndarray]] = {}
for lname, layer in (("fc1", student_rul.fc1), ("fc2", student_rul.fc2), ("fc3", student_rul.fc3)):
w_np = layer.weight.detach().cpu().numpy().astype(np.float32)
b_np = layer.bias.detach().cpu().numpy().astype(np.float32)
_, _, deq_w = quantize_symmetric_int8_tensor(w_np, float(np.max(np.abs(w_np))))
q_rul_weights[lname] = (deq_w, b_np)
def _silu(arr: np.ndarray) -> np.ndarray:
return arr * (1.0 / (1.0 + np.exp(-np.clip(arr, -30.0, 30.0))))
def _predict_rul_int8(x_in: np.ndarray) -> np.ndarray:
w1, b1 = q_rul_weights["fc1"]
w2, b2 = q_rul_weights["fc2"]
w3, b3 = q_rul_weights["fc3"]
h1 = _silu(x_in @ w1.T + b1)
h2 = _silu(h1 @ w2.T + b2)
out = np.maximum(0.0, (h2 @ w3.T + b3).squeeze(-1))
return np.clip(out, 0.0, float(stage2_rul["rul_max"]))
# Evaluate compressed INT8 student on unseen test engines
x_te_scaled = te["x_scaled"]
int8_recon_te = int8_ae_bundle["predict_int8"](x_te_scaled)
norm_res_int8 = (x_te_scaled - int8_recon_te) / np.maximum(h_std[None, :], 1e-4)
s_test_int8 = np.mean(norm_res_int8**2, axis=1)
int8_pr_auc = float(average_precision_score(te["is_imminent"], s_test_int8))
pred_rul_int8 = _predict_rul_int8(te["x_causal_ema"])
y_te_cap = cap_rul_targets(te["rul_raw"], rul_max=stage2_rul["rul_max"])
int8_rul_rmse = float(np.sqrt(np.mean((y_te_cap - pred_rul_int8) ** 2)))
# Stage 3 RCA on compressed student AE (using quantized recon residual + student grad)
s_attr = compute_rca_sensor_attribution(student_ae, x_te_scaled, h_std)
res_int8_share = norm_res_int8**2 / np.maximum(np.sum(norm_res_int8**2, axis=1, keepdims=True), 1e-8)
grad_share = s_attr["grad_attr"] / np.maximum(np.sum(s_attr["grad_attr"], axis=1, keepdims=True), 1e-8)
int8_rca_eval = evaluate_rca_subsystem_hit_rate(
0.65 * res_int8_share + 0.35 * grad_share,
te["true_subsystem"],
te["fault_mode"],
te["is_imminent"],
)
with tempfile.TemporaryDirectory() as tmp_dir:
onnx_res = export_and_verify_onnx_parity(
student_ae,
torch.from_numpy(x_te_scaled[:16].astype(np.float32)),
Path(tmp_dir) / "edge_student_ae.onnx",
)
teacher_total_fp32_bytes = sum(p.numel() * 4 for p in teacher_ae.parameters()) + sum(
p.numel() * 4 for p in teacher_rul.parameters()
)
student_total_fp32_bytes = int(int8_ae_bundle["fp32_weight_bytes"]) + int(rul_fp32_bytes)
student_total_int8_bytes = int(int8_ae_bundle["int8_bundle_bytes"]) + int(rul_int8_bytes)
return {
"teacher_total_fp32_bytes": int(teacher_total_fp32_bytes),
"student_total_fp32_bytes": int(student_total_fp32_bytes),
"student_total_int8_bytes": int(student_total_int8_bytes),
"int8_compression_ratio": float(student_total_fp32_bytes / max(student_total_int8_bytes, 1)),
"total_compression_ratio": float(teacher_total_fp32_bytes / max(student_total_int8_bytes, 1)),
"ae_prune_param_ratio": ae_prune_stats["param_compression_ratio"],
"teacher_pr_auc": float(stage1_eval["pr_auc"]),
"int8_pr_auc": int8_pr_auc,
"pr_auc_drop": float(stage1_eval["pr_auc"] - int8_pr_auc),
"teacher_rul_rmse": float(stage2_rul["test_rul_rmse"]),
"int8_rul_rmse": int8_rul_rmse,
"rul_rmse_delta": float(int8_rul_rmse - stage2_rul["test_rul_rmse"]),
"int8_top_3_rca_hit_rate": float(int8_rca_eval["top_3_rca_hit_rate"]),
"ort_latency_ms": float(onnx_res["ort_latency_ms"]),
"ort_max_abs_diff": float(onnx_res["max_abs_diff"]),
}
# ---------------------------------------------------------------------------
# Master Benchmark Suite + Workbench Panels Builder
# ---------------------------------------------------------------------------
def _build_synthetic_manifold_data(n_samples: int, input_dim: int, seed: int) -> np.ndarray:
"""Create structured multi-factor manifold data with a clear spectral gap."""
rng = np.random.default_rng(seed)
latent_true = 4
factors = rng.normal(0.0, 1.0, size=(n_samples, latent_true))
basis = rng.normal(0.0, 1.0, size=(latent_true, input_dim))
scales = np.array([2.4, 1.8, 1.3, 0.95])[:, None]
x_clean = factors @ (scales * basis)
return (x_clean + rng.normal(0.0, 0.10, size=(n_samples, input_dim))).astype(np.float64)
def _build_sparse_dictionary_data(n_samples: int, input_dim: int, seed: int) -> np.ndarray:
"""Create non-negative sparse superposition telemetry for Sparse AE benchmarking."""
rng = np.random.default_rng(seed)
n_atoms = 24
atoms = rng.normal(0.0, 1.0, size=(n_atoms, input_dim))
atoms /= np.maximum(np.linalg.norm(atoms, axis=1, keepdims=True), 1e-8)
x = np.zeros((n_samples, input_dim), dtype=np.float64)
for i in range(n_samples):
idx = rng.choice(n_atoms, size=3, replace=False)
amps = rng.uniform(0.9, 2.1, size=3)
x[i] = amps @ atoms[idx]
return x + rng.normal(0.0, 0.04, size=x.shape)
def _build_workbench_panels(results: dict[str, Any]) -> dict[str, Any]:
"""Assemble exact 6 KPIs, 4 Bar panels, 4 Tables with zero backticks, bold, or $math$."""
lin = results["linear_ae_pca"]
sae = results["sparse_ae"]
dae = results["dae"]
vae = results["vae_collapse"]
vq = results["vqvae_ema"]
sf_onx = results["safetensors_onnx"]
comp = results["pruning_kd_ptq"]
leak = results["pdm_leakage_audit"]
s1 = results["pdm_stage1_bayes"]
s2 = results["pdm_stage2_rul"]
s3 = results["pdm_stage3_rca"]
edge = results["edge_compressed_pdm"]
kpis = [
{
"id": "kpi_linear_ae_pca_parity",
"label": "Linear AE vs PCA Subspace Angle",
"value": f"{lin['subspace_principal_angle_rad']:.2e} rad",
"unit": "(< 1e-3 PASS)",
"status": "ok",
"detail": (
f"AE MSE {lin['ae_mse']:.5f} matches Eckart-Young {lin['eckart_young_mse']:.5f}; "
f"non-orthogonal GL(R) gauge dev={lin['orthogonality_deviation_fro']:.2f}."
),
},
{
"id": "kpi_vae_collapse_rescue",
"label": "VAE Active Units & KL Rescue",
"value": f"AU {vae['static']['active_units']} -> {vae['cyclical']['active_units']}",
"unit": f"(KL {vae['cyclical']['kl_nats']:.2f} nats)",
"status": "ok",
"detail": (
f"Static beta=1.0 collapses to AU={vae['static']['active_units']} "
f"(KL={vae['static']['kl_nats']:.3f}); Cyclical + Free Bits restores "
f"AU={vae['cyclical']['active_units']}."
),
},
{
"id": "kpi_serialization_onnx_parity",
"label": "Safetensors & ONNX ORT CPU Parity",
"value": f"{sf_onx['onnx']['max_abs_diff']:.2e}",
"unit": f"(sf={sf_onx['safetensors_max_diff']:.1e})",
"status": "ok",
"detail": (
f"Zero-pickle safetensors {sf_onx['safetensors_bytes']} B; "
f"ONNX dynamo=False ORT CPU p50={sf_onx['onnx']['ort_latency_ms']:.3f} ms."
),
},
{
"id": "kpi_edge_compression_int8",
"label": "Structured + INT8 Compression & SQNR",
"value": f"{comp['int8_bundle']['compression_ratio']:.2f}x INT8",
"unit": f"({comp['outlier_ptq']['sqnr_gain_db']:+.1f} dB rescue)",
"status": "ok",
"detail": (
f"Total compression {edge['total_compression_ratio']:.2f}x; "
f"Percentile 99.5% rescues MinMax +-48 EMI spike "
f"({comp['outlier_ptq']['minmax_sqnr_db']:.1f} -> "
f"{comp['outlier_ptq']['percentile_sqnr_db']:.1f} dB)."
),
},
{
"id": "kpi_pdm_bayes_cost_and_leakage",
"label": "Engine-ID Split & Bayes Cost Cut",
"value": f"-{s1['bayes_cost_reduction_vs_3std_pct']:.1f}% vs 3std",
"unit": f"(0 overlap | PR-AUC {s1['pr_auc']:.3f})",
"status": "ok",
"detail": (
f"Bayes t*={s1['bayes_threshold']:.4f} cuts cost vs 3*std and vs p=0.50 "
f"(-{s1['bayes_cost_reduction_vs_p50_pct']:.1f}%); ECE-10={s1['ece_10']:.4f}."
),
},
{
"id": "kpi_pdm_rul_phm08_and_rca",
"label": "RUL Cap=125 & Top-3 RCA Hit Rate",
"value": f"{s3['top_3_rca_hit_rate']:.1%}",
"unit": f"(RMSE {s2['test_rul_rmse']:.1f} cyc)",
"status": "ok",
"detail": (
f"PHM08 score={s2['phm08_score']:.0f} (late RMSE {s2['late_life_rmse']:.1f}); "
f"INT8 student holds {edge['int8_top_3_rca_hit_rate']:.1%} RCA "
f"at {edge['ort_latency_ms']:.3f} ms."
),
},
]
bars = [
{
"id": "bar_vae_vq_utilization",
"title": "VAE Active Units & VQ-VAE Codebook Perplexity Rescue",
"metric_label": "Units / Perplexity",
"items": [
{
"label": "vae_static_au",
"value": float(vae["static"]["active_units"]),
"display": f"AU {vae['static']['active_units']} / 6 (Collapse)",
"css_class": "is-slow",
},
{
"label": "vae_cyclical_au",
"value": float(vae["cyclical"]["active_units"]),
"display": (
f"AU {vae['cyclical']['active_units']} / 6 "
f"(KL {vae['cyclical']['kl_nats']:.2f})"
),
"css_class": "is-fast",
},
{
"label": "vq_no_ema_ppl",
"value": float(vq["no_ema"]["perplexity"]),
"display": (
f"PPL {vq['no_ema']['perplexity']:.2f} "
f"({vq['no_ema']['active_codes']}/16 codes)"
),
"css_class": "is-slow",
},
{
"label": "vq_ema_ppl",
"value": float(vq["ema"]["perplexity"]),
"display": (
f"PPL {vq['ema']['perplexity']:.2f} "
f"({vq['ema']['active_codes']}/16 codes)"
),
"css_class": "is-fast",
},
],
},
{
"id": "bar_compression_footprint_and_sqnr",
"title": "Edge Compression Byte Footprint (KB) & INT8 Student Size",
"metric_label": "Footprint (KB)",
"items": [
{
"label": "teacher_fp32_kb",
"value": round(comp["teacher_fp32_bytes"] / 1024.0, 3),
"display": f"{comp['teacher_fp32_bytes'] / 1024.0:.2f} KB (1.00x)",
"css_class": "is-slow",
},
{
"label": "unstructured_80_kb",
"value": round(comp["unstructured_80"]["dense_buffer_bytes"] / 1024.0, 3),
"display": (
f"{comp['unstructured_80']['dense_buffer_bytes'] / 1024.0:.2f} KB "
"(1.00x mirage)"
),
"css_class": "is-slow",
},
{
"label": "structured_kd_fp32_kb",
"value": round(comp["int8_bundle"]["fp32_weight_bytes"] / 1024.0, 3),
"display": (
f"{comp['int8_bundle']['fp32_weight_bytes'] / 1024.0:.2f} KB "
f"({comp['structured_prune']['memory_compression_ratio']:.2f}x)"
),
"css_class": "is-mid",
},
{
"label": "compressed_int8_kb",
"value": round(comp["int8_bundle"]["int8_bundle_bytes"] / 1024.0, 3),
"display": (
f"{comp['int8_bundle']['int8_bundle_bytes'] / 1024.0:.2f} KB "
f"({comp['total_compression_ratio']:.2f}x total)"
),
"css_class": "is-fast",
},
],
},
{
"id": "bar_pdm_threshold_cost_usd",
"title": "PdM Fleet Maintenance Cost by Decision Policy (Lower is Better, USD)",
"metric_label": "Total Cost (USD)",
"items": [
{
"label": "symmetric_p50_cost",
"value": float(s1["policies"]["symmetric_p50"]["total_cost_usd"]),
"display": (
f"{s1['policies']['symmetric_p50']['total_cost_usd']:,.0f} USD "
f"(FN={int(s1['policies']['symmetric_p50']['fn'])})"
),
"css_class": "is-slow",
},
{
"label": "naive_3std_cost",
"value": float(s1["policies"]["naive_3std"]["total_cost_usd"]),
"display": (
f"{s1['policies']['naive_3std']['total_cost_usd']:,.0f} USD "
f"(FN={int(s1['policies']['naive_3std']['fn'])})"
),
"css_class": "is-mid",
},
{
"label": "bayes_cost_optimal_tstar",
"value": float(s1["policies"]["bayes_optimal"]["total_cost_usd"]),
"display": (
f"{s1['policies']['bayes_optimal']['total_cost_usd']:,.0f} USD "
f"(t*={s1['bayes_threshold']:.4f})"
),
"css_class": "is-fast",
},
],
},
{
"id": "bar_pdm_leakage_rmse_and_rca",
"title": "Leaky Cycle Split vs Honest Engine-ID RMSE & Top-3 RCA Hit Rate",
"metric_label": "Cycles / Hit %",
"items": [
{
"label": "leaky_cycle_rmse",
"value": float(leak["leaky_cycle_rmse"]),
"display": (
f"Offline {leak['leaky_cycle_rmse']:.2f} -> "
f"Live {leak['leaky_live_unseen_rmse']:.2f}"
),
"css_class": "is-slow",
},
{
"label": "honest_engine_rmse",
"value": float(leak["honest_engine_rmse"]),
"display": f"Honest {leak['honest_engine_rmse']:.2f} cyc (0 overlap)",
"css_class": "is-mid",
},
{
"label": "stage2_capped_rul_rmse",
"value": float(s2["test_rul_rmse"]),
"display": f"Stage2 {s2['test_rul_rmse']:.2f} cyc (Late {s2['late_life_rmse']:.2f})",
"css_class": "is-fast",
},
{
"label": "stage3_top3_rca_pct",
"value": float(s3["top_3_rca_hit_rate"] * 100.0),
"display": (
f"RCA {s3['top_3_rca_hit_rate']:.1%} "
f"(INT8 {edge['int8_top_3_rca_hit_rate']:.1%})"
),
"css_class": "is-fast",
},
],
},
]
tables = [
{
"id": "tbl_ae_representation_variants",
"title": "Autoencoder Families & Representation Diagnostics",
"columns": ["Architecture", "Key Metric", "Observed Value", "Target Gate"],
"rows": [
[
"Linear AE (NumPy ALS)",
"Principal Angle vs PCA",
f"{lin['subspace_principal_angle_rad']:.2e} rad",
"< 1e-3 rad (PASS)",
],
[
"Sparse AE (L1 vs TopK vs JumpReLU)",
"Amplitude Ratio (No Shrinkage)",
(
f"L1={sae['l1']['active_amplitude_ratio']:.2f} | "
f"TopK={sae['topk']['active_amplitude_ratio']:.2f} | "
f"Jump={sae['jumprelu']['active_amplitude_ratio']:.2f}"
),
"TopK/Jump > L1 (PASS)",
],
[
"Denoising AE (Gaussian sigma=0.45)",
"Denoising MSE Gain",
f"{dae['denoising_gain_ratio']:.2f}x ({dae['snr_gain_db']:+.1f} dB)",
"> 2.5x vs noisy (PASS)",
],
[
"VAE (Static vs Cyclical + Free Bits)",
"Active Units (AU / 6) & KL",
(
f"Static AU={vae['static']['active_units']} ({vae['static']['kl_nats']:.2f}) -> "
f"Cyclical AU={vae['cyclical']['active_units']} ({vae['cyclical']['kl_nats']:.2f})"
),
"AU >= 2, KL > 0.25 (PASS)",
],
[
"VQ-VAE (No-EMA vs EMA + Dead Reset)",
"Codebook Perplexity (PPL)",
f"No-EMA {vq['no_ema']['perplexity']:.2f} -> EMA {vq['ema']['perplexity']:.2f}",
"EMA > No-EMA (PASS)",
],
],
},
{
"id": "tbl_serialization_and_compression",
"title": "Supply-Chain-Safe Serialization & Edge Compression",
"columns": ["Artifact / Regime", "Weight Size", "Compression", "Parity / SQNR"],
"rows": [
[
"Teacher FP32 (TorchSensorAE)",
f"{comp['teacher_fp32_bytes']} B",
"1.00x",
f"MSE {comp['kd']['teacher_recon_mse']:.4f}",
],
[
"Safetensors Round-Trip (0 pickle)",
f"{sf_onx['safetensors_bytes']} B",
"Zero-copy mmap",
f"Max Diff {sf_onx['safetensors_max_diff']:.2e} (< 1e-6)",
],
[
"ONNX (dynamo=False) + ORT CPU",
f"{int(sf_onx['onnx']['onnx_bytes'])} B",
f"p50 {sf_onx['onnx']['ort_latency_ms']:.3f} ms",
f"Max Diff {sf_onx['onnx']['max_abs_diff']:.2e} (< 1e-4)",
],
[
"Unstructured 80% Magnitude Mask",
f"{int(comp['unstructured_80']['dense_buffer_bytes'])} B",
"1.00x (0% saved)",
"Dense BLAS mirage",
],
[
"Structured + KD + INT8 Percentile 99.5%",
f"{comp['int8_bundle']['int8_bundle_bytes']} B",
(
f"{comp['int8_bundle']['compression_ratio']:.2f}x INT8 "
f"({comp['total_compression_ratio']:.2f}x total)"
),
(
f"SQNR {comp['outlier_ptq']['percentile_sqnr_db']:.1f} dB vs "
f"MinMax {comp['outlier_ptq']['minmax_sqnr_db']:.1f} dB"
),
],
],
},
{
"id": "tbl_pdm_stage1_stage2_audit",
"title": "IoT PdM Leakage Audit, Bayes Thresholding & Stage 2 PHM08",
"columns": ["PdM Policy / Split", "PR-AUC / ECE", "FP / FN", "Fleet Cost / Score"],
"rows": [
[
"Leaky Cycle Split (Class 3+4)",
f"{int(leak['leaky_shared_engine_count'])} shared engines",
"—",
(
f"Offline {leak['leaky_cycle_rmse']:.2f} -> "
f"Live {leak['leaky_live_unseen_rmse']:.2f} RMSE"
),
],
[
"Honest Engine-ID GroupSplit",
"0 shared engines",
"—",
f"Honest RMSE {leak['honest_engine_rmse']:.2f} cyc",
],
[
"Stage 1 Heuristic (mean + 3*std)",
f"PR-AUC {s1['pr_auc']:.3f}",
(
f"FP={int(s1['policies']['naive_3std']['fp'])} / "
f"FN={int(s1['policies']['naive_3std']['fn'])}"
),
f"{s1['policies']['naive_3std']['total_cost_usd']:,.0f} USD",
],
[
"Stage 1 Symmetric (p = 0.50)",
f"ECE-10 {s1['ece_10']:.4f}",
(
f"FP={int(s1['policies']['symmetric_p50']['fp'])} / "
f"FN={int(s1['policies']['symmetric_p50']['fn'])}"
),
f"{s1['policies']['symmetric_p50']['total_cost_usd']:,.0f} USD",
],
[
f"Stage 1 Bayes Optimal (t*={s1['bayes_threshold']:.4f})",
f"PR-AUC {s1['pr_auc']:.3f} | ECE {s1['ece_10']:.4f}",
(
f"FP={int(s1['policies']['bayes_optimal']['fp'])} / "
f"FN={int(s1['policies']['bayes_optimal']['fn'])}"
),
f"{s1['policies']['bayes_optimal']['total_cost_usd']:,.0f} USD (BEST)",
],
[
"Stage 2 Capped RUL (RUL_max=125)",
f"Late RMSE {s2['late_life_rmse']:.2f} cyc",
f"All RMSE {s2['test_rul_rmse']:.2f} cyc",
f"PHM08={s2['phm08_score']:.0f} (vs Uncap {s2['uncapped_phm08_score']:.0f})",
],
],
},
{
"id": "tbl_pdm_stage3_rca_subsystems",
"title": "Stage 3 Subsystem Root Cause Analysis (RCA) & Edge INT8 Student",
"columns": ["Fault Mode / Model", "Target Subsystem", "Top-3 Sensors", "Top-3 RCA Hit Rate"],
"rows": [
[
mode,
info["target_subsystem"],
", ".join(info["top_3_sensors"]),
f"{info['top_3_rca_hit_rate']:.1%} (Top-1 Sub {info['top_1_subsystem_acc']:.1%})",
]
for mode, info in s3["by_fault_mode"].items()
]
+ [
[
"Compressed INT8 Edge Student",
"All 4 Subsystems",
f"PR-AUC {edge['int8_pr_auc']:.3f} | RUL {edge['int8_rul_rmse']:.1f} cyc",
(
f"{edge['int8_top_3_rca_hit_rate']:.1%} "
f"({edge['int8_compression_ratio']:.2f}x INT8, "
f"{edge['ort_latency_ms']:.3f} ms)"
),
]
],
},
]
return {"kpis": kpis, "bars": bars, "tables": tables}
def run_full_ch15_lab07_benchmarks(seed: int = 42, quick: bool = False) -> dict[str, Any]:
"""Execute the full Lab 07 benchmark suite and return structured telemetry + workbench panels."""
scale = 0.55 if quick else 1.0
n_manifold = 360 if quick else 600
n_sparse = 400 if quick else 720
ae_epochs = 40 if quick else 70
# 1. Linear AE vs PCA
x_manifold = _build_synthetic_manifold_data(n_manifold, input_dim=16, seed=seed)
lin_res = fit_linear_ae_numpy(
x_manifold,
LinearAEConfig(input_dim=16, latent_dim=4, epochs=180 if quick else 260, seed=seed),
)
# 2. Sparse AE (L1 vs TopK vs JumpReLU)
x_sparse = _build_sparse_dictionary_data(n_sparse, input_dim=16, seed=seed)
sae_epochs = 90 if quick else 130
sae_l1 = train_sparse_ae_comparison(
x_sparse,
SparseAEConfig(
input_dim=16, latent_dim=32, sparsity_mode="l1", l1_lambda=0.14, epochs=sae_epochs, seed=seed
),
)
sae_topk = train_sparse_ae_comparison(
x_sparse,
SparseAEConfig(
input_dim=16, latent_dim=32, sparsity_mode="topk", topk=3, epochs=sae_epochs, seed=seed
),
)
sae_jump = train_sparse_ae_comparison(
x_sparse,
SparseAEConfig(
input_dim=16,
latent_dim=32,
sparsity_mode="jumprelu",
jumprelu_theta=0.35,
epochs=sae_epochs,
seed=seed,
),
)
# 3. Denoising AE & CAE Jacobian
dae_res = fit_denoising_ae_numpy(
x_manifold,
DAEConfig(input_dim=16, latent_dim=8, noise_std=0.45, epochs=130 if quick else 190, seed=seed),
)
# 4. VAE Static Collapse vs Cyclical Annealing + Free Bits
vae_res = train_vae_collapse_vs_annealed(
x_manifold, latent_dim=6, beta_max=1.0, free_bits_lambda=0.20, epochs=45 if quick else 65, seed=seed
)
# 5. VQ-VAE EMA + Dead-Code Reset vs No-EMA Collapse
vq_epochs = 50 if quick else 80
vq_res = train_vqvae_ema_vs_no_ema(
x_manifold,
VQVAEConfig(input_dim=16, latent_dim=4, num_codes=16, use_ema=True, epochs=vq_epochs, seed=seed),
VQVAEConfig(input_dim=16, latent_dim=4, num_codes=16, use_ema=False, epochs=vq_epochs, seed=seed),
)
# 6 & 7. Safe Serialization + Pruning + KD + INT8 Outlier PTQ
torch.manual_seed(seed)
teacher_ae = TorchSensorAE(input_dim=16, hidden_dim=128, latent_dim=6)
x_tr_t = torch.from_numpy(x_manifold.astype(np.float32))
opt_t = torch.optim.Adam(teacher_ae.parameters(), lr=0.005)
for _ in range(ae_epochs):
opt_t.zero_grad()
loss_t = F.mse_loss(teacher_ae(x_tr_t), x_tr_t)
loss_t.backward()
opt_t.step()
teacher_ae.eval()
with tempfile.TemporaryDirectory() as tmp_dir:
tmp_path = Path(tmp_dir)
sf_path = tmp_path / "teacher_ae.safetensors"
sf_meta = save_state_dict_safetensors(teacher_ae, sf_path)
reloaded_ae = TorchSensorAE(input_dim=16, hidden_dim=128, latent_dim=6).eval()
sf_diff = load_state_dict_safetensors(reloaded_ae, sf_path)
onnx_res = export_and_verify_onnx_parity(
reloaded_ae, x_tr_t[:32], tmp_path / "teacher_ae.onnx"
)
unstruct_res = unstructured_magnitude_prune_mask(teacher_ae, sparsity=0.80)
comp_cfg = CompressionConfig(
prune_ratio=0.625,
kd_temperature=4.0,
kd_alpha=0.5,
quant_calibration="percentile",
percentile_q=99.5,
seed=seed,
)
student_ae, struct_res = structured_width_prune_ae(teacher_ae, keep_ratio=1.0 - comp_cfg.prune_ratio)
kd_res = distill_student_ae(
teacher_ae, student_ae, x_manifold.astype(np.float32), comp_cfg, epochs=45 if quick else 80
)
int8_bundle = compress_student_to_int8_bundle(student_ae, x_manifold.astype(np.float32), comp_cfg)
rng = np.random.default_rng(seed)
emi_calib = rng.normal(0.0, 0.6, size=(3000, 16)).astype(np.float32)
emi_calib[rng.random(emi_calib.shape) < 0.003] = 48.0
alpha_minmax = calibrate_clipping_threshold(emi_calib, "minmax")
alpha_pct = calibrate_clipping_threshold(emi_calib, "percentile", percentile_q=99.5)
alpha_mse = calibrate_clipping_threshold(emi_calib, "mse")
sqnr_minmax = evaluate_int8_sqnr(emi_calib, alpha_minmax, normal_bound=2.0)
sqnr_pct = evaluate_int8_sqnr(emi_calib, alpha_pct, normal_bound=2.0)
sqnr_mse = evaluate_int8_sqnr(emi_calib, alpha_mse, normal_bound=2.0)
# 8. IoT Fleet Simulation, Engine-ID GroupSplit & Leakage Audit
sim_cfg = FleetSimConfig(
n_train_engines=14 if quick else 30,
n_cal_engines=8 if quick else 15,
n_test_engines=10 if quick else 18,
seed=seed,
)
cost_cfg = PdMCostConfig()
fleet = simulate_turbofan_fleet(sim_cfg)
split_data = split_fleet_by_engine_id(fleet, sim_cfg)
leak_res = run_leaky_cycle_split_contrast(fleet, cfg=sim_cfg, seed=seed)
# 9. Stage 1 Healthy-Only Detector & Bayes Cost Thresholding
stage1_detector = fit_stage1_healthy_detector(
split_data, latent_dim=6, hidden_dim=64, epochs=int(round(65 * scale)), seed=seed
)
stage1_bayes = calibrate_and_threshold_bayes(stage1_detector, split_data, cost_cfg)
# 10. Stage 2 Capped RUL & NASA PHM08
stage2_rul = fit_stage2_rul_predictor(
split_data, rul_max=cost_cfg.rul_max, hidden_dim=64, epochs=int(round(80 * scale)), seed=seed
)
# 11. Stage 3 RCA Attribution
te = split_data["test"]
attr = compute_rca_sensor_attribution(
stage1_detector["model"], te["x_scaled"], stage1_detector["healthy_err_std"]
)
stage3_rca = evaluate_rca_subsystem_hit_rate(
attr["combined_attr"], te["true_subsystem"], te["fault_mode"], te["is_imminent"]
)
# 12. End-to-End Edge Compressed Student PdM
edge_pdm = compress_and_evaluate_edge_pdm(
stage1_detector,
stage2_rul,
stage1_bayes,
split_data,
CompressionConfig(prune_ratio=0.625, seed=seed),
epochs=int(round(55 * scale)),
)
teacher_fp32_bytes = int(sum(p.numel() * 4 for p in teacher_ae.parameters()))
total_ratio = float(teacher_fp32_bytes / max(int8_bundle["int8_bundle_bytes"], 1))
results: dict[str, Any] = {
"config": {
"seed": seed,
"quick": quick,
"n_train_engines": sim_cfg.n_train_engines,
"n_cal_engines": sim_cfg.n_cal_engines,
"n_test_engines": sim_cfg.n_test_engines,
"rul_max": cost_cfg.rul_max,
"cost_fp_usd": cost_cfg.cost_fp_usd,
"cost_fn_usd": cost_cfg.cost_fn_usd,
},
"linear_ae_pca": {
"ae_mse": lin_res["ae_mse"],
"eckart_young_mse": lin_res["eckart_young_mse"],
"mse_abs_diff": lin_res["mse_abs_diff"],
"subspace_principal_angle_rad": lin_res["subspace_principal_angle_rad"],
"orthogonality_deviation_fro": lin_res["orthogonality_deviation_fro"],
"singular_gap_ratio": lin_res["singular_gap_ratio"],
},
"sparse_ae": {
"l1": sae_l1,
"topk": sae_topk,
"jumprelu": sae_jump,
},
"dae": dae_res,
"vae_collapse": vae_res,
"vqvae_ema": vq_res,
"safetensors_onnx": {
"safetensors_bytes": sf_meta["file_bytes"],
"safetensors_header_bytes": sf_meta["header_bytes"],
"safetensors_max_diff": sf_diff,
"onnx": onnx_res,
},
"pruning_kd_ptq": {
"teacher_fp32_bytes": teacher_fp32_bytes,
"unstructured_80": unstruct_res,
"structured_prune": struct_res,
"kd": kd_res,
"int8_bundle": {
k: v for k, v in int8_bundle.items() if k != "predict_int8"
},
"total_compression_ratio": total_ratio,
"outlier_ptq": {
"minmax_sqnr_db": sqnr_minmax["sqnr_db"],
"minmax_bins": int(sqnr_minmax["active_normal_bins"]),
"percentile_sqnr_db": sqnr_pct["sqnr_db"],
"percentile_bins": int(sqnr_pct["active_normal_bins"]),
"mse_sqnr_db": sqnr_mse["sqnr_db"],
"mse_bins": int(sqnr_mse["active_normal_bins"]),
"sqnr_gain_db": float(sqnr_pct["sqnr_db"] - sqnr_minmax["sqnr_db"]),
},
},
"pdm_leakage_audit": {
**leak_res,
"engine_overlap_count": split_data["overlap_count"],
"regime_stats_fit_split": split_data["regime_stats_fit_split"],
},
"pdm_stage1_bayes": {
"pr_auc": stage1_bayes["pr_auc"],
"roc_auc": stage1_bayes["roc_auc"],
"ece_10": stage1_bayes["ece_10"],
"bayes_threshold": stage1_bayes["bayes_threshold"],
"naive_3std_score_cutoff": stage1_bayes["naive_3std_score_cutoff"],
"policies": stage1_bayes["policies"],
"bayes_cost_reduction_vs_3std_pct": stage1_bayes["bayes_cost_reduction_vs_3std_pct"],
"bayes_cost_reduction_vs_p50_pct": stage1_bayes["bayes_cost_reduction_vs_p50_pct"],
},
"pdm_stage2_rul": {
"rul_max": stage2_rul["rul_max"],
"test_rul_rmse": stage2_rul["test_rul_rmse"],
"late_life_rmse": stage2_rul["late_life_rmse"],
"phm08_score": stage2_rul["phm08_score"],
"mean_phm08_per_cycle": stage2_rul["mean_phm08_per_cycle"],
"uncapped_late_life_rmse": stage2_rul["uncapped_late_life_rmse"],
"uncapped_phm08_score": stage2_rul["uncapped_phm08_score"],
},
"pdm_stage3_rca": stage3_rca,
"edge_compressed_pdm": edge_pdm,
}
results["workbench_panels"] = _build_workbench_panels(results)
return results
"""End-to-end CLI benchmark runner for Lab 07: Autoencoders, Compression & IoT PdM."""
from __future__ import annotations
import argparse
import json
import sys
from pathlib import Path
if hasattr(sys.stdout, "reconfigure"):
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
try:
import iot_ae_pdm_lab # noqa: F401
except ImportError:
_SRC_DIR = Path(__file__).resolve().parents[1] / "src"
if str(_SRC_DIR) not in sys.path:
sys.path.insert(0, str(_SRC_DIR))
from iot_ae_pdm_lab.pdm_pipeline import run_full_ch15_lab07_benchmarks # noqa: E402
def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
"""Parse CLI arguments for Lab 07 Autoencoders, Edge Compression & IoT PdM."""
parser = argparse.ArgumentParser(
description="Run Ch 15 + Lab 07: Autoencoders, Safe Export, Compression & 3-Stage IoT PdM."
)
parser.add_argument("--seed", type=int, default=42, help="Deterministic RNG seed.")
parser.add_argument(
"--quick",
action="store_true",
help="Run lighter sample sizes and epochs for fast CI verification.",
)
parser.add_argument(
"--output",
type=str,
default="artifacts/ch15_lab07_results.json",
help="Output JSON artifact path.",
)
return parser.parse_args(argv)
def main(argv: list[str] | None = None) -> int:
"""Execute benchmarks, print formatted summary telemetry, and write JSON artifact."""
args = parse_args(argv)
payload = run_full_ch15_lab07_benchmarks(seed=args.seed, quick=args.quick)
payload["config"]["output"] = args.output
lin = payload["linear_ae_pca"]
vae = payload["vae_collapse"]
vq = payload["vqvae_ema"]
sf_onx = payload["safetensors_onnx"]
comp = payload["pruning_kd_ptq"]
leak = payload["pdm_leakage_audit"]
s1 = payload["pdm_stage1_bayes"]
s2 = payload["pdm_stage2_rul"]
s3 = payload["pdm_stage3_rca"]
edge = payload["edge_compressed_pdm"]
print("=== Ch 15 + Lab 07: Autoencoders, Compression & Leakage-Proof IoT PdM ===")
print(
f"[1] Representation Core: LinearAE-PCA angle={lin['subspace_principal_angle_rad']:.2e} rad "
f"| VAE AU {vae['static']['active_units']}->{vae['cyclical']['active_units']} "
f"(KL {vae['static']['kl_nats']:.2f}->{vae['cyclical']['kl_nats']:.2f}) "
f"| VQ PPL {vq['no_ema']['perplexity']:.2f}->{vq['ema']['perplexity']:.2f}"
)
print(
f"[2] Safe Export & INT8 PTQ: Safetensors diff={sf_onx['safetensors_max_diff']:.2e} "
f"| ONNX(dynamo=False) ORT diff={sf_onx['onnx']['max_abs_diff']:.2e} "
f"({sf_onx['onnx']['ort_latency_ms']:.3f} ms) "
f"| Unstructured 80%={comp['unstructured_80']['dense_compression_ratio']:.2f}x "
f"vs INT8 Bundle={comp['int8_bundle']['compression_ratio']:.2f}x "
f"(Outlier SQNR {comp['outlier_ptq']['minmax_sqnr_db']:.1f}->"
f"{comp['outlier_ptq']['percentile_sqnr_db']:.1f} dB)"
)
print(
f"[3] Leakage & Stage 1 Bayes: Engine Overlap={leak['engine_overlap_count']} "
f"(Leaky {leak['leaky_cycle_rmse']:.2f}->Live {leak['leaky_live_unseen_rmse']:.2f} vs "
f"Honest {leak['honest_engine_rmse']:.2f}) "
f"| PR-AUC={s1['pr_auc']:.3f}, ECE={s1['ece_10']:.4f} "
f"| Bayes t*={s1['bayes_threshold']:.4f} cuts cost "
f"-{s1['bayes_cost_reduction_vs_3std_pct']:.1f}% vs 3std / "
f"-{s1['bayes_cost_reduction_vs_p50_pct']:.1f}% vs p=0.50"
)
print(
f"[4] Stage 2 RUL, Stage 3 RCA & Edge Student: RUL RMSE={s2['test_rul_rmse']:.2f} cyc "
f"(PHM08={s2['phm08_score']:.0f}) | Top-3 RCA={s3['top_3_rca_hit_rate']:.1%} "
f"| Edge INT8 {edge['int8_compression_ratio']:.2f}x "
f"(PR-AUC={edge['int8_pr_auc']:.3f}, RUL={edge['int8_rul_rmse']:.2f}, "
f"RCA={edge['int8_top_3_rca_hit_rate']:.1%}, ORT={edge['ort_latency_ms']:.3f} ms)"
)
out_path = Path(args.output)
out_path.parent.mkdir(parents=True, exist_ok=True)
out_path.write_text(json.dumps(payload, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
return 0
if __name__ == "__main__":
raise SystemExit(main())
"""16 deterministic offline unit, mathematical, anti-leakage, Tier-2 parity & AST tests for Lab 07."""
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
import torch.nn.functional as F
from pydantic import ValidationError
from iot_ae_pdm_lab.autoencoders_and_compression import (
CompressionConfig,
DAEConfig,
LinearAEConfig,
SparseAEConfig,
TorchSensorAE,
VAEConfig,
VQVAEBottleneck,
VQVAEConfig,
calibrate_clipping_threshold,
compress_student_to_int8_bundle,
contractive_jacobian_penalty_sigmoid,
cyclical_beta_schedule,
distill_student_ae,
evaluate_int8_sqnr,
export_and_verify_onnx_parity,
fit_denoising_ae_numpy,
fit_linear_ae_numpy,
gaussian_kl_divergence,
load_state_dict_safetensors,
save_state_dict_safetensors,
structured_width_prune_ae,
train_sparse_ae_comparison,
train_vae_collapse_vs_annealed,
train_vqvae_ema_vs_no_ema,
unstructured_magnitude_prune_mask,
)
from iot_ae_pdm_lab.pdm_pipeline import (
SUBSYSTEM_SENSOR_MAP,
FleetSimConfig,
PdMCostConfig,
_build_sparse_dictionary_data,
_build_synthetic_manifold_data,
calibrate_and_threshold_bayes,
cap_rul_targets,
compress_and_evaluate_edge_pdm,
compute_rca_sensor_attribution,
evaluate_rca_subsystem_hit_rate,
fit_stage1_healthy_detector,
fit_stage2_rul_predictor,
nasa_phm08_score,
run_leaky_cycle_split_contrast,
simulate_turbofan_fleet,
split_fleet_by_engine_id,
)
LAB_ROOT = Path(__file__).resolve().parents[1]
FORBIDDEN_UNSAFE_IMPORTS = {
"pickle",
"_pickle",
"cPickle",
"joblib",
"cloudpickle",
"dill",
"shelve",
"marshal",
}
# ---------------------------------------------------------------------------
# Test 1: Strict Pydantic v2 Extra-Forbid Contracts & Domain Bounds
# ---------------------------------------------------------------------------
def test_01_pydantic_configs_strict_forbid() -> None:
with pytest.raises(ValidationError):
LinearAEConfig(unknown_field=123) # type: ignore[call-arg]
with pytest.raises(ValidationError):
LinearAEConfig(input_dim=8, latent_dim=8) # must be strictly undercomplete
with pytest.raises(ValidationError):
SparseAEConfig(input_dim=16, latent_dim=16) # must be strictly overcomplete
with pytest.raises(ValidationError):
SparseAEConfig(input_dim=16, latent_dim=32, topk=32) # topk < latent_dim
with pytest.raises(ValidationError):
DAEConfig(noise_std=0.0)
with pytest.raises(ValidationError):
VAEConfig(extra_param=True) # type: ignore[call-arg]
with pytest.raises(ValidationError):
VQVAEConfig(ema_decay=1.0)
with pytest.raises(ValidationError):
CompressionConfig(quant_bits=4) # type: ignore[arg-type]
with pytest.raises(ValidationError):
FleetSimConfig(rul_max=100) # type: ignore[arg-type]
with pytest.raises(ValidationError):
PdMCostConfig(cost_fn_usd=-10.0)
cost_cfg = PdMCostConfig(cost_fp_usd=800.0, cost_fn_usd=50_000.0)
assert cost_cfg.bayes_threshold == pytest.approx(800.0 / 50_800.0, rel=1e-12)
# ---------------------------------------------------------------------------
# Test 2: Bourlard-Kamp Linear AE vs PCA Subspace Equivalence
# ---------------------------------------------------------------------------
def test_02_linear_ae_pca_subspace_equivalence() -> None:
x_data = _build_synthetic_manifold_data(n_samples=450, input_dim=16, seed=42)
cfg = LinearAEConfig(input_dim=16, latent_dim=4, epochs=240, seed=42)
res = fit_linear_ae_numpy(x_data, cfg)
assert res["subspace_principal_angle_rad"] < 1e-3
assert res["mse_abs_diff"] < 1e-5
assert res["ae_mse"] == pytest.approx(res["eckart_young_mse"], abs=1e-5)
assert res["orthogonality_deviation_fro"] > 0.01 # GL_{d_z}(R) gauge freedom
# ---------------------------------------------------------------------------
# Test 3: Sparse AE (L1 Unit-Norm vs TopK+AuxK & JumpReLU KDE-STE)
# ---------------------------------------------------------------------------
def test_03_sparse_ae_l1_vs_topk_and_jumprelu_no_shrinkage() -> None:
x_sparse = _build_sparse_dictionary_data(n_samples=480, input_dim=16, seed=42)
res_l1 = train_sparse_ae_comparison(
x_sparse,
SparseAEConfig(input_dim=16, latent_dim=32, sparsity_mode="l1", l1_lambda=0.14, epochs=110, seed=42),
)
res_topk = train_sparse_ae_comparison(
x_sparse,
SparseAEConfig(input_dim=16, latent_dim=32, sparsity_mode="topk", topk=3, epochs=110, seed=42),
)
res_jump = train_sparse_ae_comparison(
x_sparse,
SparseAEConfig(
input_dim=16, latent_dim=32, sparsity_mode="jumprelu", jumprelu_theta=0.35, epochs=110, seed=42
),
)
assert res_topk["mean_l0"] == pytest.approx(3.0, abs=0.05)
assert res_topk["dead_latent_fraction"] < 0.25
# TopK & JumpReLU eliminate Tibshirani L1 shrinkage bias
assert res_topk["active_amplitude_ratio"] > res_l1["active_amplitude_ratio"] + 0.05
assert res_jump["active_amplitude_ratio"] > res_l1["active_amplitude_ratio"] + 0.03
assert res_topk["recon_mse"] < res_l1["recon_mse"]
# ---------------------------------------------------------------------------
# Test 4: Denoising AE SNR Gain & Analytical Sigmoid Contractive Jacobian
# ---------------------------------------------------------------------------
def test_04_denoising_ae_manifold_denoising_snr() -> None:
x_clean = _build_synthetic_manifold_data(n_samples=450, input_dim=16, seed=42)
res = fit_denoising_ae_numpy(
x_clean, DAEConfig(input_dim=16, latent_dim=8, noise_std=0.45, epochs=170, seed=42)
)
assert res["denoising_gain_ratio"] > 2.5
assert res["dae_recon_mse"] < res["unregularized_ae_noisy_mse"]
assert res["snr_gain_db"] > 4.0
# Exact verification of contractive_jacobian_penalty_sigmoid against finite differences
rng = np.random.default_rng(7)
w_enc = rng.normal(0.0, 0.5, size=(5, 4))
b_enc = rng.normal(0.0, 0.2, size=(5,))
x0 = rng.normal(0.0, 1.0, size=(4,))
h0 = 1.0 / (1.0 + np.exp(-(w_enc @ x0 + b_enc)))
analytic_fnorm_sq = contractive_jacobian_penalty_sigmoid(w_enc, h0)
eps = 1e-6
fd_jac = np.zeros((5, 4), dtype=np.float64)
for j in range(4):
dx = np.zeros(4, dtype=np.float64)
dx[j] = eps
h_plus = 1.0 / (1.0 + np.exp(-(w_enc @ (x0 + dx) + b_enc)))
h_minus = 1.0 / (1.0 + np.exp(-(w_enc @ (x0 - dx) + b_enc)))
fd_jac[:, j] = (h_plus - h_minus) / (2.0 * eps)
fd_fnorm_sq = float(np.sum(fd_jac**2))
assert analytic_fnorm_sq == pytest.approx(fd_fnorm_sq, rel=1e-7, abs=1e-9)
# ---------------------------------------------------------------------------
# Test 5: VAE ELBO Gaussian KL & Collapse vs Cyclical Annealing + Free Bits
# ---------------------------------------------------------------------------
def test_05_vae_elbo_kl_collapse_vs_cyclical_annealing() -> None:
mu = torch.tensor([[0.0, 0.0], [1.2, -0.8], [-0.5, 0.3]], dtype=torch.float32)
logvar = torch.tensor([[0.0, 0.0], [-25.0, 14.0], [-0.4, 0.5]], dtype=torch.float32)
kl = gaussian_kl_divergence(mu, logvar)
assert kl.shape == (3,)
assert kl[0].item() == pytest.approx(0.0, abs=1e-7)
assert torch.all(kl >= 0.0)
assert torch.isfinite(kl).all()
assert cyclical_beta_schedule(0, 100, n_cycles=4, ramp_ratio=0.5, beta_max=1.0) == pytest.approx(0.0)
assert cyclical_beta_schedule(15, 100, n_cycles=4, ramp_ratio=0.5, beta_max=1.0) == pytest.approx(1.0)
x_data = _build_synthetic_manifold_data(n_samples=420, input_dim=16, seed=42)
res = train_vae_collapse_vs_annealed(
x_data, latent_dim=6, beta_max=1.0, free_bits_lambda=0.20, epochs=55, seed=42
)
assert res["static"]["active_units"] <= 1
assert res["static"]["kl_nats"] < 0.15
assert res["cyclical"]["active_units"] >= 2
assert res["cyclical"]["kl_nats"] > 0.25
assert res["cyclical"]["active_units"] > res["static"]["active_units"]
# ---------------------------------------------------------------------------
# Test 6: VQ-VAE STE Gradient Flow & EMA Codebook Perplexity Rescue
# ---------------------------------------------------------------------------
def test_06_vqvae_ema_codebook_perplexity_vs_collapse() -> None:
torch.manual_seed(42)
vq = VQVAEBottleneck(num_codes=8, latent_dim=4, commitment_beta=0.25, use_ema=True)
z_e = torch.randn(16, 4, requires_grad=True)
z_ste, vq_loss, indices, z_q = vq(z_e)
assert z_ste.shape == z_e.shape
assert z_q.shape == z_e.shape
assert indices.shape == (16,)
(z_ste.pow(2).mean() + vq_loss).backward()
assert z_e.grad is not None
assert float(torch.linalg.vector_norm(z_e.grad).item()) > 0.0
x_data = _build_synthetic_manifold_data(n_samples=420, input_dim=16, seed=42)
res = train_vqvae_ema_vs_no_ema(
x_data,
VQVAEConfig(input_dim=16, latent_dim=4, num_codes=16, use_ema=True, epochs=60, seed=42),
VQVAEConfig(input_dim=16, latent_dim=4, num_codes=16, use_ema=False, epochs=60, seed=42),
)
assert res["ema"]["perplexity"] > res["no_ema"]["perplexity"]
assert res["ema"]["active_codes"] > res["no_ema"]["active_codes"]
# ---------------------------------------------------------------------------
# Test 7: Safetensors Zero-Pickle Header Audit & Round-Trip Parity (< 1e-6)
# ---------------------------------------------------------------------------
def test_07_safetensors_zero_pickle_roundtrip_parity(tmp_path: Path) -> None:
torch.manual_seed(42)
model = TorchSensorAE(input_dim=16, hidden_dim=48, latent_dim=6).eval()
sf_path = tmp_path / "sensor_ae.safetensors"
meta = save_state_dict_safetensors(model, sf_path)
raw = sf_path.read_bytes()
hdr_len = struct.unpack("<Q", raw[:8])[0]
assert hdr_len == meta["header_bytes"]
header_obj = json.loads(raw[8 : 8 + hdr_len].decode("utf-8"))
assert header_obj["__metadata__"]["lab"] == "iot_ae_pdm_lab"
assert meta["num_tensors"] == len(model.state_dict())
reloaded = TorchSensorAE(input_dim=16, hidden_dim=48, latent_dim=6).eval()
load_diff = load_state_dict_safetensors(reloaded, sf_path)
assert load_diff < 1e-6
x_probe = torch.randn(12, 16)
with torch.no_grad():
out_diff = float((model(x_probe) - reloaded(x_probe)).abs().max().item())
assert out_diff < 1e-6
# ---------------------------------------------------------------------------
# Test 8: ONNX Export (dynamo=False) & ORT CPU Parity (< 1e-4)
# ---------------------------------------------------------------------------
def test_08_onnx_dynamo_false_and_ort_cpu_parity(tmp_path: Path) -> None:
torch.manual_seed(42)
model = TorchSensorAE(input_dim=16, hidden_dim=48, latent_dim=6).eval()
batch = torch.randn(24, 16, dtype=torch.float32)
res = export_and_verify_onnx_parity(model, batch, tmp_path / "sensor_ae.onnx")
assert res["onnx_bytes"] > 1000.0
assert res["max_abs_diff"] < 1e-4
assert res["ort_latency_ms"] < 5.0
# ---------------------------------------------------------------------------
# Test 9: Structured Width Pruning vs Unstructured 80% Mirage & FitNets KD
# ---------------------------------------------------------------------------
def test_09_structured_vs_unstructured_pruning_and_kd_scaling() -> None:
torch.manual_seed(42)
x_data = _build_synthetic_manifold_data(n_samples=400, input_dim=16, seed=42).astype(np.float32)
x_t = torch.from_numpy(x_data)
teacher = TorchSensorAE(input_dim=16, hidden_dim=128, latent_dim=6)
opt = torch.optim.Adam(teacher.parameters(), lr=0.005)
for _ in range(55):
opt.zero_grad()
loss = F.mse_loss(teacher(x_t), x_t)
loss.backward()
opt.step()
teacher.eval()
unstruct = unstructured_magnitude_prune_mask(teacher, sparsity=0.80)
assert unstruct["actual_weight_sparsity"] >= 0.78
assert unstruct["dense_compression_ratio"] == pytest.approx(1.0)
assert unstruct["dense_bytes_saved_pct"] == pytest.approx(0.0)
student, struct_metrics = structured_width_prune_ae(teacher, keep_ratio=0.375)
assert struct_metrics["student_hidden"] == pytest.approx(48.0)
assert struct_metrics["memory_compression_ratio"] > 2.2
assert struct_metrics["flop_compression_ratio"] > 2.2
kd_metrics = distill_student_ae(
teacher, student, x_data, CompressionConfig(prune_ratio=0.625, kd_temperature=4.0, seed=42), epochs=60
)
assert kd_metrics["student_after_kd_mse"] < kd_metrics["student_before_kd_mse"]
# ---------------------------------------------------------------------------
# Test 10: INT8 PTQ Outlier Collapse (MinMax vs Percentile / MSE) & >= 3.0x Bundle
# ---------------------------------------------------------------------------
def test_10_int8_ptq_outlier_trap_minmax_vs_percentile_mse() -> None:
rng = np.random.default_rng(42)
calib = rng.normal(0.0, 0.6, size=(4000, 16)).astype(np.float32)
calib[rng.random(calib.shape) < 0.003] = 48.0
alpha_mm = calibrate_clipping_threshold(calib, "minmax")
alpha_pct = calibrate_clipping_threshold(calib, "percentile", percentile_q=99.5)
alpha_mse = calibrate_clipping_threshold(calib, "mse")
mm_res = evaluate_int8_sqnr(calib, alpha_mm, normal_bound=2.0)
pct_res = evaluate_int8_sqnr(calib, alpha_pct, normal_bound=2.0)
mse_res = evaluate_int8_sqnr(calib, alpha_mse, normal_bound=2.0)
assert pct_res["sqnr_db"] >= mm_res["sqnr_db"] + 10.0
assert mse_res["sqnr_db"] >= mm_res["sqnr_db"] + 10.0
assert pct_res["active_normal_bins"] > mm_res["active_normal_bins"] * 4.0
student = TorchSensorAE(input_dim=16, hidden_dim=48, latent_dim=6).eval()
bundle = compress_student_to_int8_bundle(
student,
rng.normal(0.0, 0.8, size=(256, 16)).astype(np.float32),
CompressionConfig(quant_calibration="percentile", percentile_q=99.5, seed=42),
)
assert bundle["compression_ratio"] >= 3.0
assert bundle["int8_bundle_bytes"] < bundle["fp32_weight_bytes"]
# ---------------------------------------------------------------------------
# Test 11: C-MAPSS Fleet Engine-ID GroupSplit (0 Overlap) vs Leaky Cycle Contrast
# ---------------------------------------------------------------------------
def test_11_cmapss_fleet_engine_group_split_zero_leakage_vs_leaky_cycle() -> None:
sim_cfg = FleetSimConfig(n_train_engines=16, n_cal_engines=8, n_test_engines=10, seed=42)
fleet = simulate_turbofan_fleet(sim_cfg)
split_data = split_fleet_by_engine_id(fleet, sim_cfg)
train_eids = set(split_data["train"]["engine_id"].tolist())
cal_eids = set(split_data["cal"]["engine_id"].tolist())
test_eids = set(split_data["test"]["engine_id"].tolist())
assert split_data["overlap_count"] == 0
assert train_eids.isdisjoint(cal_eids)
assert train_eids.isdisjoint(test_eids)
assert cal_eids.isdisjoint(test_eids)
assert split_data["regime_stats_fit_split"] == "train_healthy_only"
leak = run_leaky_cycle_split_contrast(fleet, cfg=sim_cfg, seed=42)
assert leak["leaky_shared_engine_count"] >= 10.0
assert leak["honest_shared_engine_count"] == 0.0
assert leak["leaky_cycle_rmse"] < leak["leaky_live_unseen_rmse"]
assert leak["leaky_cycle_rmse"] < leak["honest_engine_rmse"]
# ---------------------------------------------------------------------------
# Test 12: Stage 1 Healthy-Only Detector Calibration (PR-AUC, ECE, Bayes Cost)
# ---------------------------------------------------------------------------
def test_12_stage1_healthy_only_anomaly_cal_and_bayes_cost() -> None:
sim_cfg = FleetSimConfig(n_train_engines=18, n_cal_engines=10, n_test_engines=12, seed=42)
cost_cfg = PdMCostConfig(cost_fp_usd=800.0, cost_fn_usd=50_000.0)
fleet = simulate_turbofan_fleet(sim_cfg)
split_data = split_fleet_by_engine_id(fleet, sim_cfg)
detector = fit_stage1_healthy_detector(split_data, latent_dim=6, hidden_dim=48, epochs=45, seed=42)
eval_res = calibrate_and_threshold_bayes(detector, split_data, cost_cfg)
assert eval_res["pr_auc"] >= 0.85
assert eval_res["ece_10"] < 0.06
bayes_cost = eval_res["policies"]["bayes_optimal"]["total_cost_usd"]
std3_cost = eval_res["policies"]["naive_3std"]["total_cost_usd"]
p50_cost = eval_res["policies"]["symmetric_p50"]["total_cost_usd"]
assert bayes_cost < std3_cost
assert bayes_cost < p50_cost
# ---------------------------------------------------------------------------
# Test 13: Stage 2 Capped RUL (RUL_max=125) & NASA PHM08 Asymmetry
# ---------------------------------------------------------------------------
def test_13_stage2_capped_rul_and_nasa_phm08_asymmetry() -> None:
raw = np.array([200.0, 126.0, 125.0, 80.0, 0.0])
capped = cap_rul_targets(raw, rul_max=125)
assert np.allclose(capped, np.array([125.0, 125.0, 125.0, 80.0, 0.0]))
for d in (5.0, 15.0, 30.0):
late_score = nasa_phm08_score(np.array([50.0]), np.array([50.0 + d]))
early_score = nasa_phm08_score(np.array([50.0]), np.array([50.0 - d]))
assert late_score > early_score
sim_cfg = FleetSimConfig(n_train_engines=18, n_cal_engines=8, n_test_engines=10, seed=42)
fleet = simulate_turbofan_fleet(sim_cfg)
split_data = split_fleet_by_engine_id(fleet, sim_cfg)
s2 = fit_stage2_rul_predictor(split_data, rul_max=125, hidden_dim=48, epochs=55, seed=42)
assert s2["test_rul_rmse"] < 25.0
assert s2["late_life_rmse"] < 25.0
# ---------------------------------------------------------------------------
# Test 14: Stage 3 RCA Per-Sensor Attribution (>= 85% Top-3 Subsystem Hit Rate)
# ---------------------------------------------------------------------------
def test_14_stage3_rca_subsystem_attribution_ge_85pct() -> None:
assert sum(len(v) for v in SUBSYSTEM_SENSOR_MAP.values()) == 16
sim_cfg = FleetSimConfig(n_train_engines=18, n_cal_engines=8, n_test_engines=12, seed=42)
fleet = simulate_turbofan_fleet(sim_cfg)
split_data = split_fleet_by_engine_id(fleet, sim_cfg)
detector = fit_stage1_healthy_detector(split_data, latent_dim=6, hidden_dim=48, epochs=45, seed=42)
te = split_data["test"]
attr = compute_rca_sensor_attribution(detector["model"], te["x_scaled"], detector["healthy_err_std"])
rca = evaluate_rca_subsystem_hit_rate(
attr["combined_attr"], te["true_subsystem"], te["fault_mode"], te["is_imminent"]
)
assert rca["top_3_rca_hit_rate"] >= 0.85
assert rca["top_1_subsystem_acc"] >= 0.80
assert set(rca["by_fault_mode"].keys()) == {
"HPC_degradation",
"Fan_imbalance",
"Turbine_thermal_erosion",
}
# ---------------------------------------------------------------------------
# Test 15: End-to-End Compressed Edge Student & CLI Workbench Schema Validation
# ---------------------------------------------------------------------------
def test_15_compressed_edge_student_end_to_end_and_cli_workbench_schema(tmp_path: Path) -> None:
sim_cfg = FleetSimConfig(n_train_engines=14, n_cal_engines=8, n_test_engines=10, seed=42)
cost_cfg = PdMCostConfig()
fleet = simulate_turbofan_fleet(sim_cfg)
split_data = split_fleet_by_engine_id(fleet, sim_cfg)
s1_det = fit_stage1_healthy_detector(split_data, latent_dim=6, hidden_dim=64, epochs=40, seed=42)
s1_eval = calibrate_and_threshold_bayes(s1_det, split_data, cost_cfg)
s2_eval = fit_stage2_rul_predictor(split_data, rul_max=125, hidden_dim=64, epochs=50, seed=42)
edge = compress_and_evaluate_edge_pdm(
s1_det, s2_eval, s1_eval, split_data, CompressionConfig(prune_ratio=0.625, seed=42), epochs=40
)
assert edge["int8_compression_ratio"] >= 3.0
assert edge["pr_auc_drop"] <= 0.04
assert edge["int8_rul_rmse"] < 25.0
assert edge["int8_top_3_rca_hit_rate"] >= 0.85
assert edge["ort_latency_ms"] < 5.0
out_json = tmp_path / "lab07_quick.json"
proc = subprocess.run(
[
sys.executable,
str(LAB_ROOT / "scripts" / "run_lab_demo.py"),
"--seed",
"42",
"--quick",
"--output",
str(out_json),
],
cwd=str(LAB_ROOT),
capture_output=True,
text=True,
check=False,
)
assert proc.returncode == 0, f"CLI failed: {proc.stderr}"
payload = json.loads(out_json.read_text(encoding="utf-8"))
wb = payload["workbench_panels"]
assert len(wb["kpis"]) == 6
assert len(wb["bars"]) == 4
assert len(wb["tables"]) == 4
wb_text = json.dumps(wb, ensure_ascii=False)
assert "`" not in wb_text
assert "**" not in wb_text
assert "$" not in wb_text
# ---------------------------------------------------------------------------
# Test 16: Security AST Guard — Ban Unsafe Deserialization Imports Only
# ---------------------------------------------------------------------------
def test_16_security_only_ast_deserialization_guard() -> None:
py_files = sorted(
list((LAB_ROOT / "src").rglob("*.py"))
+ list((LAB_ROOT / "scripts").rglob("*.py"))
+ list((LAB_ROOT / "tests").rglob("*.py"))
)
assert len(py_files) >= 5
violations: list[str] = []
for fpath in py_files:
tree = ast.parse(fpath.read_text(encoding="utf-8"), filename=str(fpath))
for node in ast.walk(tree):
if isinstance(node, ast.Import):
for alias in node.names:
root_mod = alias.name.split(".", 1)[0]
if root_mod in FORBIDDEN_UNSAFE_IMPORTS:
violations.append(f"{fpath.name}: import {alias.name}")
elif isinstance(node, ast.ImportFrom) and node.module:
root_mod = node.module.split(".", 1)[0]
if root_mod in FORBIDDEN_UNSAFE_IMPORTS:
violations.append(f"{fpath.name}: from {node.module} import ...")
assert violations == [], f"Unsafe deserialization imports found: {violations}"
MSE trên dữ liệu đã quy tâm \(\mathbf{X}_{\text{col}} = \mathbf{U}\boldsymbol{\Sigma}\mathbf{V}^\top\) (\(\sigma_{d_z} > \sigma_{d_z+1}\)). Phát biểu nào ĐÚNG theo Định lý Bourlard–Kamp (1988) và kết quả Lab 07?6.07e-15 rad < 1e-3 rad, Test 02) nhưng có độ lệch trực giao 3.30.
Sparse Autoencoder (SAE) siêu đầy đủ (\(d_z > D_x\)) từ L1/KL cổ điển đến TopK + AuxK (OpenAI 2024), JumpReLU (DeepMind 2024) và Matryoshka (2025), nhận định nào ĐÚNG?L1 về 0 bằng cách thu nhỏ encoder và phóng đại decoder; L1 bóp biên độ (0.19 vs 1.03 của TopK, Test 03), còn AuxK hồi sinh latent chết và Matryoshka chống tách/hấp thụ đặc trưng.
Denoising Autoencoder (DAE) dưới nhiễu Gauss \(\tilde{\mathbf{x}} = \mathbf{x} + \boldsymbol{\varepsilon}\) (\(\boldsymbol{\varepsilon} \sim \mathcal{N}(\mathbf{0}, \sigma_{\text{noise}}^2 \mathbf{I})\)) và Contractive Autoencoder (CAE)?Test 04 đạt mức giảm MSE 3.80x / +5.8 dB). Với sigmoid, \(\sigma'(a_i) = h_i(1-h_i)\) nên chuẩn Frobenius bình phương là \(\sum_i [h_i(1-h_i)]^2 \|\mathbf{w}_{1,i}\|_2^2\).
Lab 07, vì sao mô hình VAE với bộ giải mã mạnh và \(\beta_{\text{VAE}} = 1.0\) tĩnh bị Posterior Collapse (AU = 0/6, KL = 0.002 nats), còn VQ-VAE không dùng EMA lại sụt giảm Perplexity (PPL) xuống 10.15?pathwise) với phương sai thấp hơn hẳn REINFORCE. Cyclical Annealing khởi động lại \(\beta\) về 0 kết hợp sàn Free Bits chặn gradient KL triệt tiêu z (Test 05), trong khi VQ-VAE EMA + dead-code reset và FSQ chống sụp đổ codebook (Test 06).
TorchSensorAE để suy luận trên cổng biên CPU (trong môi trường PyTorch 2.15+cpu không cài onnxscript). Lựa chọn triển khai và cảnh báo kỹ thuật nào ĐÚNG?CVE-2025-32434 chứng minh ngay cả weights_only=True trên PyTorch <= 2.5.1 vẫn bị RCE; safetensors triệt tiêu mã thực thi (Test 07). Trên PyTorch 2.15+cpu thiếu onnxscript, dynamo=True lỗi ModuleNotFoundError, còn dynamo=False xuất thành công với max_abs_diff = 3.81e-06 < 1e-4 (Test 08) nhưng chỉ vết theo nhánh tĩnh.
Lab 07 (Test 09, Test 10), điều gì xảy ra khi so sánh tỉa thưa phi cấu trúc 80% với Structured Width Pruning + FitNets KD + INT8 PTQ trên dữ liệu cảm biến chứa 0.3% xung nhiễu ±48.0 EMI?KL theo logit student tỷ lệ nghịch \(1/T_{\text{kd}}^2\) ở giới hạn nhiệt độ cao nên bắt buộc nhân \(T_{\text{kd}}^2\) (Test 09). Một xung nhiễu ±48 đẩy bước nhảy \(\Delta_q = 48/127 = 0.378\), phình phương sai làm tròn \(\Delta_q^2/12\) hàng nghìn lần (14.80 dB, 11 bins) trước khi được Percentile/MSE giải cứu (41.57–42.48 dB, 255 bins, Test 10).
Lab 07 (16 cảm biến, chi phí kiểm tra giả c_fp = 800 USD vs chi phí hỏng hóc bỏ sót c_fn = 50,000 USD), kết quả nào phản ánh ĐÚNG sự khác biệt giữa tách dữ liệu rò rỉ và đường ống Tầng 1 hiệu chuẩn theo Bayes?eng_bias của cùng động cơ (Test 11). Với \(c_{\text{FN}} = 62.5\, c_{\text{FP}}\), ngưỡng tối thiểu hóa rủi ro Bayes \(t^* = \frac{800}{800 + 50,000} = 0.01575\) cắt bỏ 28 -> 1 FN so với p = 0.50 (1,408,800 -> 123,600 USD) và giảm báo giả 231 -> 92 FP so với mean + 3*std (Test 12).
RUL Tầng 2 (RUL_max = 125), định vị nguyên nhân gốc rễ RCA Tầng 3 và nén Student INT8 ra Edge (Lab 07: Test 13, Test 14, Test 15), nhận định nào ĐÚNG?PHM08 phạt \(\exp(+d/10)-1\) cho dự báo trễ (\(d \ge 0\)) nặng hơn \(\exp(-d/13)-1\) cho dự báo sớm (Test 13). Chuẩn hóa theo \(\sigma_{j,\text{healthy}}^2\) ngăn cảm biến nhiễu nền lớn (s09_phi, s10_Wf) che khuất lỗi thật, đạt 100.0% Top-3 RCA ở cả FP32 lẫn INT8 biên (Test 14, Test 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 — Chứng minh Định lý Bourlard–Kamp & Bất biến GL(R) 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Viết \(\mathbf{B} = \mathbf{W}_2\mathbf{W}_1\mathbf{X}_{\text{col}}\) có hạng \(\le d_z\), áp dụng Định lý Eckart–Young–Mirsky (ch-02) suy ra tính duy nhất của \(\mathbf{X}_{d_z}\) khi \(\sigma_{d_z} > \sigma_{d_z+1}\), rồi biến đổi cơ sở \((\mathbf{R}^{-1}\mathbf{W}_1, \mathbf{W}_2\mathbf{R})\).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Gọi fit_linear_ae_numpy và compute_pca_basis trong autoencoders_and_compression.py (Test 02) để kiểm chứng góc không gian con < 1e-3 rad (6.07e-15 rad) và đo độ lệch trực giao orthogonality_deviation_fro.
Tiêu chí Đáp án & Số đối chứng
Linear AE khớp không gian con chính hàng đầu với góc 6.07e-15 rad và ae_mse == eckart_young_mse == 0.0074346, nhưng độ lệch trực giao bằng 3.30 chứng minh các trục ẩn bị xoay/lệch bởi \(\mathbf{R} \in \operatorname{GL}_{d_z}(\mathbb{R})\).
Bài tập 2 — Toán học Sparse AE: Chuẩn cột Giải mã, Thiên lệch L1 & TopK / JumpReLU 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Chứng minh nếu \(\|\mathbf{W}_{\text{dec},:,j}\|_2\) không bị chặn, phép đổi tỉ lệ \(\mathbf{W}_1 \leftarrow c\mathbf{W}_1, \mathbf{W}_2 \leftarrow \frac{1}{c}\mathbf{W}_2\) (\(c \to 0^+\)) giữ nguyên \(\hat{\mathbf{x}}\) nhưng ép \(\lambda_{\text{L1}}\|\mathbf{h}\|_1 \to 0\); tính soft-thresholding \(\hat{z}_j = z_j^* - \lambda_{\text{L1}}/2\).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy train_sparse_ae_comparison qua 3 chế độ 'l1', 'topk', 'jumprelu' (Test 03), đối chiếu recon_mse, mean_l0, dead_latent_fraction, và active_amplitude_ratio.
Tiêu chí Đáp án & Số đối chứng
L1 bóp biên độ hoạt động xuống 0.19 (recon_mse = 0.285), trong khi TopK đạt đúng \(L_0 = 3.0\), biên độ 1.03, tái tạo thấp nhất (0.058) và JumpReLU đạt biên độ 1.44 không co rút.
Bài tập 3 — Dẫn xuất ELBO, Gaussian KL, Tweedie DAE & Sửa Posterior Collapse 20%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Chứng minh \(\ln p_\theta(\mathbf{x}) = \operatorname{ELBO} + D_{\text{KL}}(q_\phi(\mathbf{z}|\mathbf{x}) \parallel p_\theta(\mathbf{z}|\mathbf{x}))\), tính tích phân từng phần cho \(D_{\text{KL}}\) Gauss chéo, và đạo hàm dưới dấu tích phân Gaussian kernel cho đồng nhất thức Tweedie của DAE.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Kiểm chứng fit_denoising_ae_numpy (Test 04), train_vae_collapse_vs_annealed (Test 05) và train_vqvae_ema_vs_no_ema (Test 06) trên các chỉ số AU, KL, PPL.
Tiêu chí Đáp án & Số đối chứng
DAE tăng SNR khử nhiễu 3.80x (+5.8 dB); Cyclical Annealing + Free Bits cứu VAE từ AU = 0 -> 6/6 (KL: 0.002 -> 1.09 nats); VQ-VAE EMA + Dead-Code Reset nâng PPL từ 10.15 -> 14.38 (16/16 mã sống).
Bài tập 4 — Chuỗi cung ứng Safetensors/ONNX, Chứng minh T_kd^2 & Giải cứu Outlier INT8 20%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Khai triển Taylor bậc 1 của \(\exp(z/T_{\text{kd}})\) tại \(T_{\text{kd}} \gg |z|\) để thu về độ dốc \(\frac{1}{C T_{\text{kd}}^2}[(z_S-\bar{z}_S)-(z_T-\bar{z}_T)]\); tích phân \(\int_{-\Delta_q/2}^{\Delta_q/2} (u^2/\Delta_q)\,du = \Delta_q^2/12\).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy save_state_dict_safetensors, export_and_verify_onnx_parity (dynamo=False), unstructured_magnitude_prune_mask, structured_width_prune_ae, distill_student_ae, và compress_student_to_int8_bundle (Test 07..Test 10).
Tiêu chí Đáp án & Số đối chứng
safetensors đạt sai số 0.00e+00; ONNX (dynamo=False) ORT CPU đạt 3.81e-06 (0.020 ms); tỉa phi cấu trúc 80% giữ 1.00x (0% tiết kiệm), còn Struct + KD + INT8 đạt 3.43x INT8 (9.09x tổng) và Percentile 99.5% tăng SQNR từ 14.80 -> 41.57 dB (+26.8 dB).
Bài tập 5 — Kiểm toán Rò rỉ Engine-ID & Chứng minh Ngưỡng Bayes Chi phí Bất đối xứng 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Thiết lập kỳ vọng rủi ro \(\mathbb{E}[\text{Cost}(a=1|\mathbf{x})] \le \mathbb{E}[\text{Cost}(a=0|\mathbf{x})]\) với \(c_{\text{FP}} = 800, c_{\text{FN}} = 50,000\) để suy ra \(t^* = \frac{c_{\text{FP}}}{c_{\text{FP}}+c_{\text{FN}}}\); kiểm tra phân tách tập engine_id.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy split_fleet_by_engine_id, run_leaky_cycle_split_contrast (Test 11) và fit_stage1_healthy_detector + calibrate_and_threshold_bayes (Test 12).
Tiêu chí Đáp án & Số đối chứng
Leaky Cycle Split làm lộ 45 động cơ dùng chung (8.92 -> 34.23 RMSE live), trong khi Engine-ID GroupSplit đạt 0 trùng lặp (Honest 10.36); ngưỡng Bayes t* = 0.0157 (123,600 USD) hạ -33.1% so với mean+3*std (184,800 USD) và -91.2% so với p = 0.50 (1,408,800 USD).
Bài tập 6 — Đường ống 3 Tầng Anomaly -> RUL (PHM08) -> RCA & Kiểm định Toàn trình (16/16 Pytest) 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
So sánh độ dốc phải và trái của \(s_i(d_i^{\text{rul}})\) theo chuẩn PHM08, thiết kế công thức kết hợp phần dư chuẩn hóa và gradient đầu vào quy gán về 4 phân hệ (Fan, HPC, Combustor, HPT).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy fit_stage2_rul_predictor (Test 13), evaluate_rca_subsystem_hit_rate (Test 14), compress_and_evaluate_edge_pdm (Test 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
RUL_max = 125 đạt RMSE = 7.24 (PHM08 = 2,698 vs 4,639 không cắt ngọn); Stage 3 RCA đạt 100.0% Top-3 Hit Rate trên cả 3 chế độ lỗi; Edge INT8 đạt 3.36x INT8 (11.23x tổng), PR-AUC = 0.988, RUL = 7.23, RCA = 100.0%, 0.017 ms ORT CPU, và 16/16 pytest đạt xanh.