Chương 02 — Đại số Tuyến tính, Giải tích Ma trận & Tối ưu hóa cho Machine Learning
Từ Bốn không gian con, Eckart–Young SVD, Numerator-Layout Matrix Calculus, Tích phân/Đổi biến Flows đến Autodiff JVP/VJP/HVP, rSVD/LoRA/DoRA/PiSSA/MLA, AdamW & Muon (Newton–Schulz / Moonlight).
Unit ID:
T1-P1-U02
Track & Part: Track 1 (DSAI) — Part 1: Mathematical Foundations, Statistical Inference & Causal Decision Science (part-01-math-stats-and-causal)
Truy xuất Giáo trình Gốc (R27): Lesson 2 (Math for ML: Linear Algebra — Scalars, vectors, matrices and operations; Vector & matrix norms; Special matrices & vectors; Eigenvalues & eigenvectors; Norms & eigen decomposition; Calculus — Differentiation of univariate functions; Partial derivatives & gradients; Integration; Optimization) (Phần Probability & Statistics củaR27được phủ trọn vẹn tại Chương 03T1-P1-U03)
Bài thực hành Song hành (Lab 02):labs/ch02-linalg-and-optimizers-workbench/(linalg_lab)
Mục tiêu Học tập (Learning Objectives)#
Sau khi hoàn thành trọn vẹn học phần T1-P1-U02 (Chương 02 và linalg_lab), học viên có đủ năng lực để:
- Chứng minh & Phân tích Cấu trúc Ma trận Nền tảng (Mathematical Rigor): Suy diễn trọn vẹn Định lý Hạng–Không gian hạch (Rank–Nullity), Phân tách Tổng trực tiếp Trực giao của Bốn Không gian Con Cơ bản (Four Fundamental Subspaces), Đối ngẫu Phổ–Hạt nhân (Spectral–Nuclear Duality), tính xác định dương của phân rã Cholesky (\(\frac{1}{3}n^3\) FLOPs), phép chéo hóa ma trận Tuần hoàn (Circulant) trong \(O(n \log n)\) bằng DFT, Định lý Phổ Thực (Real Spectral Theorem), và chứng minh đầy đủ Định lý Eckart–Young–Mirsky theo cả chuẩn phổ lẫn chuẩn Frobenius.
- Giải tích Ma trận & Tích phân Chuẩn xác (Analytical + Numerical Rigor): Vận dụng quy ước Numerator Layout (Bố cục Tử số / Jacobian Layout) và vi phân ma trận (\(df = \operatorname{tr}((\nabla_{\mathbf{X}} f)^\top d\mathbf{X})\)) để suy diễn gradient bình phương tối thiểu, vi phân ma trận nghịch đảo và công thức Jacobi \(\nabla_{\mathbf{X}} \ln \det \mathbf{X} = \mathbf{X}^{-\top}\); suy diễn tích phân Gaussian đa biến, bộ ước lượng đạo hàm điểm số
REINFORCE, Định lý Đổi biến Đa biến cho Normalizing Flows, và chứng minh vì sao Monte Carlo \(O(N^{-1/2})\) thắng cầu phương lưới (Quadrature) \(O(N^{-2/d})\) khi \(d > 4\). - Thiết kế Hệ thống Autodiff & Bộ giải Ổn định Số học (Systems Rigor): Đối chiếu cơ chế lan truyền xuôi
JVPvà lan truyền ngượcVJP, chiến lược lưu điểm kiểm tra chọn lọcSAC(Selective Activation Checkpointing) tối ưu min-cut, và phép nhân Hessian–vectorHVPchính xác của Pearlmutter (Forward-over-Reverse); triệt tiêu sụp đổ chữ số \(\kappa(\mathbf{X}^\top \mathbf{X}) = \kappa(\mathbf{X})^2\) bằng HouseholderQR/SVD, chống tràn sốlog(det(K))bằngslogdet/Cholesky jitter, và khắc phục nhiễu hiệp phương sai bằngLedoit–Wolf. - Suy diễn & Triển khai Kiến trúc Hạng thấp và Bộ tối ưu 2024–2026 (Frontier Engineering): Làm chủ thuật toán Randomized SVD (
HMT+CholeskyQR2), kiến trúcLoRA/DoRA/PiSSA/GaLore, cơ chế hấp thụ trọng sốMLAcủa DeepSeek, phân rã khốiMamba-2 SSD, suy giảm trọng số tách rờiAdamW, và phép trực giao hóa đa thức bậc 5 Newton–Schulz củaMuonkèm hệ số chuẩn hóaMoonlight\(0.2\sqrt{\max(d_{\text{out}}, d_{\text{in}})}\) dưới mô hình Roofline GPU (GEMVvs.GEMM) và độ chính xác hỗn hợpbf16/fp8. - Kiểm chứng Đầu–Cuối bằng Mã nguồn Pure-NumPy (
linalg_lab): Tự xây dựng, đo kiểm và vượt qua toàn bộ15/15kiểm thử tự độngpytesttrên cả ba mô-đunsvd_and_lowrank.py,calculus_and_autodiff.py,optimizers.pyvà CLIscripts/run_lab_demo.py(lõi tham chiếu thuần NumPy/Pandas không lệ thuộcscipy/scikit-learn/torch, kèm rào chắn AST chỉ bảo mật chống giải tuần tự hóapickle/joblib).
Tình huống Mở đầu: Bốn Thảm họa Toán học Phá vỡ Pipeline ML Thực tế#
Trong kỹ thuật học máy sản xuất (production ML), phần lớn sự cố sập hệ thống không xuất phát từ lỗi cú pháp mà bắt nguồn từ việc áp dụng máy móc các công thức đại số tuyến tính và giải tích lý thuyết vào phần cứng dấu chấm động hữu hạn (IEEE-754 floating-point):
- Sụp đổ Độ chính xác trong Phương trình Chuẩn (
Normal Equations Collapse): Một pipeline hồi quy đa biến có hiện tượng đa cộng tuyến mức vừa phải (\(\kappa_2(\mathbf{X}) = 10^8\)) tính trọng số bằng công thức sách giáo khoanp.linalg.inv(X.T @ X) @ X.T @ y. Phép nhân \(\mathbf{X}^\top \mathbf{X}\) bình phương số điều kiện lên \(\kappa_2(\mathbf{X}^\top \mathbf{X}) = 10^{16}\), thổi bay toàn bộ~16chữ số thập phân có nghĩa củafloat64, khiến nghiệm trôi ngẫu nhiên hoặc văng lỗiLinAlgError: Singular matrix. - Tràn dưới
det(K)& Thảm họa Làm trắng Không cắt cụt (Untruncated Whitening Collapse): Khi tính log-likelihood cho Gaussian Process hoặc Normalizing Flow trên không gian \(d = 500\) chiều bằngnp.log(np.linalg.det(K))với trị riêng trung bình \(\bar{\lambda} = 0.2\), giá trị \(\det(\mathbf{K}) \approx 0.2^{500} \approx 10^{-349.5}\) vượt dưới ngưỡng subnormal củafloat64(4.94e-324) và trả vềlog(0.0) = -inf. Song song đó, một đội ngũ tìm kiếm ngữ nghĩa áp dụng ZCA whitening toàn phần lên vector BERT 768 chiều đã vô tình nhân các chiều đuôi nhiễu (\(\lambda_i \approx 10^{-5}\)) với hệ số \(1/\sqrt{\lambda_i} \approx 316\times\), làm sụt giảm mạnh độ chính xác xếp hạng truy xuất. - Tràn bộ nhớ HBM trong Autodiff & Kiểm định Sai phân Hữu hạn Sai bước: Kiểm tra đạo hàm bằng sai phân hữu hạn với bước quá nhỏ (\(\epsilon = 10^{-14}\)) gây triệt tiêu thảm khốc (catastrophic cancellation) mất
14/16chữ sốfloat64, trong khi huấn luyện LLM sâu hàng trăm tỷ tham số không cóSAC(Selective Activation Checkpointing) khiến băng thông/dung lượng HBM80 GBtràn ngập ngay từ batch đầu tiên. - Phân kỳ
MuonNgây thơ & Bẫy Cộng dồn 14-bit HopperFP8: Áp dụng phép trực giao hóa phổ \(\mathbf{U}\mathbf{V}^\top\) củaMuonlên toàn bộ mô hình (bao gồm vector 1DRMSNorm, bảng nhúng từembed_tokensvàlm_head) mà thiếu suy giảm trọng số tách rời (decoupled weight decay) và hệ số tỷ lệMoonlight\(0.2\sqrt{\max(d_{\text{out}}, d_{\text{in}})}\), hoặc thực hiện phép nhân ma trậnFP8 WGMMAtrên phần cứng NVIDIA Hopper mà không thúc đẩy tổng riêng phần vềfp32ngoài bộ cộng dồn 14-bit cố định, sẽ đẩy chuẩn kích hoạt và loss phân kỳ sau vài nghìn bước với chi phí đốt GPU hàng trăm nghìn đến hàng triệu đô-la ($100K–$2.5M).
Bảng Truy xuất Giáo trình Gốc sang Chuẩn SOTA 2026 (Unit T1-P1-U02)#
Nội dung Gốc (01-track-dsai-raw-curriculum.md, Dòng R27) |
Nâng cấp Chuẩn SOTA 2026 (ch-02) |
Mục trong Chương 02 | Mô-đun & Kiểm thử (linalg_lab) |
|---|---|---|---|
| Linear Algebra — Scalars, vectors, matrices and operations | Hệ phân cấp đại số, tích ngoài/Hadamard/Kronecker (\(\operatorname{vec}(\mathbf{A}\mathbf{X}\mathbf{B})\) cho K-FAC), einsum & bẫy thứ tự co \(O(Ld^2)\) vs. \(O(L^2 d)\), BLAS-2 gemv vs. BLAS-3 gemm, Bốn Không gian Con Cơ bản, Rank–Nullity & Phép chiếu trực giao \(\mathbf{Q}\mathbf{Q}^\top\) |
Trụ cột 1 (§1.1) + Trụ cột 2 (§2.4) + Mermaid 1 | svd_and_lowrank.py (compute_matrix_norms), Test 1 |
| Linear Algebra — Vector & matrix norms | Chuẩn \(\ell_1, \ell_2, \ell_\infty\) & hình học quả cầu đơn vị, chứng minh Young/Hölder/Cauchy–Schwarz/Minkowski, Chuẩn Đối ngẫu (\((\|\cdot\|_p)_* = \|\cdot\|_q\)), bất đẳng thức tương đương chuẩn ma trận, Đối ngẫu Phổ–Hạt nhân (nền tảng Muon) |
Trụ cột 1 (§1.2) + Trụ cột 2 (§2.3) | svd_and_lowrank.py (compute_matrix_norms), Test 1 |
| Linear Algebra — Special matrices & vectors | Ma trận SPD/Cholesky (\(\frac{1}{3}n^3\) FLOPs + chứng minh phần bù Schur), Trực giao (\(\kappa_2=1\)), Phép chiếu (\(\lambda\in\{0,1\}\)), Hạng thấp, Đường chéo/Tam đường chéo (\(O(n)\)), Chéo hóa DFT \(O(n\log n)\) cho Ma trận Tuần hoàn & Toeplitz, slogdet + jitter, Ledoit–Wolf |
Trụ cột 1 (§1.3) + Trụ cột 2 (§2.1, §2.4) + Trụ cột 3 (§3.1, §3.4) | svd_and_lowrank.py (circulant_matvec_fft, safe_logdet_cholesky, ledoit_wolf_shrinkage), Tests 2, 3, 6 |
| Linear Algebra — Eigenvalues & eigenvectors | Thương số Rayleigh & điểm dừng, Định lý Phổ Thực (chứng minh biến phân + quy nạp trên \(\mathbb{R}\)), Định lý Min-Max Courant–Fischer, phổ nhiễu Marchenko–Pastur (\(\lambda_\pm = \sigma^2(1\pm\sqrt{c})^2\)), tính dị hướng BERT & truncated whitening | Trụ cột 1 (§1.4) + Trụ cột 3 (§3.1 Case 4, 5) | svd_and_lowrank.py (ledoit_wolf_shrinkage), Test 6 |
| Linear Algebra — Norms & eigen decomposition | Full/Thin/Compact SVD, chứng minh trọn vẹn Eckart–Young–Mirsky (Phổ qua Rank–Nullity + Frobenius qua bổ đề Weyl), giả nghịch đảo \(\mathbf{A}^+\), sụp đổ \(\kappa_2(\mathbf{X}^\top\mathbf{X})=\kappa_2(\mathbf{X})^2\) vs. QR/SVD, Randomized SVD (HMT + CholeskyQR2), LoRA/DoRA/PiSSA/GaLore, DeepSeek MLA, Mamba-2 SSD |
Trụ cột 1 (§1.4) + Trụ cột 2 (§2.1, §2.2) + Trụ cột 3 (§3.1, §3.2) + Widget svd-lora-explorer |
svd_and_lowrank.py (eckart_young_approximation, randomized_svd, pissa_initialize, dora_effective_weight, benchmark_lora_dora_pissa_adaptation, compare_normal_eq_vs_qr_svd), Tests 4, 5, 6 |
| Calculus — Differentiation of univariate functions | Đạo hàm hàm kích hoạt (\(\sigma'\le 1/4\), \(\tanh'\), \(\operatorname{softplus}'\)), khai triển Taylor 1D/đa biến, bước tối ưu sai phân trung tâm float64 (\(\epsilon^* \approx \varepsilon_{\text{mach}}^{1/3} \approx 6\times 10^{-6}\)) |
Trụ cột 1 (§1.5) + Trụ cột 2 (§2.1) + Trụ cột 3 (§3.4) | calculus_and_autodiff.py (central_diff_grad_check), Test 8 |
| Calculus — Partial derivatives & gradients | Quy ước Numerator Layout (\(\mathbf{J}_{\mathbf{f}}\in\mathbb{R}^{m\times n}\), \(\nabla_{\mathbf{x}}f\) bảo toàn hình dạng), Vi phân ma trận (\(df=\operatorname{tr}((\nabla_{\mathbf{X}}f)^\top d\mathbf{X})\)), công thức Jacobi \(\nabla_{\mathbf{X}}\ln\det\mathbf{X}=\mathbf{X}^{-\top}\), Autodiff JVP vs. VJP, SAC checkpointing, Pearlmutter HVP (Forward-over-Reverse) |
Trụ cột 1 (§1.5) + Trụ cột 2 (§2.1) + Mermaid 2 + Widget conditioning-jacobian-explorer |
calculus_and_autodiff.py (DualArray, ReverseTensor, jvp, vjp, hvp_forward_over_reverse, compute_full_jacobian_*, simulate_checkpointing_memory), Tests 7, 8, 9 |
| Calculus — Integration | FTC & kỳ vọng độ đo, Quy tắc Leibniz & Đẳng thức Điểm số REINFORCE, Tích phân Gaussian 1D & Đa biến (\(Z = (2\pi)^{d/2}\sqrt{\det\boldsymbol{\Sigma}}\)), Đổi biến Đa biến (Normalizing Flows), Cầu phương \(O(N^{-2/d})\) vs. Monte Carlo \(O(N^{-1/2})\) |
Trụ cột 1 (§1.6) + Trụ cột 2 (§2.1) | calculus_and_autodiff.py (triangular_flow_log_prob, compare_quadrature_vs_monte_carlo), Test 9 |
| Calculus — Optimization | Tính lồi, \(L\)-trơn, \(\mu\)-lồi mạnh, \(\mu\)-PL, Bổ đề Giảm, GD, Heavy-Ball, Nesterov, Newton, L-BFGS 2 vòng, Điều kiện KKT & Phép chiếu Simplex dạng đóng, AdamW, Muon Newton–Schulz bậc 5 + Moonlight RMS scaling, SOAP, Schedule-Free, ổn định bf16/fp8 |
Trụ cột 1 (§1.7) + Trụ cột 2 (§2.3, §2.4) + Trụ cột 3 (§3.1–§3.4) + Mermaid 3 + Widget optimizer-trajectory-arena |
optimizers.py (project_onto_simplex, verify_simplex_kkt, GradientDescent, LBFGS, AdamW, zeropower_via_newtonschulz5, Muon, HybridMuonAdamW, ScheduleFreeAdamW, verify_bf16_stagnation_vs_fp32_master), Tests 10, 11, 12, 13 |
(Tham chiếu chéo R27: Prob & Stats) |
(Không gian xác suất, Bayes, phân phối, kiểm định thống kê, Conformal Prediction, Sequential A/B) | Phủ toàn bộ tại Chương 03 (T1-P1-U03) |
Kiểm chứng tại Lab Chương 03 |
Bảng Ký hiệu Toán học Thống nhất (Unified Notation Reference)#
| Ký hiệu | Miền / Kiểu | Định nghĩa Chuẩn hóa Xuyên suốt Chương 02 & linalg_lab |
Quy ước Phân biệt Bắt buộc | Ký hiệu Mã nguồn (linalg_lab) |
|---|---|---|---|---|
| \(\mathbf{A} \in \mathbb{R}^{m \times n}\) | Ma trận tổng quát | Ma trận thực (\(m\) hàng, \(n\) cột), hạng \(r \le \min(m, n)\) | Phân biệt với trọng số neural \(\mathbf{W}\) | matrix, A |
| \(\mathbf{x} \in \mathbb{R}^n\) | Vector cột | Vector cột chuẩn (\(n \times 1\)); vector hàng viết \(\mathbf{x}^\top\) | \(\mathbf{x}_t\) dùng cho bước lặp vector | x, vec |
| \(\mathbf{W} \in \mathbb{R}^{d_{\text{out}} \times d_{\text{in}}}\) | Ma trận trọng số | Trọng số tầng tuyến tính (\(\mathbf{y} = \mathbf{W}\mathbf{x}\)); LoRA \(\mathbf{B}\mathbf{A}\) với \(\mathbf{B}\in\mathbb{R}^{d_{\text{out}}\times r}, \mathbf{A}\in\mathbb{R}^{r\times d_{\text{in}}}\) |
Không dùng \(A\times B\) để tránh trùng nhân tố LoRA | weight, W, B, A |
| \(\mathbf{X} \in \mathbb{R}^{N_{\text{obs}} \times d}\) | Ma trận thiết kế | Ma trận đặc trưng hồi quy (\(N_{\text{obs}}\) mẫu, \(d\) chiều) | Tránh nhầm với ma trận biến \(\mathbf{X}\) trong vi phân | X |
| \(\mathcal{C}(\mathbf{A}), \mathcal{N}(\mathbf{A})\) | Không gian con | Không gian cột (\(\subseteq \mathbb{R}^m\), bậc \(r\)) & Không gian hạch (null space \(\subseteq \mathbb{R}^n\), bậc \(n-r\)) | Hàng \(\mathcal{C}(\mathbf{A}^\top)\), không gian hạch trái \(\mathcal{N}(\mathbf{A}^\top)\) | — |
| \(\mathbf{J}_{\mathbf{f}}(\mathbf{x}) \in \mathbb{R}^{m \times n}\) | Ma trận Jacobian | Numerator Layout: \([\mathbf{J}_{\mathbf{f}}(\mathbf{x})]_{ij} = \frac{\partial f_i}{\partial x_j} = \frac{\partial \mathbf{f}}{\partial \mathbf{x}^\top}\) | Tuyệt đối không dùng Denominator Layout | jacobian |
| \(\nabla_{\mathbf{x}} f(\mathbf{x}) \in \mathbb{R}^n\) | Gradient | Gradient cột bảo toàn hình dạng \((\frac{\partial f}{\partial \mathbf{x}^\top})^\top\); ma trận \(\nabla_{\mathbf{X}}f\) qua \(df=\operatorname{tr}((\nabla_{\mathbf{X}}f)^\top d\mathbf{X})\) | Phân biệt với Jacobian hàng \(\mathbf{J}_f \in \mathbb{R}^{1\times n}\) | grad, analytic_grad |
| \(\mathbf{H}_f(\mathbf{x}) \in \mathbb{R}^{n \times n}\) | Ma trận Hessian | Ma trận đối xứng đạo hàm bậc hai \([\mathbf{H}_f]_{ij} = \frac{\partial^2 f}{\partial x_i \partial x_j}\) | — | hessian, hvp (H @ v) |
| \(\sigma_1 \ge \dots \ge \sigma_r > 0\) | \(\mathbb{R}_{>0}\) | Giá trị kỳ dị dương từ SVD \(\mathbf{A} = \mathbf{U}\boldsymbol{\Sigma}\mathbf{V}^\top\) | Khác với hàm kích hoạt sigmoid \(\sigma(z)\) | singular_values (s) |
| \(\kappa_2(\mathbf{A}), \kappa\) | \([1, \infty]\) | Số điều kiện phổ \(\frac{\sigma_{\max}(\mathbf{A})}{\sigma_{\min}(\mathbf{A})}\); trong tối ưu \(\kappa := L/\mu\) | \(\kappa_2(\mathbf{X}^\top\mathbf{X}) = \kappa_2(\mathbf{X})^2\) | condition_number, kappa |
| \(\|\mathbf{A}\|_F, \|\mathbf{A}\|_2, \|\mathbf{A}\|_*\) | \(\mathbb{R}_{\ge 0}\) | Chuẩn Frobenius \(\sqrt{\sum\sigma_i^2}\), Phổ \(\sigma_1\), Hạt nhân \(\sum_{i=1}^r \sigma_i\) | Chuẩn đối ngẫu vector cũng ký hiệu \(\|\cdot\|_*\) | frobenius_norm, spectral_norm, nuclear_norm |
| \(\mathbf{A}_k, \mathbf{A}^+\) | Ma trận | Xấp xỉ hạng \(k\) Eckart–Young \(\sum_{i=1}^k \sigma_i \mathbf{u}_i\mathbf{v}_i^\top\); Giả nghịch đảo \(\mathbf{V}_r\boldsymbol{\Sigma}_r^{-1}\mathbf{U}_r^\top\) | — | approx_matrix, pinv |
| \(L, \mu, \text{PL}\) | \(\mathbb{R}_{>0}\) | Hằng số Lipschitz gradient (\(L\)), lồi mạnh (\(\mu \le \lambda_{\min}(\mathbf{H})\)), hằng số PL |
Động lượng dùng \(\beta_{\text{mom}} / \mu_{\text{mom}}\); trung bình \(\boldsymbol{\mu}\) | L, mu, kappa |
| \((a, b, c)\) | Bộ hằng số bậc 5 | Đa thức lẻ bậc 5 Jordan \(\phi(s) = as + bs^3 + cs^5\) với \((3.4445, -4.7750, 2.0315)\) | — | NS5_COEFFS = (3.4445, -4.7750, 2.0315) |
| \(\mathbf{O}_t, \text{scale}_{\text{RMS}}\) | Ma trận, \(\mathbb{R}_{>0}\) | Bước trực giao \(\operatorname{NS}_5(\tilde{\mathbf{G}}_t)\); hệ số RMS Moonlight \(0.2\sqrt{\max(d_{\text{out}}, d_{\text{in}})}\) | PyTorch 2.9 match_rms_adamw |
rms_scale |
| \(\Delta^{n-1}, \Pi_{\Delta^{n-1}}(\mathbf{y})\) | Tập, Ánh xạ | Đơn hình xác suất \(\{\mathbf{p} \ge \mathbf{0}: \sum p_i = 1\}\); phép chiếu \((y_i - \nu^*)_+\) | Nhân tử đối ngẫu \(\nu^*\) | project_onto_simplex |
| \(\operatorname{JVP}, \operatorname{VJP}, \operatorname{HVP}\) | Toán tử | Đẩy xuôi \(\mathbf{J}_f\dot{\mathbf{x}}\); kéo ngược \(\mathbf{J}_f^\top\bar{\mathbf{y}}\); Hessian–vector \(\mathbf{H}_f\mathbf{v}\) | — | jvp, vjp, hvp_forward_over_reverse |
| \(k, p_{\text{ov}}, q\) | \(\mathbb{N}, \mathbb{N}_{\ge 0}, \mathbb{N}_{\ge 0}\) | Hạng mục tiêu \(k\), phần lấy dư rSVD \(p_{\text{ov}} \in [5, 10]\), số vòng lũy thừa \(q \in \{0,1,2\}\) | Bề rộng phác thảo \(\ell = k + p_{\text{ov}}\) | rank_k, oversampling, n_power_iter |
| \(p_{\text{assets}}, n_{\text{bars}}, c\) | \(\mathbb{N}, \mathbb{N}, \mathbb{R}_{>0}\) | Số tài sản danh mục \(p_{\text{assets}}\), số thanh lợi suất \(n_{\text{bars}}\), tỷ số \(c = p_{\text{assets}}/n_{\text{bars}}\) | Tách bạch khỏi \(p_{\text{ov}}\) và chỉ số Hölder \(p\) | returns shape (n_bars, p_assets) |
| \(\text{AI}, I^*, \varepsilon_{\text{mach}}\) | \(\mathbb{R}_{>0}\) | Cường độ số học (\(\text{FLOP/B}\)), điểm gãy Roofline \(P_{\max}/B_{\max}\), sai số làm tròn | float64: \(2^{-53}\); bf16: \(2^{-7}\) |
eps |
Trụ cột 1 — Nền tảng Toán học & Giải tích Ma trận từ Nguyên lý Gốc (First-Principles Mathematical & Theoretical Rigor)#
1.1 Không gian Vector, Tensor, einsum & Bốn Không gian Con Cơ bản (Vectors, Tensors, einsum & Four Fundamental Subspaces)#
Phân cấp Đại số & Bốn Góc nhìn Phép nhân Ma trận#
Mọi cấu trúc dữ liệu trong học sâu đều nằm trong một hệ phân cấp đa tuyến tính (multilinear algebraic hierarchy):
- Vô hướng (
Scalar, tensor bậc \(0\)): \(a \in \mathbb{R}\). - Vector (
Vector, tensor bậc \(1\)): Quy ước mặc định là vector cột \(\mathbf{x} = (x_1, \dots, x_n)^\top \in \mathbb{R}^n\), vector hàng viết tường minh \(\mathbf{x}^\top \in \mathbb{R}^{1 \times n}\). - Ma trận (
Matrix, tensor bậc \(2\)): \(\mathbf{A} \in \mathbb{R}^{m \times n}\) gồm phần tử \(A_{ij}\), các cột \(\mathbf{a}_j \in \mathbb{R}^m\) (\(j=1,\dots,n\)), và các hàng \(\tilde{\mathbf{a}}_i^\top \in \mathbb{R}^{1 \times n}\) (\(i=1,\dots,m\)). Đối với tầng tuyến tính mạng neural \(\mathbf{y} = \mathbf{W}\mathbf{x}\), ta khóa kích thước \(\mathbf{W} \in \mathbb{R}^{d_{\text{out}} \times d_{\text{in}}}\). - Tensor bậc cao (
Higher-Order Tensor, bậc \(K\)): \(\boldsymbol{\mathcal{T}} \in \mathbb{R}^{d_1 \times d_2 \times \dots \times d_K}\), ví dụ tensor kích hoạt Multi-Head Attention[B, H, L, d_h].
Từ các đối tượng này hình thành các phép nhân nền tảng với đặc trưng phần cứng rất khác nhau:
- Tích vô hướng (
Inner / Dot Product): \(\langle \mathbf{u}, \mathbf{v} \rangle = \mathbf{u}^\top \mathbf{v} = \sum_{i=1}^n u_i v_i\) tốn \(2n - 1 \approx 2n\) FLOPs nhưng phải đọc \(2n\) số từ bộ nhớ, cho cường độ số học \(\text{AI} \approx 0.125\text{ FLOP/B}\) ởfloat64— bị trói chặt bởi băng thông bộ nhớ (memory-bandwidth-bound). - Tích ngoài (
Outer Product): \(\mathbf{u}\mathbf{v}^\top \in \mathbb{R}^{m \times n}\) với \((\mathbf{u}\mathbf{v}^\top)_{ij} = u_i v_j\) tạo ra ma trận có \(\operatorname{rank}(\mathbf{u}\mathbf{v}^\top) \le 1\). - Tích Hadamard (
Element-Wise Product): \((\mathbf{A} \odot \mathbf{B})_{ij} = A_{ij} B_{ij}\) thực hiện \(mn\) phép nhân giao hoán, kết hợp. - Tích Kronecker (
Kronecker Product): Cho \(\mathbf{A} \in \mathbb{R}^{m \times n}\) và \(\mathbf{B} \in \mathbb{R}^{p \times q}\), ma trận khối \(\mathbf{A} \otimes \mathbf{B} \in \mathbb{R}^{mp \times nq}\) đặt khối \((i, j)\) bằng \(A_{ij}\mathbf{B}\). Đẳng thức vector hóa (vectorization identity) tối quan trọng cho các bộ tối ưu bậc hai nhưK-FACvàSOAPlà:
- Nhân Ma trận–Vector (
BLAS-2 gemv) vs. Nhân Ma trận–Ma trận (BLAS-3 gemm): Phép \(\mathbf{y} = \mathbf{A}\mathbf{x}\) (gemv) tốn \(2mn\) FLOPs nhưng phải đọc toàn bộ \(mn + n\) phần tử chỉ dùng một lần (\(\text{AI} \le 0.25\text{ FLOP/B}\) ởfloat64, \(\le 0.5\) ởfloat32) — đây là nguyên nhân giải mã tự hồi quy (autoregressive decode) từng token bị nghẽn băng thông HBM. Ngược lại, \(\mathbf{C} = \mathbf{A}\mathbf{B}\) (gemm, \(\mathbf{A}\in\mathbb{R}^{m\times k}, \mathbf{B}\in\mathbb{R}^{k\times n}\)) thực hiện \(2mkn\) FLOPs trên tổng lượng dữ liệu \(O(mk + kn + mn)\), đạt \(\text{AI} = \Theta\!\left(\frac{mkn}{mk+kn+mn}\right)\), chuyển sang chế độ compute-bound và bão hòa Tensor Cores trong pha prefill và training.
Có bốn góc nhìn tương đương của phép nhân \(\mathbf{C} = \mathbf{A}\mathbf{B}\), mỗi góc nhìn giải thích một công nghệ học máy cốt lõi:
- Theo từng phần tử (Inner Products): \(C_{ij} = \tilde{\mathbf{a}}_i^\top \mathbf{b}_j\).
- Tổ hợp Không gian Cột (Column-Space Combination): Cột \(j\) của \(\mathbf{C}\) là \(\mathbf{c}_j = \mathbf{A}\mathbf{b}_j = \sum_{l=1}^k B_{lj}\mathbf{a}_l \in \mathcal{C}(\mathbf{A})\).
- Tổ hợp Không gian Hàng (Row-Space Combination): Hàng \(i\) của \(\mathbf{C}\) là \(\tilde{\mathbf{c}}_i^\top = \tilde{\mathbf{a}}_i^\top \mathbf{B} = \sum_{l=1}^k A_{il}\tilde{\mathbf{b}}_l^\top \in \mathcal{C}(\mathbf{B}^\top)\).
- Tổng các tích ngoài hạng 1 (Sum of Rank-1 Outer Products): \(\mathbf{A}\mathbf{B} = \sum_{l=1}^k \mathbf{a}_l \tilde{\mathbf{b}}_l^\top\) — biểu diễn tự nhiên cho
SVD,LoRAvà phân chia gạch Tensor Core (outer-product tiling).
Ký hiệu Tổng Einstein (einsum) & Bẫy Thứ tự Co Tensor (Contraction-Order Trap)#
Trong einsum với chuỗi chỉ số idx_1,idx_2,...->idx_out, mọi chỉ số xuất hiện ở đầu vào nhưng bị lược bỏ khỏi idx_out sẽ tự động được lấy tổng trên toàn trục; các chỉ số còn lại giữ đúng thứ tự trong idx_out.
| Phép toán | Biểu thức Toán học | Chữ ký einsum |
Số FLOPs | Hình dạng Đầu ra & Ghi chú Hệ thống |
|---|---|---|---|---|
| Dot Product | \(s = \sum_i u_i v_i\) | i,i-> |
\(2n\) | () (vô hướng); đọc tuyến tính \(O(n)\) |
| Outer Product | \(M_{ij} = u_i v_j\) | i,j->ij |
\(mn\) | (m, n); ghi \(O(mn)\) RAM |
| Matrix Transpose | \(B_{ji} = A_{ij}\) | ij->ji |
\(0\) | (n, m); chỉ hoán đổi strides (zero-copy) |
| Matrix Trace | \(t = \sum_i A_{ii}\) | ii-> |
\(n\) | (); đọc chéo chính |
| Frobenius Inner Product | \(\langle \mathbf{A}, \mathbf{B}\rangle_F = \operatorname{tr}(\mathbf{A}^\top \mathbf{B}) = \sum_{i,j} A_{ij} B_{ij}\) | ij,ij-> |
\(2mn\) | (); bộ cộng dồn \(O(1)\) |
MatVec (BLAS-2) |
\(y_i = \sum_j A_{ij} x_j\) | ij,j->i |
\(2mn\) | (m,); nghẽn băng thông bộ nhớ |
MatMul (BLAS-3) |
\(C_{ij} = \sum_k A_{ik} B_{kj}\) | ik,kj->ij |
\(2mkn\) | (m, n); bão hòa tính toán khi lớn |
Batched MatMul (BMM) |
\(C_{bij} = \sum_k A_{bik} B_{bkj}\) | bik,bkj->bij |
\(2Bmkn\) | (B, m, n); trục batch b độc lập |
| Attention Scores | \(S_{bhqk} = \frac{1}{\sqrt{d_k}}\sum_{d=1}^{d_k} Q_{bhqd} K_{bhkd}\) | bhqd,bhkd->bhqk |
\(2BHL_q L_k d_k\) | (B, H, L_q, L_k); RAM \(O(L_q L_k)\) bậc hai |
| Attention Aggregation | \(O_{bhqd} = \sum_{k=1}^{L_k} P_{bhqk} V_{bhkd}\) | bhqk,bhkd->bhqd |
\(2BHL_q L_k d_v\) | (B, H, L_q, d_v); nhạy cảm thứ tự co |
Chứng minh Độ nhạy Thứ tự Co (
Contraction-Order Trap): Xét chuỗi nhân tuyến tính \(\mathbf{Q}(\mathbf{K}^\top \mathbf{V})\) với \(\mathbf{Q}, \mathbf{K}, \mathbf{V} \in \mathbb{R}^{L \times d}\) (trong bài toán ngữ cảnh dài \(L = 128{,}000, d = 128\)). Nếu tính theo(Q @ K.T) @ V(qd,kd->qkrồiqk,kd->qd), bước đầu sinh ma trận trung gian \(L \times L\) tiêu tốn \(O(L^2 d)\) FLOPs và \(O(L^2)\) RAM (\(\sim 65.5\text{ GB}\) ởfp32). Nếu áp dụng tính kết hợp đổi ngoặc thànhQ @ (K.T @ V)(kd,kv->dvrồiqd,dv->qv), ma trận trung gian chỉ có kích thước \(d \times d\), kéo chi phí xuống \(O(L d^2)\) FLOPs và \(O(d^2)\) RAM (\(\sim 64\text{ KB}\)) — giảm \(L/d = 1{,}000\times\) tính toán khi \(d \ll L\)! Tương tự, tính hoán vị vòng của vết suy ra trực tiếp từeinsum: \(\operatorname{tr}(\mathbf{A}\mathbf{B}\mathbf{C}) = \sum_{i,j,k} A_{ij}B_{jk}C_{ki} = \operatorname{tr}(\mathbf{C}\mathbf{A}\mathbf{B}) = \operatorname{tr}(\mathbf{B}\mathbf{C}\mathbf{A})\).
Bốn Không gian Con Cơ bản, Định lý Hạng–Không gian hạch & Phép chiếu Trực giao#
Cho ma trận \(\mathbf{A} \in \mathbb{R}^{m \times n}\) ứng với ánh xạ tuyến tính \(T_{\mathbf{A}}: \mathbb{R}^n \to \mathbb{R}^m\), \(\mathbf{x} \mapsto \mathbf{A}\mathbf{x}\) và hạng \(r := \operatorname{rank}(\mathbf{A}) \le \min(m, n)\). Bốn không gian con cơ bản (Four Fundamental Subspaces) gồm:
- Không gian cột (
Column Space / Range): \(\mathcal{C}(\mathbf{A}) := \{\mathbf{A}\mathbf{x} : \mathbf{x} \in \mathbb{R}^n\} \subseteq \mathbb{R}^m\), \(\dim\mathcal{C}(\mathbf{A}) = r\). - Không gian hạch (
Null Space): \(\mathcal{N}(\mathbf{A}) := \{\mathbf{x} \in \mathbb{R}^n : \mathbf{A}\mathbf{x} = \mathbf{0}\} \subseteq \mathbb{R}^n\), \(\dim\mathcal{N}(\mathbf{A}) = n - r\). - Không gian hàng (
Row Space): \(\mathcal{C}(\mathbf{A}^\top) := \{\mathbf{A}^\top \mathbf{y} : \mathbf{y} \in \mathbb{R}^m\} \subseteq \mathbb{R}^n\), \(\dim\mathcal{C}(\mathbf{A}^\top) = r\). - Không gian hạch trái (
Left Null Space): \(\mathcal{N}(\mathbf{A}^\top) := \{\mathbf{y} \in \mathbb{R}^m : \mathbf{A}^\top \mathbf{y} = \mathbf{0}\} \subseteq \mathbb{R}^m\), \(\dim\mathcal{N}(\mathbf{A}^\top) = m - r\).
Định lý 1.1 (Rank–Nullity Theorem): Với mọi \(\mathbf{A} \in \mathbb{R}^{m \times n}\), ta có \(\dim\mathcal{C}(\mathbf{A}) + \dim\mathcal{N}(\mathbf{A}) = n\).
Chứng minh: Đặt \(k = \dim\mathcal{N}(\mathbf{A})\) và chọn một cơ sở \(\{\mathbf{v}_1, \dots, \mathbf{v}_k\}\) của \(\mathcal{N}(\mathbf{A})\). Mở rộng hệ này thành một cơ sở đầy đủ \(\{\mathbf{v}_1, \dots, \mathbf{v}_k, \mathbf{w}_1, \dots, \mathbf{w}_r\}\) của \(\mathbb{R}^n\) (trong đó \(k + r = n\)). Ta chứng minh \(\mathcal{B} = \{\mathbf{A}\mathbf{w}_1, \dots, \mathbf{A}\mathbf{w}_r\}\) là một cơ sở của \(\mathcal{C}(\mathbf{A})\):
- Tính sinh (
Spanning): Mọi \(\mathbf{y} \in \mathcal{C}(\mathbf{A})\) đều viết được dạng \(\mathbf{y} = \mathbf{A}\mathbf{x}\) với \(\mathbf{x} = \sum_{i=1}^k \alpha_i \mathbf{v}_i + \sum_{j=1}^r \beta_j \mathbf{w}_j\). Vì \(\mathbf{A}\mathbf{v}_i = \mathbf{0}\), suy ra \(\mathbf{y} = \sum_{j=1}^r \beta_j (\mathbf{A}\mathbf{w}_j) \in \operatorname{span}(\mathcal{B})\). - Độc lập tuyến tính (
Linear Independence): Giả sử \(\sum_{j=1}^r c_j (\mathbf{A}\mathbf{w}_j) = \mathbf{0}\). Theo tính tuyến tính, \(\mathbf{A}\!\left(\sum_{j=1}^r c_j \mathbf{w}_j\right) = \mathbf{0}\), nghĩa là \(\sum_{j=1}^r c_j \mathbf{w}_j \in \mathcal{N}(\mathbf{A}) = \operatorname{span}\{\mathbf{v}_1, \dots, \mathbf{v}_k\}\). Tồn tại \(d_1, \dots, d_k\) sao cho \(\sum_{j=1}^r c_j \mathbf{w}_j - \sum_{i=1}^k d_i \mathbf{v}_i = \mathbf{0}\). Do hệ vector của \(\mathbb{R}^n\) độc lập tuyến tính, mọi \(c_j = 0\) (và \(d_i = 0\)). Vậy \(\dim\mathcal{C}(\mathbf{A}) = r\), dẫn tới \(\dim\mathcal{C}(\mathbf{A}) + \dim\mathcal{N}(\mathbf{A}) = r + k = n\). \(\blacksquare\)
Định lý 1.2 (Định lý Cơ bản của Đại số Tuyến tính — Fundamental Theorem of Linear Algebra): Với mọi \(\mathbf{A} \in \mathbb{R}^{m \times n}\):
- \(\mathcal{C}(\mathbf{A}^\top) \perp \mathcal{N}(\mathbf{A})\) trong \(\mathbb{R}^n\), và \(\mathbb{R}^n = \mathcal{C}(\mathbf{A}^\top) \oplus \mathcal{N}(\mathbf{A})\).
- \(\mathcal{C}(\mathbf{A}) \perp \mathcal{N}(\mathbf{A}^\top)\) trong \(\mathbb{R}^m\), và \(\mathbb{R}^m = \mathcal{C}(\mathbf{A}) \oplus \mathcal{N}(\mathbf{A}^\top)\).
- Hạng hàng bằng hạng cột (\(\dim\mathcal{C}(\mathbf{A}^\top) = \dim\mathcal{C}(\mathbf{A}) = r\)), và \(\mathbf{A}\) thu hẹp thành một song ánh (
bijection) từ \(\mathcal{C}(\mathbf{A}^\top)\) lên \(\mathcal{C}(\mathbf{A})\).
Chứng minh: Lấy bất kỳ \(\mathbf{z} = \mathbf{A}^\top \mathbf{y} \in \mathcal{C}(\mathbf{A}^\top)\) và \(\mathbf{x} \in \mathcal{N}(\mathbf{A})\) (\(\mathbf{A}\mathbf{x} = \mathbf{0}\)). Ta có \(\langle \mathbf{z}, \mathbf{x} \rangle = (\mathbf{A}^\top \mathbf{y})^\top \mathbf{x} = \mathbf{y}^\top (\mathbf{A}\mathbf{x}) = 0\), chứng tỏ \(\mathcal{C}(\mathbf{A}^\top) \perp \mathcal{N}(\mathbf{A})\). Áp dụng tương tự cho \(\mathbf{A}^\top\) thu được \(\mathcal{C}(\mathbf{A}) \perp \mathcal{N}(\mathbf{A}^\top)\). Do trực giao, \(\mathcal{C}(\mathbf{A}^\top) \cap \mathcal{N}(\mathbf{A}) = \{\mathbf{0}\}\), nên \(\dim\mathcal{C}(\mathbf{A}^\top) + \dim\mathcal{N}(\mathbf{A}) \le n = \dim\mathcal{C}(\mathbf{A}) + \dim\mathcal{N}(\mathbf{A})\), suy ra \(\dim\mathcal{C}(\mathbf{A}^\top) \le \dim\mathcal{C}(\mathbf{A})\). Hoán đổi vai trò \(\mathbf{A}\) và \(\mathbf{A}^\top\) đảo ngược bất đẳng thức, chứng minh \(\dim\mathcal{C}(\mathbf{A}^\top) = \dim\mathcal{C}(\mathbf{A}) = r\) và hai phân tách tổng trực tiếp trực giao. Cuối cùng, mọi \(\mathbf{x} \in \mathbb{R}^n\) tách duy nhất thành \(\mathbf{x} = \mathbf{x}_r + \mathbf{x}_0\) (\(\mathbf{x}_r \in \mathcal{C}(\mathbf{A}^\top), \mathbf{x}_0 \in \mathcal{N}(\mathbf{A})\)) với \(\mathbf{A}\mathbf{x} = \mathbf{A}\mathbf{x}_r\). Nếu \(\mathbf{A}\mathbf{x}_r = \mathbf{0}\) thì \(\mathbf{x}_r \in \mathcal{C}(\mathbf{A}^\top) \cap \mathcal{N}(\mathbf{A}) = \{\mathbf{0}\}\), nên \(\mathbf{A}|_{\mathcal{C}(\mathbf{A}^\top)}\) vừa đơn ánh vừa toàn ánh lên \(\mathcal{C}(\mathbf{A})\). \(\blacksquare\)
Phép chiếu Trực giao & Ví dụ Số 3x2 Giải tay Đầy đủ: Khi \(\mathbf{A} \in \mathbb{R}^{m \times n}\) đủ hạng cột (\(\operatorname{rank}(\mathbf{A}) = n \le m\)), bài toán bình phương tối thiểu \(\min_{\mathbf{x}} \|\mathbf{b} - \mathbf{A}\mathbf{x}\|_2^2\) đòi hỏi vector phần dư \(\mathbf{r} = \mathbf{b} - \mathbf{A}\hat{\mathbf{x}}\) trực giao với \(\mathcal{C}(\mathbf{A})\), tức \(\mathbf{r} \in \mathcal{N}(\mathbf{A}^\top)\), dẫn đến phương trình chuẩn \(\mathbf{A}^\top\mathbf{A}\hat{\mathbf{x}} = \mathbf{A}^\top\mathbf{b}\) và ma trận chiếu trực giao lên \(\mathcal{C}(\mathbf{A})\):
với \(\mathbf{A} = \mathbf{Q}\mathbf{R}\) là phân rã QR rút gọn (\(\mathbf{Q}^\top\mathbf{Q} = \mathbf{I}_n\)). Dễ thấy \(\mathbf{P}^2 = \mathbf{P} = \mathbf{P}^\top\), và tính \(\mathbf{P}\mathbf{b} = \mathbf{Q}(\mathbf{Q}^\top\mathbf{b})\) tránh được việc lập \(\mathbf{A}^\top\mathbf{A}\) làm bình phương số điều kiện.
Xét ma trận chuẩn hóa \(\mathbf{A} = \begin{bmatrix} 3 & 2 \\ 2 & 3 \\ 2 & -2 \end{bmatrix} \in \mathbb{R}^{3 \times 2}\) (\(m=3, n=2\)):
- Ma trận Gram \(\mathbf{A}^\top\mathbf{A} = \begin{bmatrix} 17 & 8 \\ 8 & 17 \end{bmatrix}\) có \(\det = 289 - 64 = 225 \ne 0\), nên \(\mathcal{N}(\mathbf{A}) = \{\mathbf{0}\}\) (\(\dim 0\)) và \(\mathcal{C}(\mathbf{A}^\top) = \mathbb{R}^2\) (\(\dim 2\)).
- Không gian hạch trái \(\mathcal{N}(\mathbf{A}^\top) = \operatorname{span}\{(2, -2, -1)^\top\}\) (\(\dim 1\)) vì \(\mathbf{A}^\top [2, -2, -1]^\top = [6-4-2,\; 4-6+2]^\top = \mathbf{0}\). Kiểm tra trực giao: \(\dim\mathcal{C}(\mathbf{A}) + \dim\mathcal{N}(\mathbf{A}^\top) = 2 + 1 = 3 = m\).
- Nghịch đảo \((\mathbf{A}^\top\mathbf{A})^{-1} = \frac{1}{225}\begin{bmatrix} 17 & -8 \\ -8 & 17 \end{bmatrix}\) cho ma trận chiếu:
Kiểm chứng \(\mathbf{P}^2 = \mathbf{P} = \mathbf{P}^\top\) và \(\operatorname{tr}(\mathbf{P}) = \frac{5+5+8}{9} = 2 = \operatorname{rank}(\mathbf{P})\). Chiếu vector \(\mathbf{b} = [1, 5, 1]^\top\) thu được \(\hat{\mathbf{b}} = \mathbf{P}\mathbf{b} = [3, 3, 0]^\top = \mathbf{A}[3/5, 3/5]^\top\) và phần dư \(\mathbf{r} = \mathbf{b} - \hat{\mathbf{b}} = [-2, 2, 1]^\top \in \mathcal{N}(\mathbf{A}^\top)\) thỏa mãn \(\hat{\mathbf{b}}^\top\mathbf{r} = 0\).
1.2 Chuẩn Vector, Chuẩn Ma trận & Đối ngẫu Phổ–Hạt nhân (Norms, Dual Norms & Spectral–Nuclear Duality)#
Chuẩn Vector \(\ell_p\), Hình học Quả cầu Đơn vị & Các Bất đẳng thức Kinh điển#
Hàm \(\|\cdot\|: \mathbb{R}^n \to \mathbb{R}_{\ge 0}\) là một chuẩn (norm) khi và chỉ khi với mọi \(\mathbf{x}, \mathbf{y} \in \mathbb{R}^n\) và \(\alpha \in \mathbb{R}\): (1) \(\|\mathbf{x}\| = 0 \iff \mathbf{x} = \mathbf{0}\) (xác định dương), (2) \(\|\alpha \mathbf{x}\| = |\alpha|\|\mathbf{x}\|\) (thuần nhất tuyệt đối), và (3) \(\|\mathbf{x} + \mathbf{y}\| \le \|\mathbf{x}\| + \|\mathbf{y}\|\) (bất đẳng thức tam giác). Với \(p \ge 1\), chuẩn \(\ell_p\) được định nghĩa là \(\|\mathbf{x}\|_p := \big(\sum_{i=1}^n |x_i|^p\big)^{1/p}\), và khi \(p \to \infty\), đặt \(M = \max_i |x_i|\) thì \(M \le (\sum_i |x_i|^p)^{1/p} \le n^{1/p} M \xrightarrow{p\to\infty} M = \|\mathbf{x}\|_\infty\).
| Chuẩn Vector | Công thức | Hình học Quả cầu Đơn vị (\(\|\mathbf{x}\|_p \le 1\)) | Vai trò trong Machine Learning |
|---|---|---|---|
| \(\ell_1\) (Manhattan) | \(\sum_{i=1}^n |x_i|\) | Khối đa diện chéo (cross-polytope), đỉnh nhọn tại \(\pm \mathbf{e}_i\) |
Thúc đẩy tính thưa chính xác (sparsity) trong hồi quy Lasso; bao lồi của \(\|\mathbf{x}\|_0\) (lưu ý \(\ell_0\) vi phạm tính thuần nhất, \(\ell_q\) với \(0<q<1\) vi phạm bất đẳng thức tam giác). |
| \(\ell_2\) (Euclidean) | \(\sqrt{\sum_{i=1}^n x_i^2}\) | Siêu cầu (hypersphere); lồi chặt và bất biến quay \(O(n)\) |
Trơn khắp nơi trừ \(\mathbf{0}\); cảm sinh từ tích vô hướng chuẩn; điều chuẩn Ridge. |
| \(\ell_\infty\) (Chebyshev) | \(\max_{1 \le i \le n} |x_i|\) | Siêu lập phương \([-1, 1]^n\) (hypercube) |
Mô hình nhiễu đối kháng (FGSM/PGD \(\ell_\infty\)); chặn minimax; đối ngẫu của \(\ell_1\). |
Chuỗi tương đương chặt trên \(\mathbb{R}^n\): \(\|\mathbf{x}\|_\infty \le \|\mathbf{x}\|_2 \le \|\mathbf{x}\|_1 \le \sqrt{n}\|\mathbf{x}\|_2 \le n\|\mathbf{x}\|_\infty\) (đẳng thức trái đạt tại \(\mathbf{e}_1\), đẳng thức phải đạt tại \(\mathbf{1}_n\)).
Cho cặp số liên hợp Hölder \(p, q \in (1, \infty)\) thỏa \(\frac{1}{p} + \frac{1}{q} = 1\):
- Bất đẳng thức Young (\(a, b \ge 0\)): Do \(\ln(\cdot)\) lõm chặt trên \((0, \infty)\), \(\ln(ab) = \frac{1}{p}\ln(a^p) + \frac{1}{q}\ln(b^q) \le \ln\!\left(\frac{a^p}{p} + \frac{b^q}{q}\right)\), lấy mũ hai vế suy ra \(ab \le \frac{a^p}{p} + \frac{b^q}{q}\) (dấu bằng khi \(a^p = b^q\)). \(\blacksquare\)
- Bất đẳng thức Hölder: Với \(\mathbf{u}, \mathbf{v} \ne \mathbf{0}\), chuẩn hóa \(\tilde{u}_i = |u_i|/\|\mathbf{u}\|_p\), \(\tilde{v}_i = |v_i|/\|\mathbf{v}\|_q\) (\(\sum \tilde{u}_i^p = \sum \tilde{v}_i^q = 1\)). Áp dụng Young theo từng tọa độ rồi lấy tổng cho \(\sum_{i=1}^n \tilde{u}_i \tilde{v}_i \le \sum_{i=1}^n (\frac{\tilde{u}_i^p}{p} + \frac{\tilde{v}_i^q}{q}) = 1\), nhân chéo mẫu số chứng minh \(|\mathbf{u}^\top\mathbf{v}| \le \|\mathbf{u}\|_p\|\mathbf{v}\|_q\). \(\blacksquare\) (Khi \(p=q=2\) thu được Cauchy–Schwarz: \(|\mathbf{u}^\top\mathbf{v}| \le \|\mathbf{u}\|_2\|\mathbf{v}\|_2\).)
- Bất đẳng thức Tam giác Minkowski (\(p > 1\)): \(\|\mathbf{x}+\mathbf{y}\|_p^p \le \sum_i |x_i||x_i+y_i|^{p-1} + \sum_i |y_i||x_i+y_i|^{p-1}\). Áp dụng Hölder với \((p, q = \frac{p}{p-1})\) và nhận xét \(\||x+y|^{p-1}\|_q = \|\mathbf{x}+\mathbf{y}\|_p^{p-1}\) ta được \(\|\mathbf{x}+\mathbf{y}\|_p^p \le (\|\mathbf{x}\|_p + \|\mathbf{y}\|_p)\|\mathbf{x}+\mathbf{y}\|_p^{p-1}\), chia hai vế cho \(\|\mathbf{x}+\mathbf{y}\|_p^{p-1}\) hoàn tất chứng minh. \(\blacksquare\)
Chuẩn Đối ngẫu & Định lý Đối ngẫu Phổ–Hạt nhân#
Chuẩn đối ngẫu (dual norm) của \(\|\cdot\|\) định nghĩa bởi \(\|\mathbf{z}\|_* := \sup_{\|\mathbf{x}\|\le 1} \mathbf{z}^\top \mathbf{x}\), kéo theo bất đẳng thức Cauchy–Schwarz tổng quát \(\mathbf{z}^\top \mathbf{x} \le \|\mathbf{z}\|_*\|\mathbf{x}\|\) và tính song đối ngẫu \(((\|\cdot\|)_*)_* = \|\cdot\|\).
Định lý 2.1 (Đối ngẫu của \(\ell_p\) là \(\ell_q\)): Với \(1 \le p \le \infty\) và \(\frac{1}{p} + \frac{1}{q} = 1\), ta có \((\|\mathbf{z}\|_p)_* = \|\mathbf{z}\|_q\).
Chứng minh: Cận trên suy trực tiếp từ Hölder (\(\mathbf{z}^\top \mathbf{x} \le \|\mathbf{z}\|_q\|\mathbf{x}\|_p \le \|\mathbf{z}\|_q\)). Tính đạt được khi \(\mathbf{z} \ne \mathbf{0}\): với \(1 < p < \infty\), chọn \(x_i^* = \operatorname{sgn}(z_i)|z_i|^{q-1}/\|\mathbf{z}\|_q^{q-1}\) thỏa \((q-1)p = q \implies \|\mathbf{x}^*\|_p = 1\) và \(\mathbf{z}^\top \mathbf{x}^* = \|\mathbf{z}\|_q\); với \(p=1\) (\(q=\infty\)), chọn \(\mathbf{x}^* = \operatorname{sgn}(z_k)\mathbf{e}_k\) tại \(k \in \arg\max_i |z_i|\); với \(p=\infty\) (\(q=1\)), chọn \(x_i^* = \operatorname{sgn}(z_i)\). \(\blacksquare\)
Ý nghĩa Hình học trong Tối ưu hóa: Bài toán tìm hướng giảm dốc nhất trong quả cầu chuẩn đơn vị \(\arg\min_{\|\mathbf{v}\| \le 1} \nabla f^\top \mathbf{v}\) cho nghiệm khác nhau hoàn toàn theo hình học chuẩn chọn: dưới chuẩn \(\ell_2\) là \(-\nabla f / \|\nabla f\|_2\) (Gradient Descent); dưới chuẩn \(\ell_\infty\) là \(-\operatorname{sgn}(\nabla f)\) (họ
SignSGD/Lion); còn dưới chuẩn phổ ma trận \(\|\cdot\|_2\) là thừa số cực trực giao \(-\mathbf{U}_r\mathbf{V}_r^\top\) (bộ tối ưuMuon!).
Với ma trận \(\mathbf{A} \in \mathbb{R}^{m \times n}\) hạng \(r\) và các giá trị kỳ dị \(\sigma_1 \ge \dots \ge \sigma_r > 0\), xét ba chuẩn Schatten cơ bản:
- Chuẩn Frobenius (
Schatten-2): \(\|\mathbf{A}\|_F := \sqrt{\sum_{i,j} A_{ij}^2} = \sqrt{\operatorname{tr}(\mathbf{A}^\top\mathbf{A})} = \sqrt{\sum_{i=1}^r \sigma_i^2}\) (tự đối ngẫu dưới tích vô hướng \(\langle \mathbf{A},\mathbf{B}\rangle_F = \operatorname{tr}(\mathbf{A}^\top\mathbf{B})\), bất biến trực giao và nhân tính dưới \(\|\mathbf{A}\mathbf{B}\|_F \le \|\mathbf{A}\|_F\|\mathbf{B}\|_F\)). - Chuẩn Phổ (
Spectral / Schatten-∞): \(\|\mathbf{A}\|_2 := \sup_{\|\mathbf{x}\|_2 \le 1}\|\mathbf{A}\mathbf{x}\|_2 = \sigma_1\). - Chuẩn Hạt nhân (
Nuclear / Trace / Schatten-1): \(\|\mathbf{A}\|_* := \operatorname{tr}(\sqrt{\mathbf{A}^\top\mathbf{A}}) = \sum_{i=1}^r \sigma_i\).
Định lý 2.2 (Chuỗi Tương đương Chặt của Chuẩn Ma trận): Với mọi \(\mathbf{A} \in \mathbb{R}^{m \times n}\) hạng \(r\):
Chứng minh: Chuỗi thứ nhất suy từ \(\sigma_1^2 \le \sum_{i=1}^r \sigma_i^2 \le r\sigma_1^2\) rồi lấy căn bậc hai. Ở chuỗi thứ hai, \(\|\mathbf{A}\|_*^2 = (\sum_{i=1}^r \sigma_i)^2 = \sum_{i=1}^r \sigma_i^2 + 2\sum_{i<j} \sigma_i\sigma_j \ge \sum_{i=1}^r \sigma_i^2 = \|\mathbf{A}\|_F^2\), suy ra \(\|\mathbf{A}\|_F \le \|\mathbf{A}\|_*\). Mặt khác, áp dụng Cauchy–Schwarz cho \(\boldsymbol{\sigma} \in \mathbb{R}^r\) và vector đơn vị toàn một \(\mathbf{1}_r\) cho \(\|\mathbf{A}\|_* = \mathbf{1}_r^\top\boldsymbol{\sigma} \le \|\mathbf{1}_r\|_2 \|\boldsymbol{\sigma}\|_2 = \sqrt{r}\|\mathbf{A}\|_F\). \(\blacksquare\)
Định lý 2.3 (Đối ngẫu Phổ–Hạt nhân — Spectral–Nuclear Duality): Dưới tích vô hướng Frobenius \(\langle \mathbf{A}, \mathbf{X}\rangle_F = \operatorname{tr}(\mathbf{A}^\top\mathbf{X})\), chuẩn phổ và chuẩn hạt nhân là cặp đối ngẫu chính xác của nhau:
Chứng minh: Khai triển SVD gọn \(\mathbf{A} = \mathbf{U}_r \boldsymbol{\Sigma}_r \mathbf{V}_r^\top\). Với mọi \(\mathbf{X}\) thỏa \(\|\mathbf{X}\|_2 \le 1\), tính hoán vị vòng của vết cho \(\operatorname{tr}(\mathbf{A}^\top\mathbf{X}) = \operatorname{tr}(\boldsymbol{\Sigma}_r\mathbf{U}_r^\top\mathbf{X}\mathbf{V}_r) = \sum_{i=1}^r \sigma_i (\mathbf{u}_i^\top \mathbf{X}\mathbf{v}_i)\). Do \(|\mathbf{u}_i^\top\mathbf{X}\mathbf{v}_i| \le \|\mathbf{u}_i\|_2\|\mathbf{X}\|_2\|\mathbf{v}_i\|_2 \le 1\), ta có \(\operatorname{tr}(\mathbf{A}^\top\mathbf{X}) \le \sum_{i=1}^r \sigma_i = \|\mathbf{A}\|_*\). Đẳng thức đạt duy nhất tại thừa số cực trực giao \(\mathbf{X}^* = \mathbf{U}_r\mathbf{V}_r^\top\) (thỏa \(\|\mathbf{X}^*\|_2 = 1\) và \(\mathbf{u}_i^\top\mathbf{X}^*\mathbf{v}_i = 1\)). Chiều ngược lại suy từ tính song đối ngẫu (hoặc khai triển SVD \(\mathbf{X} = \sum_j \tilde{\sigma}_j \tilde{\mathbf{u}}_j \tilde{\mathbf{v}}_j^\top\) với \(\sum_j \tilde{\sigma}_j \le 1\), đạt cận trên \(\sigma_1\) tại \(\mathbf{u}_1\mathbf{v}_1^\top\)). \(\blacksquare\)
1.3 Ma trận Đặc biệt & Khai thác Cấu trúc (Special Matrices: SPD/Cholesky, Orthogonal, Projection, Low-Rank & Circulant FFT)#
Nhận diện đúng cấu trúc đại số giúp hạ độ phức tạp lưu trữ và giải hệ từ \(O(n^3)\) xuống \(O(n)\) hoặc \(O(n\log n)\) đồng thời bảo toàn độ ổn định số học.
| Lớp Ma trận | Tính chất Định nghĩa | Lưu trữ | Chi phí MatVec / Giải hệ | Bất biến & Vai trò ML |
|---|---|---|---|---|
Đối xứng PSD / SPD |
\(\mathbf{A}=\mathbf{A}^\top\); \(\mathbf{x}^\top\mathbf{A}\mathbf{x} \ge 0\) (PSD) hoặc \(>0\;\forall\mathbf{x}\ne\mathbf{0}\) (SPD) |
\(\frac{n(n+1)}{2}\) | Cholesky \(\mathbf{L}\mathbf{L}^\top\): \(\frac{1}{3}n^3\) FLOPs (nhanh \(2\times\) LU); Giải hệ: \(2n^2\) | Hiệp phương sai, nhân Kernel, Hessian lồi; chuẩn Mahalanobis; \(\ln\det\mathbf{A} = 2\sum_i \ln L_{ii}\) |
| Trực giao (\(O(n)\)) | \(\mathbf{Q}^\top\mathbf{Q} = \mathbf{Q}\mathbf{Q}^\top = \mathbf{I}_n\) | \(n^2\) (\(O(nk)\) Householder) | MatVec \(2n^2\); Nghịch đảo \(\mathbf{Q}^{-1} = \mathbf{Q}^\top\) (\(0\) FLOPs) | Bảo toàn chuẩn \(\ell_2\) và góc; \(\sigma_i = 1\); \(|\det\mathbf{Q}|=1\), \(\kappa_2(\mathbf{Q})=1\); RoPE, khởi tạo trực giao |
| Chiếu trực giao | \(\mathbf{P}^2 = \mathbf{P} = \mathbf{P}^\top\) | \(n^2\) (\(O(nr)\) qua \(\mathbf{Q}\mathbf{Q}^\top\)) | \(2nr\) qua \(\mathbf{Q}(\mathbf{Q}^\top\mathbf{x})\) | Trị riêng \(\in \{0, 1\}\); \(\operatorname{rank}(\mathbf{P}) = \operatorname{tr}(\mathbf{P})\); \(\|\mathbf{P}\|_2 = 1\) (khi \(\mathbf{P}\ne\mathbf{0}\)) |
Hạng thấp (Low-Rank) |
\(\mathbf{A} = \mathbf{U}\mathbf{V}^\top\) (\(r \ll m, n\)) | \(O(r(m+n))\) | MatVec \(2r(m+n)\) (so với \(2mn\)) | LoRA, PiSSA, nén KV cache MLA, SVD cắt cụt |
| Đường chéo & Tam đường chéo | \(A_{ij}=0\) khi \(i\ne j\) (hoặc \(|i-j|>1\)) | \(n\) / \(3n-2\) | MatVec \(O(n)\); Thuật toán Thomas giải hệ \(O(n)\) (\(\approx 8n\) FLOPs) | Tiền điều kiện đường chéo Adam; sai phân hữu hạn 1D, spline |
Toeplitz & Tuần hoàn (Circulant) |
\(T_{ij}=t_{i-j}\); \(C_{ij}=c_{(i-j)\bmod n}\) | \(2n-1\) / \(n\) | MatVec & Giải hệ tuần hoàn \(O(n\log n)\) qua FFT | Tích chập 1D; mô hình chuỗi dài Hyena / FFT-Conv |
Phân rã Cholesky (\(\mathbf{A} = \mathbf{L}\mathbf{L}^\top\)): Phần bù Schur & \(\frac{1}{3}n^3\) FLOPs#
Mọi ma trận SPD \(\mathbf{A} \in \mathbb{R}^{n\times n}\) đều tồn tại duy nhất phân rã tam giác dưới \(\mathbf{A} = \mathbf{L}\mathbf{L}^\top\) với đường chéo dương chặt \(L_{jj} > 0\), tính theo từng cột \(j = 1, \dots, n\):
- Chứng minh Dương chặt & Ổn định Không cần Đổi hàng (
No Pivoting): Phân khối \(\mathbf{A} = \begin{bmatrix} a_{11} & \mathbf{a}^\top \\ \mathbf{a} & \tilde{\mathbf{A}} \end{bmatrix} \succ 0\) cho \(a_{11} = \mathbf{e}_1^\top\mathbf{A}\mathbf{e}_1 > 0\) nên \(L_{11} = \sqrt{a_{11}} > 0\). Phần bù Schur \(\mathbf{S} = \tilde{\mathbf{A}} - \frac{1}{a_{11}}\mathbf{a}\mathbf{a}^\top\) thỏa \(\mathbf{z}^\top\mathbf{S}\mathbf{z} = [-\mathbf{a}^\top\mathbf{z}/a_{11},\; \mathbf{z}^\top]\mathbf{A}[-\mathbf{a}^\top\mathbf{z}/a_{11},\; \mathbf{z}^\top]^\top > 0\) với mọi \(\mathbf{z} \ne \mathbf{0}\), suy ra \(\mathbf{S} \succ 0\) theo quy nạp. Đồng thời \(\sum_{k=1}^i L_{ik}^2 = A_{ii}\) chặn chặt mọi phần tử \(|L_{ik}| \le \sqrt{A_{ii}}\), triệt tiêu nguy cơ bùng nổ chốt. - Đếm chính xác FLOPs: Tại mỗi cặp \((i, j)\) (\(i > j\)) cần \(j-1\) phép nhân, \(j-1\) phép trừ và \(1\) phép chia (\(\approx 2j\) FLOPs), tổng cộng \(\sum_{j=1}^n (n-j)(2j) + O(n^2) = 2(\frac{n^3}{2} - \frac{n^3}{3}) + O(n^2) = \frac{1}{3}n^3 + O(n^2)\) FLOPs — nhanh gấp \(2\times\) phân rã
LU(\(\frac{2}{3}n^3\)). Giá trị \(\ln\det\mathbf{A} = 2\sum_{i=1}^n \ln L_{ii}\) thu được miễn phí ngay từ đường chéo của \(\mathbf{L}\).
Chứng minh Đặc trưng Ma trận Trực giao & Ma trận Chiếu#
- Với \(\mathbf{Q} \in O(n)\): \(\|\mathbf{Q}\mathbf{x}\|_2^2 = \mathbf{x}^\top\mathbf{Q}^\top\mathbf{Q}\mathbf{x} = \|\mathbf{x}\|_2^2 \implies \sigma_{\max}(\mathbf{Q}) = \sigma_{\min}(\mathbf{Q}) = 1 \implies \kappa_2(\mathbf{Q}) = 1\) (số điều kiện lý tưởng nhỏ nhất có thể).
- Với ma trận lũy đẳng \(\mathbf{P}^2 = \mathbf{P}\): mọi trị riêng thỏa \(\lambda^2 = \lambda \implies \lambda \in \{0, 1\}\), tách \(\mathbb{R}^n = \mathcal{C}(\mathbf{P}) \oplus \mathcal{N}(\mathbf{P})\). Tích vô hướng \((\mathbf{P}\mathbf{u})^\top(\mathbf{I}-\mathbf{P})\mathbf{v} = \mathbf{u}^\top(\mathbf{P}^\top - \mathbf{P}^\top\mathbf{P})\mathbf{v}\) triệt tiêu với mọi \(\mathbf{u}, \mathbf{v}\) khi và chỉ khi \(\mathbf{P}^\top = \mathbf{P}^\top\mathbf{P}\), tức \(\mathbf{P}^\top\) đối xứng \(\iff \mathbf{P} = \mathbf{P}^\top\). Mọi phép chiếu trực giao khác không đều có \(\|\mathbf{P}\|_2 = 1\), trái ngược phép chiếu xiên (\(\mathbf{P} \ne \mathbf{P}^\top\)) có thể khuếch đại chuẩn \(\|\mathbf{P}\|_2 > 1\).
Định lý 3.1: Chéo hóa Ma trận Tuần hoàn bằng Biến đổi Fourier Rời rạc Đơn nguyên (DFT Diagonalization)#
Ma trận tuần hoàn \(\mathbf{C} \in \mathbb{R}^{n \times n}\) sinh bởi cột đầu \(\mathbf{c} = (c_0, \dots, c_{n-1})^\top\) có phần tử \(C_{rj} = c_{(r-j)\bmod n}\), nên \((\mathbf{C}\mathbf{x})_r = \sum_{j=0}^{n-1} c_{(r-j)\bmod n}\,x_j\) chính là tích chập vòng 1D. Đặt \(\omega = e^{2\pi i / n}\) và định nghĩa ma trận DFT đơn nguyên \(\mathbf{F} \in \mathbb{C}^{n \times n}\) bởi \(F_{mj} = \frac{1}{\sqrt{n}}\omega^{-mj}\) (\(0 \le m, j \le n-1\)), thỏa mãn \(\mathbf{F}^*\mathbf{F} = \mathbf{F}\mathbf{F}^* = \mathbf{I}_n\). Khi đó, mọi ma trận tuần hoàn \(\mathbf{C}\) đều được chéo hóa đơn nguyên bởi \(\mathbf{F}\):
Chứng minh: Gọi \(\mathbf{u}_m\) là cột thứ \(m\) của \(\mathbf{F}^*\), với \((\mathbf{u}_m)_j = \overline{F_{mj}} = \frac{1}{\sqrt{n}}\omega^{mj}\). Nhân \(\mathbf{C}\) với \(\mathbf{u}_m\) tại hàng \(r\) và đặt chỉ số dịch vòng \(k := (r - j) \bmod n\) (do đó \(j \equiv r - k \pmod n\) và \(\omega^n = 1\) nên \(\omega^{mj} = \omega^{mr}\omega^{-mk}\)):
Suy ra \(\mathbf{C}\mathbf{u}_m = \hat{c}_m \mathbf{u}_m\) hay \(\mathbf{C}\mathbf{F}^* = \mathbf{F}^*\operatorname{diag}(\hat{\mathbf{c}})\). Nhân phải hai vế với \(\mathbf{F}\) (\(\mathbf{F}^*\mathbf{F}=\mathbf{I}_n\)) thu được \(\mathbf{C} = \mathbf{F}^* \operatorname{diag}(\hat{\mathbf{c}}) \mathbf{F}\). \(\blacksquare\)
Hệ quả Thuật toán (\(O(n\log n)\)): \(\mathbf{C}\mathbf{x} = \operatorname{IFFT}(\operatorname{FFT}(\mathbf{c}) \odot \operatorname{FFT}(\mathbf{x}))\) chỉ tốn \(O(n\log n)\) FLOPs thay vì \(O(n^2)\)! Với ma trận Toeplitz \(\mathbf{T} \in \mathbb{R}^{n\times n}\) (\(T_{ij} = t_{i-j}\)), ta nhúng \(\mathbf{T}\) vào góc trên-trái của ma trận tuần hoàn kích thước \(2n \times 2n\) có cột đầu \([t_0, \dots, t_{n-1}, 0, t_{-(n-1)}, \dots, t_{-1}]^\top\), đệm \(n\) số \(0\) vào \(\mathbf{x}\) rồi cắt lấy \(n\) phần tử đầu của kết quả IFFT — giữ trọn độ phức tạp \(O(n\log n)\) cho các lớp tích chập dài như Hyena.
1.4 Trị riêng, Định lý Phổ, SVD & Chứng minh Định lý Eckart–Young–Mirsky (Eigenvalues, Spectral Theorem, SVD & Eckart–Young)#
Trị riêng, Lũy thừa Hệ động lực & Thương số Rayleigh#
Với ma trận vuông \(\mathbf{A} \in \mathbb{R}^{n\times n}\), cặp \((\lambda, \mathbf{v})\) (\(\mathbf{v}\ne\mathbf{0}\)) là cặp riêng khi \(\mathbf{A}\mathbf{v} = \lambda\mathbf{v}\). Khi chéo hóa được (\(\mathbf{A} = \mathbf{P}\boldsymbol{\Lambda}\mathbf{P}^{-1}\)), lũy thừa \(\mathbf{A}^t = \mathbf{P}\boldsymbol{\Lambda}^t\mathbf{P}^{-1}\) chi phối sự triệt tiêu (\(\max|\lambda_i| < 1\)) hay bùng nổ (\(\max|\lambda_i| > 1\)) gradient khi lan truyền qua nhiều bước thời gian trong RNN/SSM; ngược lại ma trận khiếm khuyết (defective, số chiều hình học nhỏ hơn số bội đại số như \(\begin{bmatrix} 0 & 1 \\ 0 & 0 \end{bmatrix}\)) không chéo hóa được.
Với ma trận đối xứng \(\mathbf{A} = \mathbf{A}^\top\) và \(\mathbf{x} \ne \mathbf{0}\), Thương số Rayleigh (Rayleigh Quotient) là \(R_{\mathbf{A}}(\mathbf{x}) := \frac{\mathbf{x}^\top\mathbf{A}\mathbf{x}}{\mathbf{x}^\top\mathbf{x}}\). Lấy đạo hàm theo quy tắc thương số (dùng \(\nabla_{\mathbf{x}}(\mathbf{x}^\top\mathbf{A}\mathbf{x}) = 2\mathbf{A}\mathbf{x}\)):
Từ đây \(\nabla_{\mathbf{x}} R_{\mathbf{A}}(\mathbf{x}) = \mathbf{0} \iff \mathbf{A}\mathbf{x} = R_{\mathbf{A}}(\mathbf{x})\mathbf{x}\): mọi điểm dừng của thương số Rayleigh chính xác là vector riêng của \(\mathbf{A}\) và giá trị tại điểm dừng là trị riêng tương ứng.
Định lý 4.1 (Định lý Phổ Thực) & Định lý 4.2 (Min-Max Courant–Fischer)#
Định lý 4.1 (Real Spectral Theorem): Mọi ma trận thực đối xứng \(\mathbf{A} = \mathbf{A}^\top \in \mathbb{R}^{n\times n}\) đều có \(n\) trị riêng thực \(\lambda_1 \ge \dots \ge \lambda_n\) và một cơ sở trực chuẩn các vector riêng thực tạo thành \(\mathbf{Q} \in O(n)\) sao cho \(\mathbf{A} = \mathbf{Q}\boldsymbol{\Lambda}\mathbf{Q}^\top = \sum_{i=1}^n \lambda_i \mathbf{q}_i\mathbf{q}_i^\top\).
Chứng minh (Biến phân + Quy nạp thuần trên \(\mathbb{R}\)):
- Tồn tại cực đại thực: Mặt cầu đơn vị \(\mathbb{S}^{n-1}\) là tập compact và \(R_{\mathbf{A}}(\mathbf{x}) = \mathbf{x}^\top\mathbf{A}\mathbf{x}\) liên tục trên \(\mathbb{S}^{n-1}\). Theo Định lý Weierstrass, \(R_{\mathbf{A}}\) đạt cực đại toàn cục tại \(\mathbf{q}_1 \in \mathbb{S}^{n-1}\) với giá trị \(\lambda_1 = R_{\mathbf{A}}(\mathbf{q}_1)\). Do \(R_{\mathbf{A}}\) bất biến tỷ lệ (\(R_{\mathbf{A}}(\alpha\mathbf{x}) = R_{\mathbf{A}}(\mathbf{x})\)), \(\mathbf{q}_1\) cũng là điểm cực đại không ràng buộc trên \(\mathbb{R}^n\setminus\{\mathbf{0}\}\), nên \(\nabla R_{\mathbf{A}}(\mathbf{q}_1) = \mathbf{0} \implies \mathbf{A}\mathbf{q}_1 = \lambda_1\mathbf{q}_1\).
- Tính bất biến của \(W = \operatorname{span}\{\mathbf{q}_1\}^\perp\): Với mọi \(\mathbf{y} \in W\), \((\mathbf{A}\mathbf{y})^\top\mathbf{q}_1 = \mathbf{y}^\top(\mathbf{A}^\top\mathbf{q}_1) = \lambda_1 (\mathbf{y}^\top\mathbf{q}_1) = 0\), nên \(\mathbf{A}(W) \subseteq W\).
- Quy nạp: Hạn chế \(\mathbf{A}|_W\) trên bất kỳ cơ sở trực chuẩn nào của \(W\) là một ma trận thực đối xứng kích thước \((n-1)\times(n-1)\). Theo giả thiết quy nạp, \(W\) sở hữu cơ sở trực chuẩn vector riêng \(\{\mathbf{q}_2, \dots, \mathbf{q}_n\}\) ứng với \(\lambda_2 \ge \dots \ge \lambda_n\) (\(\le \lambda_1\) do \(\lambda_1\) là cực đại toàn cục). Xếp cột thành \(\mathbf{Q} \in O(n)\) cho \(\mathbf{A} = \mathbf{Q}\boldsymbol{\Lambda}\mathbf{Q}^\top\). \(\blacksquare\)
Định lý 4.2 (Courant–Fischer Min-Max): Với \(\mathbf{A}=\mathbf{A}^\top\) có trị riêng \(\lambda_1 \ge \dots \ge \lambda_n\) và \(1 \le k \le n\):
Chứng minh: Chọn \(V^* = \operatorname{span}\{\mathbf{q}_1, \dots, \mathbf{q}_k\}\) cho mọi vector đơn vị \(\mathbf{x} = \sum_{i=1}^k c_i \mathbf{q}_i \in V^*\) thỏa \(R_{\mathbf{A}}(\mathbf{x}) = \sum_{i=1}^k \lambda_i c_i^2 \ge \lambda_k\), nên vế phải \(\ge \lambda_k\). Ngược lại, đặt \(W_0 = \operatorname{span}\{\mathbf{q}_k, \dots, \mathbf{q}_n\}\) (\(\dim = n-k+1\)). Với bất kỳ không gian con \(V\) có \(\dim V = k\), công thức chiều Grassmann đảm bảo \(\dim(V \cap W_0) \ge k + (n-k+1) - n = 1\). Lấy vector đơn vị \(\mathbf{x} \in V \cap W_0\) suy ra \(R_{\mathbf{A}}(\mathbf{x}) = \sum_{i=k}^n \lambda_i c_i^2 \le \lambda_k\), do đó \(\min_{\mathbf{x}\in V\setminus\{\mathbf{0}\}} R_{\mathbf{A}}(\mathbf{x}) \le \lambda_k\). Đẳng thức thứ hai suy tương tự khi thay \(\mathbf{A}\) bởi \(-\mathbf{A}\). \(\blacksquare\)
Định lý 4.3 (Phân rã Giá trị Kỳ dị — SVD) & Định lý 4.4 (Eckart–Young–Mirsky)#
Định lý 4.3 (Singular Value Decomposition — SVD): Mọi ma trận \(\mathbf{A} \in \mathbb{R}^{m\times n}\) hạng \(r \le p := \min(m, n)\) đều phân rã thành \(\mathbf{A} = \mathbf{U}\boldsymbol{\Sigma}\mathbf{V}^\top\) với \(\mathbf{U} \in O(m)\), \(\mathbf{V} \in O(n)\) và \(\boldsymbol{\Sigma} \in \mathbb{R}^{m\times n}\) đường chéo không âm \(\sigma_1 \ge \dots \ge \sigma_r > 0 = \sigma_{r+1} = \dots = \sigma_p\). Có ba biến thể kích thước: Full SVD (\(\mathbf{U}_{m\times m}\boldsymbol{\Sigma}_{m\times n}\mathbf{V}_{n\times n}^\top\)), Thin SVD (\(\mathbf{U}_p \boldsymbol{\Sigma}_p \mathbf{V}_p^\top\) với \(\mathbf{U}_p^\top\mathbf{U}_p = \mathbf{V}_p^\top\mathbf{V}_p = \mathbf{I}_p\)), và Compact SVD (\(\sum_{i=1}^r \sigma_i \mathbf{u}_i\mathbf{v}_i^\top\)).
Chứng minh Kiến thiết: Do \(\mathbf{A}^\top\mathbf{A} \in \mathbb{R}^{n\times n}\) đối xứng PSD, Định lý 4.1 cho \(\mathbf{A}^\top\mathbf{A} = \mathbf{V}\boldsymbol{\Lambda}\mathbf{V}^\top\) với \(\lambda_1 \ge \dots \ge \lambda_r > 0 = \lambda_{r+1} = \dots = \lambda_n\). Đặt \(\sigma_i = \sqrt{\lambda_i}\) và \(\mathbf{u}_i = \frac{1}{\sigma_i}\mathbf{A}\mathbf{v}_i\) (\(i \le r\)), ta có \(\mathbf{u}_i^\top\mathbf{u}_j = \frac{1}{\sigma_i\sigma_j}\mathbf{v}_i^\top(\mathbf{A}^\top\mathbf{A}\mathbf{v}_j) = \delta_{ij}\). Với \(i > r\), \(\|\mathbf{A}\mathbf{v}_i\|_2^2 = \lambda_i = 0 \implies \mathbf{A}\mathbf{v}_i = \mathbf{0}\). Mở rộng \(\{\mathbf{u}_1,\dots,\mathbf{u}_r\}\) thành cơ sở trực chuẩn của \(\mathbb{R}^m\) thu được \(\mathbf{A}\mathbf{V} = \mathbf{U}\boldsymbol{\Sigma} \implies \mathbf{A} = \mathbf{U}\boldsymbol{\Sigma}\mathbf{V}^\top\). \(\blacksquare\)
Đồng thời, các cột của \(\mathbf{U}\) và \(\mathbf{V}\) cung cấp ngay cơ sở trực chuẩn cho cả Bốn Không gian Con Cơ bản: \(\mathcal{C}(\mathbf{A}) = \operatorname{span}\{\mathbf{u}_1,\dots,\mathbf{u}_r\}\), \(\mathcal{N}(\mathbf{A}^\top) = \operatorname{span}\{\mathbf{u}_{r+1},\dots,\mathbf{u}_m\}\), \(\mathcal{C}(\mathbf{A}^\top) = \operatorname{span}\{\mathbf{v}_1,\dots,\mathbf{v}_r\}\), và \(\mathcal{N}(\mathbf{A}) = \operatorname{span}\{\mathbf{v}_{r+1},\dots,\mathbf{v}_n\}\), với chi phí SVD tất định là \(O(\min(m^2 n, m n^2))\) FLOPs.
Định lý 4.4 (Eckart–Young–Mirsky Optimal Low-Rank Approximation, 1936 & 1960): Cho \(\mathbf{A} \in \mathbb{R}^{m\times n}\) hạng \(r\) và cắt cụt hạng \(k \in \{0, 1, \dots, r-1\}\): \(\mathbf{A}_k := \sum_{i=1}^k \sigma_i \mathbf{u}_i\mathbf{v}_i^\top\). Với mọi ma trận \(\mathbf{B} \in \mathbb{R}^{m\times n}\) có \(\operatorname{rank}(\mathbf{B}) \le k\):
- Tối ưu theo Chuẩn Phổ: \(\|\mathbf{A} - \mathbf{B}\|_2 \ge \|\mathbf{A} - \mathbf{A}_k\|_2 = \sigma_{k+1}\).
- Tối ưu theo Chuẩn Frobenius: \(\|\mathbf{A} - \mathbf{B}\|_F \ge \|\mathbf{A} - \mathbf{A}_k\|_F = \sqrt{\sum_{i=k+1}^r \sigma_i^2}\).
Chứng minh Đầy đủ Hai phần:
-
Phần 1 (Chuẩn Phổ qua Rank–Nullity & Giao không gian Con): Phần dư \(\mathbf{A} - \mathbf{A}_k = \sum_{i=k+1}^r \sigma_i \mathbf{u}_i \mathbf{v}_i^\top\) có giá trị kỳ dị lớn nhất là \(\sigma_{k+1}\), suy ra \(\|\mathbf{A} - \mathbf{A}_k\|_2 = \sigma_{k+1}\). Với bất kỳ \(\mathbf{B}\) thỏa \(\operatorname{rank}(\mathbf{B}) \le k\), Định lý 1.1 cho \(\dim\mathcal{N}(\mathbf{B}) = n - \operatorname{rank}(\mathbf{B}) \ge n - k\). Xét \(\mathcal{V}_{k+1} := \operatorname{span}\{\mathbf{v}_1, \dots, \mathbf{v}_{k+1}\} \subseteq \mathbb{R}^n\) (\(\dim = k + 1\)). Theo công thức chiều Grassmann:
\[\dim\big(\mathcal{N}(\mathbf{B}) \cap \mathcal{V}_{k+1}\big) = \dim\mathcal{N}(\mathbf{B}) + \dim\mathcal{V}_{k+1} - \dim\big(\mathcal{N}(\mathbf{B}) + \mathcal{V}_{k+1}\big) \ge (n - k) + (k + 1) - n = 1\]Chọn vector đơn vị \(\mathbf{w} \in \mathcal{N}(\mathbf{B}) \cap \mathcal{V}_{k+1}\) (\(\|\mathbf{w}\|_2 = 1\)). Khai triển \(\mathbf{w} = \sum_{i=1}^{k+1} c_i \mathbf{v}_i\) (\(\sum c_i^2 = 1\)) và vì \(\mathbf{B}\mathbf{w} = \mathbf{0}\) cùng tính trực chuẩn của \(\{\mathbf{u}_i\}\):
\[\|\mathbf{A} - \mathbf{B}\|_2^2 \ge \|(\mathbf{A} - \mathbf{B})\mathbf{w}\|_2^2 = \|\mathbf{A}\mathbf{w}\|_2^2 = \left\|\sum_{i=1}^{k+1} \sigma_i c_i \mathbf{u}_i\right\|_2^2 = \sum_{i=1}^{k+1} \sigma_i^2 c_i^2 \ge \sigma_{k+1}^2 \sum_{i=1}^{k+1} c_i^2 = \sigma_{k+1}^2\]Lấy căn bậc hai thu được \(\|\mathbf{A} - \mathbf{B}\|_2 \ge \sigma_{k+1} = \|\mathbf{A} - \mathbf{A}_k\|_2\).
-
Phần 2 (Chuẩn Frobenius qua Bổ đề Nhiễu Giá trị Kỳ dị Weyl): Ký hiệu \(p = \min(m, n)\) và mở rộng \(\sigma_l(\mathbf{M}) = 0\) cho \(l > \operatorname{rank}(\mathbf{M})\).
- Bổ đề (Bất đẳng thức Weyl): Với mọi \(\mathbf{X}, \mathbf{Y} \in \mathbb{R}^{m\times n}\) và \(i, j \ge 1\) thỏa \(i + j - 1 \le p\), ta có \(\sigma_{i+j-1}(\mathbf{X} + \mathbf{Y}) \le \sigma_i(\mathbf{X}) + \sigma_j(\mathbf{Y})\).
Chứng minh Bổ đề: Xét ba không gian con trong \(\mathbb{R}^n\): \(S_1 = \operatorname{span}\{\mathbf{v}_i^X, \dots, \mathbf{v}_n^X\}\) (\(\dim = n - i + 1\)), \(S_2 = \operatorname{span}\{\mathbf{v}_j^Y, \dots, \mathbf{v}_n^Y\}\) (\(\dim = n - j + 1\)), và \(S_3 = \operatorname{span}\{\mathbf{v}_1^{X+Y}, \dots, \mathbf{v}_{i+j-1}^{X+Y}\}\) (\(\dim = i + j - 1\)). Áp dụng Grassmann hai lần: \(\dim(S_1 \cap S_2) \ge n - (i+j-2)\), suy ra \(\dim(S_1 \cap S_2 \cap S_3) \ge [n - (i+j-2)] + (i+j-1) - n = 1\). Lấy vector đơn vị \(\mathbf{w} \in S_1 \cap S_2 \cap S_3\): do \(\mathbf{w} \in S_3\) nên \(\|(\mathbf{X}+\mathbf{Y})\mathbf{w}\|_2 \ge \sigma_{i+j-1}(\mathbf{X}+\mathbf{Y})\); do \(\mathbf{w} \in S_1\) nên \(\|\mathbf{X}\mathbf{w}\|_2 \le \sigma_i(\mathbf{X})\); và do \(\mathbf{w} \in S_2\) nên \(\|\mathbf{Y}\mathbf{w}\|_2 \le \sigma_j(\mathbf{Y})\). Áp dụng bất đẳng thức tam giác hoàn tất Bổ đề Weyl. - Áp dụng Weyl cho \(\mathbf{A}\) và \(\mathbf{B}\): Đặt \(\mathbf{X} = \mathbf{A} - \mathbf{B}\), \(\mathbf{Y} = \mathbf{B}\) (nên \(\mathbf{X}+\mathbf{Y} = \mathbf{A}\)) và chọn \(j = k + 1\). Vì \(\operatorname{rank}(\mathbf{B}) \le k\) nên \(\sigma_{k+1}(\mathbf{B}) = 0\), suy ra với mọi \(i \in \{1, \dots, p - k\}\):
\[\sigma_{i+k}(\mathbf{A}) \le \sigma_i(\mathbf{A} - \mathbf{B}) + \sigma_{k+1}(\mathbf{B}) = \sigma_i(\mathbf{A} - \mathbf{B})\]
- Lấy tổng bình phương:
\[\|\mathbf{A} - \mathbf{B}\|_F^2 = \sum_{i=1}^p \sigma_i(\mathbf{A} - \mathbf{B})^2 \ge \sum_{i=1}^{p-k} \sigma_i(\mathbf{A} - \mathbf{B})^2 \ge \sum_{i=1}^{p-k} \sigma_{i+k}(\mathbf{A})^2 = \sum_{l=k+1}^r \sigma_l(\mathbf{A})^2 = \|\mathbf{A} - \mathbf{A}_k\|_F^2\]Lấy căn bậc hai hai vế hoàn tất chứng minh Định lý Eckart–Young–Mirsky. \(\blacksquare\)
- Bổ đề (Bất đẳng thức Weyl): Với mọi \(\mathbf{X}, \mathbf{Y} \in \mathbb{R}^{m\times n}\) và \(i, j \ge 1\) thỏa \(i + j - 1 \le p\), ta có \(\sigma_{i+j-1}(\mathbf{X} + \mathbf{Y}) \le \sigma_i(\mathbf{X}) + \sigma_j(\mathbf{Y})\).
Tính Duy nhất (Uniqueness Subtlety): Nếu có khe hở phổ \(\sigma_k > \sigma_{k+1}\), \(\mathbf{A}_k\) là nghiệm tối ưu duy nhất theo chuẩn Frobenius; nhưng theo chuẩn phổ \(\|\cdot\|_2\), nghiệm không duy nhất (giữ nguyên các mode đầu và chỉnh các mode \(i > k+1\) trong đoạn \([0, \sigma_{k+1}]\) không làm tăng \(\|\cdot\|_2\)).
Giả nghịch đảo Moore–Penrose, Độ nhạy Điều kiện & Ví dụ Số 3x2#
- Giả nghịch đảo (
Pseudoinverse): \(\mathbf{A}^+ := \mathbf{V}_r \boldsymbol{\Sigma}_r^{-1} \mathbf{U}_r^\top = \sum_{i=1}^r \frac{1}{\sigma_i}\mathbf{v}_i\mathbf{u}_i^\top \in \mathbb{R}^{n\times m}\). Nghiệm \(\mathbf{x}^+ = \mathbf{A}^+\mathbf{b}\) giải bài toán bình phương tối thiểu \(\min_{\mathbf{x}}\|\mathbf{A}\mathbf{x}-\mathbf{b}\|_2\) và trong trường hợp thiếu xác định (\(\mathcal{N}(\mathbf{A})\ne\{\mathbf{0}\}\)) chọn nghiệm có chuẩn \(\|\mathbf{x}\|_2\) nhỏ nhất (triệt tiêu thành phần thuộc \(\mathcal{N}(\mathbf{A})\)), trùng với giới hạn \(\lim_{\lambda\to 0^+}(\mathbf{A}^\top\mathbf{A} + \lambda\mathbf{I})^{-1}\mathbf{A}^\top\mathbf{b}\). - Chặn Nhiễu Tuyến tính: Nếu \(\mathbf{A}\mathbf{x}=\mathbf{b}\) khả nghịch bị nhiễu \(\mathbf{b} \mapsto \mathbf{b} + \delta\mathbf{b}\), từ \(\delta\mathbf{x} = \mathbf{A}^{-1}\delta\mathbf{b}\) và \(\|\mathbf{b}\|_2 \le \|\mathbf{A}\|_2\|\mathbf{x}\|_2\) suy ra chặn sai số tương đối:
Ví dụ Giải tay Đầy đủ (3x2 SVD, Chuẩn, Rank-1 Eckart–Young & \(\mathbf{A}^+\)): Tiếp tục xét \(\mathbf{A} = \begin{bmatrix} 3 & 2 \\ 2 & 3 \\ 2 & -2 \end{bmatrix}\):
- Từ \(\mathbf{A}^\top\mathbf{A} = \begin{bmatrix} 17 & 8 \\ 8 & 17 \end{bmatrix}\), giải \((17-\lambda)^2 - 64 = 0\) thu \(\lambda_1 = 25, \lambda_2 = 9\), suy ra \(\sigma_1 = 5, \sigma_2 = 3\) và \(\mathbf{v}_1 = \frac{1}{\sqrt{2}}[1, 1]^\top\), \(\mathbf{v}_2 = \frac{1}{\sqrt{2}}[1, -1]^\top\).
- Vector kỳ dị trái: \(\mathbf{u}_1 = \frac{1}{5}\mathbf{A}\mathbf{v}_1 = \frac{1}{\sqrt{2}}[1, 1, 0]^\top\), \(\mathbf{u}_2 = \frac{1}{3}\mathbf{A}\mathbf{v}_2 = \frac{1}{3\sqrt{2}}[1, -1, 4]^\top\), và hoàn thiện \(O(3)\) bằng \(\mathbf{u}_3 = \frac{1}{3}[2, -2, -1]^\top \in \mathcal{N}(\mathbf{A}^\top)\).
- Kiểm tra các chuẩn & Định lý 2.2 (\(r=2\)): \(\|\mathbf{A}\|_2 = 5\), \(\|\mathbf{A}\|_F = \sqrt{25+9} = \sqrt{34} \approx 5.831\), \(\|\mathbf{A}\|_* = 5+3 = 8\), \(\kappa_2(\mathbf{A}) = 5/3 \approx 1.667\); đúng với \(5 \le \sqrt{34} \le 5\sqrt{2}\) và \(\sqrt{34} \le 8 \le \sqrt{68}\).
- Xấp xỉ hạng 1 tốt nhất: \(\mathbf{A}_1 = \sigma_1\mathbf{u}_1\mathbf{v}_1^\top = \begin{bmatrix} 2.5 & 2.5 \\ 2.5 & 2.5 \\ 0 & 0 \end{bmatrix}\) với phần dư \(\mathbf{A}-\mathbf{A}_1 = \begin{bmatrix} 0.5 & -0.5 \\ -0.5 & 0.5 \\ 2 & -2 \end{bmatrix}\), đạt \(\|\mathbf{A}-\mathbf{A}_1\|_2 = 3.0 = \sigma_2\) và \(\|\mathbf{A}-\mathbf{A}_1\|_F = \sqrt{0.25\times 4 + 4\times 2} = 3.0 = \sigma_2\).
- Giả nghịch đảo: \(\mathbf{A}^+ = \frac{1}{5}\mathbf{v}_1\mathbf{u}_1^\top + \frac{1}{3}\mathbf{v}_2\mathbf{u}_2^\top = \frac{1}{45}\begin{bmatrix} 7 & 2 & 10 \\ 2 & 7 & -10 \end{bmatrix}\), cho \(\mathbf{A}^+[1, 5, 1]^\top = [3/5, 3/5]^\top\) khớp phương trình chuẩn.
Cầu nối trực tiếp tới Thích nghi LLM Hạng thấp (LoRA, DoRA, PiSSA): Khi tinh chỉnh LLM hàng chục tỷ tham số, cập nhật trọng số \(\Delta\mathbf{W} = \mathbf{W}_{\text{ft}} - \mathbf{W}_0\) có năng lượng tập trung ở \(r\) không gian kỳ dị hàng đầu (theo Eckart–Young). Thay vì cập nhật \(d_{\text{out}} d_{\text{in}}\) tham số, LoRA tham số hóa \(\Delta\mathbf{W} = \frac{\alpha}{r}\mathbf{B}\mathbf{A}\), DoRA tách riêng biên độ hàng/cột và hướng \(\mathbf{W}_0+\mathbf{B}\mathbf{A}\), còn PiSSA tách trực tiếp \(r\) thành phần chính SVD của \(\mathbf{W}_0\) để tinh chỉnh ngay từ bước 0 — toàn bộ động lực hình học này được phân tích sâu tại §2.2 và kiểm chứng tương tác ngay dưới đây.
1.5 Giải tích Ma trận qua Vi phân (Numerator Layout & Trace Identification)#
Đạo hàm Đơn biến, Khai triển Taylor & Đạo hàm Theo hướng#
Cho \(f: \mathbb{R} \to \mathbb{R}\), đạo hàm các hàm kích hoạt học sâu cốt lõi giải thích hiện tượng bão hòa gradient:
- Sigmoid: \(\sigma(z) = (1 + e^{-z})^{-1} \implies \sigma'(z) = \sigma(z)(1 - \sigma(z)) \in (0, 1/4]\) (nhân liên tiếp qua \(L\) tầng làm triệt tiêu gradient theo hệ số \((1/4)^L\)).
- Tanh & Softplus: \(\tanh'(z) = 1 - \tanh^2(z) \in (0, 1]\); \(\operatorname{softplus}(z) = \ln(1 + e^z) \implies \operatorname{softplus}'(z) = \sigma(z)\).
Khai triển Taylor bậc 2 cho \(f \in \mathcal{C}^2(\mathbb{R}^n)\) xung quanh \(\mathbf{x}\) viết gọn qua gradient và Hessian:
Khi \(f\) khả vi Fréchet tại \(\mathbf{x}\), đạo hàm theo hướng \(\mathbf{v}\) thỏa \(D_{\mathbf{v}} f(\mathbf{x}) = \nabla f(\mathbf{x})^\top \mathbf{v}\). Theo Cauchy–Schwarz trên mặt cầu đơn vị \(\|\mathbf{v}\|_2 = 1\), hướng giảm dốc nhất là \(-\nabla f(\mathbf{x}) / \|\nabla f(\mathbf{x})\|_2\).
Quy ước Khóa Numerator Layout & Vi phân Ma trận qua Vết (Trace Identification)#
Xuyên suốt Chương 02, ta khóa chặt Numerator Layout (Jacobian Layout) cho ánh xạ \(\mathbf{f}: \mathbb{R}^n \to \mathbb{R}^m\):
Với hàm vô hướng \(f: \mathbb{R}^n \to \mathbb{R}\) (\(m=1\)), Jacobian \(\mathbf{J}_f(\mathbf{x}) \in \mathbb{R}^{1\times n}\) là vector hàng, còn gradient là chuyển vị cột bảo toàn hình dạng \(\nabla_{\mathbf{x}} f(\mathbf{x}) := (\frac{\partial f}{\partial \mathbf{x}^\top})^\top \in \mathbb{R}^n\) sao cho \(df = \mathbf{J}_f(\mathbf{x})d\mathbf{x} = \nabla_{\mathbf{x}} f(\mathbf{x})^\top d\mathbf{x}\). Quy tắc dây chuyền cho hợp thành \(\mathbf{x} \xrightarrow{\mathbf{f}} \mathbf{u} \xrightarrow{\mathbf{g}} \mathbf{y}\) nhân đúng thứ tự ma trận: \(\mathbf{J}_{\mathbf{g}\circ\mathbf{f}}(\mathbf{x}) = \mathbf{J}_{\mathbf{g}}(\mathbf{f}(\mathbf{x}))\,\mathbf{J}_{\mathbf{f}}(\mathbf{x}) \in \mathbb{R}^{k \times n}\). Ma trận Hessian \(\mathbf{H}_f(\mathbf{x}) = \mathbf{J}_{\nabla f}(\mathbf{x}) \in \mathbb{R}^{n\times n}\) luôn đối xứng với \(f \in \mathcal{C}^2\) theo Định lý Schwarz.
Bổ đề Đồng nhất Vi phân (Differential Identification, Magnus & Neudecker): Với hàm vô hướng \(f(\mathbf{X})\) của ma trận \(\mathbf{X} \in \mathbb{R}^{m \times n}\), gradient bảo toàn hình dạng \(\nabla_{\mathbf{X}} f(\mathbf{X}) \in \mathbb{R}^{m\times n}\) (\([\nabla_{\mathbf{X}} f]_{ij} = \partial f / \partial X_{ij}\)) được nhận diện duy nhất thông qua khai triển vi phân bậc nhất:
(Chú ý: cách viết hình thức giúp bước cập nhật \(\mathbf{X}_{t+1} = \mathbf{X}_t - \eta \nabla_{\mathbf{X}} f(\mathbf{X}_t)\) khớp kích thước \(m\times n\) trực tiếp.) Áp dụng quy tắc vi phân \(d(\mathbf{A}\mathbf{B}) = (d\mathbf{A})\mathbf{B} + \mathbf{A}(d\mathbf{B})\), \(d(\mathbf{X}^\top) = (d\mathbf{X})^\top\), \(d\operatorname{tr}(\mathbf{Y}) = \operatorname{tr}(d\mathbf{Y})\) và tính vòng của vết \(\operatorname{tr}(\mathbf{A}\mathbf{B}) = \operatorname{tr}(\mathbf{B}\mathbf{A})\), ta suy diễn trọn vẹn 6 công thức nền tảng:
- Dạng tuyến tính (\(f(\mathbf{x}) = \mathbf{a}^\top \mathbf{x}\)): \(df = \mathbf{a}^\top d\mathbf{x} \implies \mathbf{J}_f(\mathbf{x}) = \mathbf{a}^\top\) và \(\nabla_{\mathbf{x}}(\mathbf{a}^\top\mathbf{x}) = \mathbf{a}\).
- Dạng toàn phương (\(f(\mathbf{x}) = \mathbf{x}^\top\mathbf{A}\mathbf{x}\), \(\mathbf{A}\) bất kỳ): \(df = (d\mathbf{x})^\top\mathbf{A}\mathbf{x} + \mathbf{x}^\top\mathbf{A}d\mathbf{x} = [(\mathbf{A}+\mathbf{A}^\top)\mathbf{x}]^\top d\mathbf{x}\), suy ra \(\nabla_{\mathbf{x}}(\mathbf{x}^\top\mathbf{A}\mathbf{x}) = (\mathbf{A}+\mathbf{A}^\top)\mathbf{x}\) (bằng \(2\mathbf{A}\mathbf{x}\) nếu \(\mathbf{A}=\mathbf{A}^\top\)) và \(\mathbf{H}_f(\mathbf{x}) = \mathbf{A} + \mathbf{A}^\top\).
- Tích vô hướng Vết (\(f(\mathbf{X}) = \operatorname{tr}(\mathbf{A}^\top\mathbf{X})\)): \(df = \operatorname{tr}(\mathbf{A}^\top d\mathbf{X}) \implies \nabla_{\mathbf{X}}\operatorname{tr}(\mathbf{A}^\top\mathbf{X}) = \mathbf{A}\) (và \(\nabla_{\mathbf{X}}\operatorname{tr}(\mathbf{A}\mathbf{X}) = \mathbf{A}^\top\)).
- Bình phương tối thiểu Frobenius (\(f(\mathbf{W}) = \|\mathbf{X}\mathbf{W} - \mathbf{Y}\|_F^2\)): Đặt \(\mathbf{E} := \mathbf{X}\mathbf{W}-\mathbf{Y}\), \(d\mathbf{E} = \mathbf{X}(d\mathbf{W})\), khi đó:
\[df = d\operatorname{tr}(\mathbf{E}^\top\mathbf{E}) = 2\operatorname{tr}(\mathbf{E}^\top d\mathbf{E}) = 2\operatorname{tr}(\mathbf{E}^\top\mathbf{X}\,d\mathbf{W}) = \operatorname{tr}\!\big((2\mathbf{X}^\top\mathbf{E})^\top d\mathbf{W}\big) \implies \nabla_{\mathbf{W}}\|\mathbf{X}\mathbf{W}-\mathbf{Y}\|_F^2 = 2\mathbf{X}^\top(\mathbf{X}\mathbf{W}-\mathbf{Y})\](Tương tự đối với \(\mathbf{X}\): \(\nabla_{\mathbf{X}}\|\mathbf{X}\mathbf{W}-\mathbf{Y}\|_F^2 = 2(\mathbf{X}\mathbf{W}-\mathbf{Y})\mathbf{W}^\top\).)
- Vi phân Ma trận Nghịch đảo (\(\mathbf{X} \in \operatorname{GL}_n(\mathbb{R})\)): Lấy vi phân đẳng thức \(\mathbf{X}\mathbf{X}^{-1} = \mathbf{I}_n\) cho \((d\mathbf{X})\mathbf{X}^{-1} + \mathbf{X}d(\mathbf{X}^{-1}) = \mathbf{0}\), suy ra:
\[d(\mathbf{X}^{-1}) = -\mathbf{X}^{-1}(d\mathbf{X})\mathbf{X}^{-1} \quad \text{và} \quad \nabla_{\mathbf{X}}(\mathbf{a}^\top\mathbf{X}^{-1}\mathbf{b}) = -\mathbf{X}^{-\top}\mathbf{a}\mathbf{b}^\top\mathbf{X}^{-\top}\]
- Công thức Jacobi & Đạo hàm \(\nabla_{\mathbf{X}} \ln\det\mathbf{X} = \mathbf{X}^{-\top}\): Gọi \(\mathbf{C}\) là ma trận phần bù đại số (cofactor matrix) của \(\mathbf{X}\), với ma trận phụ hợp \(\operatorname{adj}(\mathbf{X}) = \mathbf{C}^\top\) thỏa \(\mathbf{X}\operatorname{adj}(\mathbf{X}) = (\det\mathbf{X})\mathbf{I}_n\). Khai triển Laplace theo hàng \(i\) là \(\det\mathbf{X} = \sum_{j=1}^n X_{ij} C_{ij}\) (trong đó \(C_{ij}\) không phụ thuộc vào phần tử hàng \(i\)), cho \(\frac{\partial\det\mathbf{X}}{\partial X_{ij}} = C_{ij}\). Suy ra:
\[d(\det\mathbf{X}) = \sum_{i,j} C_{ij}\,dX_{ij} = \operatorname{tr}(\mathbf{C}^\top d\mathbf{X}) = \operatorname{tr}(\operatorname{adj}(\mathbf{X})\,d\mathbf{X}) = \det(\mathbf{X})\operatorname{tr}(\mathbf{X}^{-1}\,d\mathbf{X})\]Với \(\det\mathbf{X} > 0\) (hoặc \(\ln|\det\mathbf{X}|\) tổng quát), chia hai vế cho \(\det\mathbf{X}\) thu được:\[d(\ln\det\mathbf{X}) = \frac{d(\det\mathbf{X})}{\det\mathbf{X}} = \operatorname{tr}(\mathbf{X}^{-1}\,d\mathbf{X}) = \operatorname{tr}\!\big((\mathbf{X}^{-\top})^\top d\mathbf{X}\big) \implies \nabla_{\mathbf{X}}\ln\det\mathbf{X} = \mathbf{X}^{-\top}\]Kiểm chứng trên ma trận không đối xứng \(2\times 2\): Lấy \(\mathbf{X} = \begin{bmatrix} 2 & 1 \\ 0 & 3 \end{bmatrix}\) (\(\det\mathbf{X} = 6\)). Nhiễu vị trí \((2, 1)\) thành \(\varepsilon\) cho \(\det = 6 - \varepsilon \implies \left.\frac{\partial \ln\det\mathbf{X}}{\partial X_{21}}\right|_{\varepsilon=0} = -\frac{1}{6}\). Khớp chính xác \((\mathbf{X}^{-\top})_{21} = -\frac{1}{6}\), trong khi \((\mathbf{X}^{-1})_{21} = 0\) (chứng tỏ dấu chuyển vị \(^{\top}\) là tối quan trọng!).
1.6 Tích phân cho Machine Learning (Integration, Score-Function REINFORCE, Change-of-Variables & Monte Carlo)#
Quy tắc Leibniz & Đẳng thức Điểm số REINFORCE#
Với hàm \(f(x, \theta)\) và \(\partial_\theta f\) liên tục (hoặc bị chặn bởi hàm khả tích theo Định lý Hội tụ bị chặn Dominated Convergence Theorem), quy tắc Leibniz cho phép đưa đạo hàm vào trong dấu tích phân:
Xét hàm mục tiêu kỳ vọng \(\mathbb{E}_{x \sim p_\theta}[f(x)]\) trên miền lấy mẫu \(\Omega\) độc lập với \(\theta\). Sử dụng đẳng thức đạo hàm logarit \(\nabla_\theta \ln p_\theta(x) = \frac{\nabla_\theta p_\theta(x)}{p_\theta(x)} \iff \nabla_\theta p_\theta(x) = p_\theta(x)\nabla_\theta \ln p_\theta(x)\) (khi \(p_\theta(x) > 0\)), ta rút ra bộ ước lượng Score-Function / REINFORCE (Williams, 1992):
Vì \(\mathbb{E}_{p_\theta}[\nabla_\theta \ln p_\theta(x)] = \int \nabla_\theta p_\theta(x)\,dx = \nabla_\theta(1) = \mathbf{0}\), ta có thể trừ đi bất kỳ baseline \(b\) độc lập mẫu nào (\(\mathbb{E}[(f(x)-b)\nabla_\theta\ln p_\theta(x)]\)) mà không gây chệch, giúp giảm phương sai Monte Carlo mạnh mẽ trong học tăng cường chính sách (REINFORCE, PPO, và GRPO huấn luyện LLM suy luận RLVR). Khác với thủ thuật tái tham số hóa (reparameterization trick \(\mathbf{z} = g_\theta(\boldsymbol{\varepsilon})\) chỉ áp dụng cho phân phối liên tục và đòi hỏi \(f\) khả vi), REINFORCE hoạt động trên cả phần thưởng rời rạc không khả vi và không gian token rời rạc.
Tích phân Gaussian 1D & Đa biến#
- Tích phân Gaussian 1D: Đặt \(I = \int_{-\infty}^\infty e^{-x^2/2}\,dx > 0\). Theo Định lý Tonelli, \(I^2 = \int_{-\infty}^\infty \int_{-\infty}^\infty e^{-(x^2+y^2)/2}\,dx\,dy\). Đổi sang tọa độ cực \(x = r\cos\theta, y = r\sin\theta\) có định thức Jacobian \(\det\begin{bmatrix} \cos\theta & -r\sin\theta \\ \sin\theta & r\cos\theta \end{bmatrix} = r\):
\[I^2 = \int_0^{2\pi}\int_0^\infty e^{-r^2/2}\,r\,dr\,d\theta = 2\pi\Big[-e^{-r^2/2}\Big]_0^\infty = 2\pi \implies I = \sqrt{2\pi}\]
- Chuẩn hóa Gaussian Đa biến (\(\boldsymbol{\Sigma} \succ 0\)): Đặt \(Z := \int_{\mathbb{R}^d}\exp\!\big(-\frac{1}{2}(\mathbf{x}-\boldsymbol{\mu})^\top\boldsymbol{\Sigma}^{-1}(\mathbf{x}-\boldsymbol{\mu})\big)\,d\mathbf{x}\). Dịch chuyển \(\mathbf{u} = \mathbf{x}-\boldsymbol{\mu}\) (\(d\mathbf{u}=d\mathbf{x}\)), sau đó chéo hóa trực giao \(\boldsymbol{\Sigma} = \mathbf{Q}\boldsymbol{\Lambda}\mathbf{Q}^\top\) (\(\mathbf{Q} \in O(d), \lambda_i > 0\)) và đặt \(\mathbf{y} = \mathbf{Q}^\top\mathbf{u}\) (\(|\det\mathbf{Q}| = 1 \implies d\mathbf{u} = d\mathbf{y}\)). Biến đổi dạng toàn phương thành \(\sum_{i=1}^d \frac{y_i^2}{\lambda_i}\) giúp tách biến thành tích \(d\) tích phân 1D:
\[Z = \prod_{i=1}^d \int_{-\infty}^\infty e^{-y_i^2/(2\lambda_i)}\,dy_i = \prod_{i=1}^d \sqrt{2\pi\lambda_i} = (2\pi)^{d/2}(\det\boldsymbol{\Sigma})^{1/2}\]
Định lý 6.1: Đổi biến Đa biến (Change-of-Variables cho Normalizing Flows)#
Cho song ánh khả vi ngược \(\mathcal{C}^1\)-diffeomorphism \(T: \mathcal{Z} \to \mathcal{X}\) (\(\mathcal{Z}, \mathcal{X} \subseteq \mathbb{R}^d\)) với Jacobian không suy biến \(\mathbf{J}_T(\mathbf{z})\). Bảo toàn khối xác suất \(\int_{T(B)} p_X(\mathbf{x})\,d\mathbf{x} = \int_B p_Z(\mathbf{z})\,d\mathbf{z} = \int_B p_X(T(\mathbf{z}))|\det\mathbf{J}_T(\mathbf{z})|\,d\mathbf{z}\) trên mọi tập đo được \(B\) suy ra mật độ biến đổi chính xác tại \(\mathbf{x} = T(\mathbf{z})\):
Để tránh chi phí \(O(d^3)\) tính định thức dày đặc, các kiến trúc ghép tam giác (triangular coupling như RealNVP, Glow, MAF) ép \(\mathbf{J}_T\) thành tam giác dưới để \(\ln|\det\mathbf{J}_T| = \sum_{i=1}^d \ln|[\mathbf{J}_T]_{ii}|\) chỉ tốn \(O(d)\). Trong Continuous Normalizing Flows / Flow Matching (\(\frac{d\mathbf{z}(t)}{dt} = \mathbf{v}_\theta(\mathbf{z}(t), t)\)), áp dụng công thức Jacobi cho phương trình vi phân tức thời thu được \(\frac{d\ln p(\mathbf{z}(t))}{dt} = -\operatorname{tr}(\mathbf{J}_{\mathbf{v}_\theta})\).
Cầu phương Số học (Quadrature) vs. Tích phân Monte Carlo (Curse of Dimensionality)#
| Phương pháp (\(N\) lần gọi hàm trên \([0, 1]^d\)) | Sai số 1D (\(M\) nút) | Lưới Tensor \(d\) chiều (\(N = M^d\)) | Lời nguyền Số chiều (Curse of Dimensionality) |
|---|---|---|---|
Hình thang ghép (Composite Trapezoidal) |
\(O(M^{-2})\) | \(O(N^{-2/d})\) | Ở \(d=100\), để giảm sai số \(100\times\) cần \(100^{50} = 10^{100}\) điểm lưới — bất khả thi về mặt vật lý. |
Simpson ghép (Composite Simpson) |
\(O(M^{-4})\) | \(O(N^{-4/d})\) | Ở \(d=100\), tốc độ hội tụ chỉ còn \(N^{-0.04}\). |
Monte Carlo (MC) |
\(O(N^{-1/2})\) | \(O(N^{-1/2})\) (độc lập \(d\)!) | Với \(\hat{I}_N = \frac{1}{N}\sum_{i=1}^N f(\mathbf{x}_i)\), \(\operatorname{Var}(\hat{I}_N) = \frac{\sigma_f^2}{N} \implies \operatorname{RMSE} = \frac{\sigma_f}{\sqrt{N}}\). Thắng Hình thang khi \(d > 4\) và thắng Simpson khi \(d > 8\)! |
1.7 Tối ưu hóa Lồi, Tốc độ Hội tụ & Điều kiện KKT (Convex Optimization & Closed-Form Simplex Projection)#
Hệ phân cấp Tính chính quy (Regularity Hierarchy) & Bổ đề Giảm (Descent Lemma)#
Cho hàm khả vi \(f: \mathbb{R}^d \to \mathbb{R}\) có cận dưới \(f^* = \inf_{\mathbf{x}} f(\mathbf{x}) > -\infty\):
| Tính chất | Định nghĩa Bậc nhất (\(\forall \mathbf{x}, \mathbf{y} \in \mathbb{R}^d\)) | Tiêu chuẩn Bậc hai (\(\mathcal{C}^2\)) | Hệ quả Hội tụ Cốt lõi |
|---|---|---|---|
Lồi (Convex) |
\(f(\mathbf{y}) \ge f(\mathbf{x}) + \nabla f(\mathbf{x})^\top(\mathbf{y}-\mathbf{x})\) | \(\mathbf{H}_f(\mathbf{x}) \succeq \mathbf{0}\) | Mọi cực tiểu địa phương đều là cực tiểu toàn cục. |
\(L\)-Trơn (L-Smooth) |
\(\|\nabla f(\mathbf{y}) - \nabla f(\mathbf{x})\|_2 \le L\|\mathbf{y}-\mathbf{x}\|_2\) | \(-L\mathbf{I} \preceq \mathbf{H}_f(\mathbf{x}) \preceq L\mathbf{I}\) | Đảm bảo Bổ đề Giảm với bước an toàn \(\eta \le 1/L\) (ổn định \(\eta < 2/L\)). |
| \(\mu\)-Lồi mạnh (\(\mu > 0\)) | \(f(\mathbf{y}) \ge f(\mathbf{x}) + \nabla f(\mathbf{x})^\top(\mathbf{y}-\mathbf{x}) + \frac{\mu}{2}\|\mathbf{y}-\mathbf{x}\|_2^2\) | \(\mathbf{H}_f(\mathbf{x}) \succeq \mu\mathbf{I}\) | Cực tiểu \(\mathbf{x}^*\) duy nhất; số điều kiện \(\kappa := L/\mu \ge 1\). |
\(\mu\)-Polyak–Łojasiewicz (PL) |
\(\frac{1}{2}\|\nabla f(\mathbf{x})\|_2^2 \ge \mu\big(f(\mathbf{x}) - f^*\big)\) | (Không cần tính lồi!) | Đủ để GD hội tụ tuyến tính về nghiệm toàn cục \(f^*\). |
Bổ đề 7.1 (Descent Lemma & \(\mu\)-Lồi mạnh \(\implies\) \(\mu\)-PL):
- Bổ đề Giảm: Từ FTC dọc đoạn thẳng \(\mathbf{x} + t(\mathbf{y}-\mathbf{x})\), \(f(\mathbf{y})-f(\mathbf{x})-\nabla f(\mathbf{x})^\top(\mathbf{y}-\mathbf{x}) = \int_0^1 (\nabla f(\mathbf{x}+t(\mathbf{y}-\mathbf{x}))-\nabla f(\mathbf{x}))^\top(\mathbf{y}-\mathbf{x})\,dt \le \int_0^1 L t\|\mathbf{y}-\mathbf{x}\|_2^2\,dt = \frac{L}{2}\|\mathbf{y}-\mathbf{x}\|_2^2\). \(\blacksquare\)
- \(\mu\)-Lồi mạnh \(\implies\) \(\mu\)-PL: Cực tiểu hóa hai vế bất đẳng thức lồi mạnh theo \(\mathbf{y}\): vế phải đạt cực tiểu tại \(\mathbf{y} = \mathbf{x}-\frac{1}{\mu}\nabla f(\mathbf{x})\) bằng \(f(\mathbf{x})-\frac{1}{2\mu}\|\nabla f(\mathbf{x})\|_2^2 \le f^*\), biến đổi đại số ra \(\frac{1}{2}\|\nabla f(\mathbf{x})\|_2^2 \ge \mu(f(\mathbf{x})-f^*)\). \(\blacksquare\)
Các Phương pháp Tối ưu Bậc nhất & Bậc hai#
| Thuật toán | Quy tắc Cập nhật | Tốc độ Lồi \(L\)-Trơn | Tốc độ \(\mu\)-Lồi mạnh (\(\kappa=L/\mu\)) | Chi phí Bộ nhớ / Bước |
|---|---|---|---|---|
Gradient Descent (GD) |
\(\mathbf{x}_{t+1} = \mathbf{x}_t - \eta \nabla f(\mathbf{x}_t)\) | \(O(1/T)\): \(\frac{L\|\mathbf{x}_0-\mathbf{x}^*\|_2^2}{2T}\) | \((1 - \frac{1}{\kappa})^T\) (\(\eta=\frac{1}{L}\)); \((\frac{\kappa-1}{\kappa+1})^{2T}\) (\(\eta=\frac{2}{\mu+L}\)) | \(O(d)\) RAM; \(1\) gradient |
| Heavy-Ball Momentum | \(\mathbf{x}_{t+1} = \mathbf{x}_t - \eta\nabla f(\mathbf{x}_t) + \beta_{\text{mom}}(\mathbf{x}_t-\mathbf{x}_{t-1})\) | \(O(1/T)\) (có thể dao động phi toàn phương) | \((\frac{\sqrt{\kappa}-1}{\sqrt{\kappa}+1})^T\) trên toàn phương (\(O(\sqrt{\kappa}\ln\frac{1}{\varepsilon})\)) | \(O(d)\) RAM (\(1\) buffer) |
Nesterov NAG |
\(\mathbf{y}_t = \mathbf{x}_t + \beta_t(\mathbf{x}_t-\mathbf{x}_{t-1}),\; \mathbf{x}_{t+1} = \mathbf{y}_t - \eta\nabla f(\mathbf{y}_t)\) | \(O(1/T^2)\) (đạt cận dưới tối ưu bậc nhất!) | \((1 - \frac{1}{\sqrt{\kappa}})^T\) toàn cục (\(O(\sqrt{\kappa}\ln\frac{1}{\varepsilon})\)) | \(O(d)\) RAM (điểm nhìn trước) |
| Newton's Method | \(\mathbf{x}_{t+1} = \mathbf{x}_t - \mathbf{H}_f(\mathbf{x}_t)^{-1}\nabla f(\mathbf{x}_t)\) | Bậc hai cục bộ (cần điều chỉnh dương) | Bậc hai cục bộ: \(\|\mathbf{e}_{t+1}\|_2 \le \frac{M}{2\mu}\|\mathbf{e}_t\|_2^2\) | \(O(d^2)\) RAM; \(O(d^3)\) FLOPs |
L-BFGS |
Đệ quy 2 vòng \(m_{\text{hist}}\approx 10\) cặp \((\mathbf{s}_i, \mathbf{y}_i)\) | Hội tụ toàn cục với tìm kiếm đường Wolfe | Siêu tuyến tính cục bộ | \(O(m_{\text{hist}}d)\) RAM & FLOPs |
- Chứng minh tốc độ
GD: Trên hàm lồi \(L\)-trơn (\(\eta=1/L\)), Bổ đề Giảm cho \(-\frac{1}{2L}\|\nabla f(\mathbf{x}_t)\|_2^2 \ge f(\mathbf{x}_{t+1})-f(\mathbf{x}_t)\). Kết hợp với \(\|\mathbf{x}_{t+1}-\mathbf{x}^*\|_2^2 = \|\mathbf{x}_t-\mathbf{x}^*\|_2^2 - \frac{2}{L}\nabla f(\mathbf{x}_t)^\top(\mathbf{x}_t-\mathbf{x}^*) + \frac{1}{L^2}\|\nabla f(\mathbf{x}_t)\|_2^2 \le \|\mathbf{x}_t-\mathbf{x}^*\|_2^2 - \frac{2}{L}(f(\mathbf{x}_t)-f^*) + \frac{1}{L^2}\|\nabla f(\mathbf{x}_t)\|_2^2\) và thế hạng tử gradient thu được \(f(\mathbf{x}_{t+1})-f^* \le \frac{L}{2}(\|\mathbf{x}_t-\mathbf{x}^*\|_2^2 - \|\mathbf{x}_{t+1}-\mathbf{x}^*\|_2^2)\). Cộng tổng lồng từ \(t=0\) đến \(T-1\) cho \(\frac{L\|\mathbf{x}_0-\mathbf{x}^*\|_2^2}{2T}\). Dưới \(\mu\)-PL, thế \(\frac{1}{2}\|\nabla f\|_2^2 \ge \mu(f-f^*)\) thẳng vào Bổ đề Giảm lập tức cho \(f(\mathbf{x}_{t+1})-f^* \le (1-\frac{\mu}{L})(f(\mathbf{x}_t)-f^*)\). \(\blacksquare\) - Heavy-Ball vs. Nesterov (
NAG): Trên dạng toàn phươngSPD, ma trận đồng hành \(2\times 2\) của Heavy-Ball với \(\eta^* = \frac{4}{(\sqrt{L}+\sqrt{\mu})^2}, \beta_{\text{mom}}^* = (\frac{\sqrt{\kappa}-1}{\sqrt{\kappa}+1})^2\) đưa bán kính phổ xuống \(\sqrt{\beta_{\text{mom}}^*} = \frac{\sqrt{\kappa}-1}{\sqrt{\kappa}+1}\), giảm số vòng lặp từ \(O(\kappa)\) xuống \(O(\sqrt{\kappa})\). Tuy nhiên, Lessard et al. (2016) đã dựng phản ví dụ chứng minh Heavy-Ball có thể phân kỳ trên hàm lồi mạnh trơn phi toàn phương; ngược lại, tính toán gradient tại điểm nhìn trước \(\mathbf{y}_t\) trongNAG(giới hạn phương trình vi phân \(\ddot{\mathbf{x}} + \frac{3}{t}\dot{\mathbf{x}} + \nabla f(\mathbf{x}) = \mathbf{0}\)) bảo toàn tốc độ \(O(1/T^2)\) và \((1-1/\sqrt{\kappa})^T\) toàn cục. - Chứng minh Hội tụ Bậc hai của Newton: Giả sử \(\mathbf{H}_f(\mathbf{x})\succeq\mu\mathbf{I}\) và Hessian \(M\)-Lipschitz. Khi đó \(\mathbf{x}_{t+1}-\mathbf{x}^* = \mathbf{H}(\mathbf{x}_t)^{-1}[\mathbf{H}(\mathbf{x}_t)(\mathbf{x}_t-\mathbf{x}^*) - \int_0^1 \mathbf{H}(\mathbf{x}^*+s(\mathbf{x}_t-\mathbf{x}^*))(\mathbf{x}_t-\mathbf{x}^*)\,ds]\), lấy chuẩn suy ra \(\|\mathbf{x}_{t+1}-\mathbf{x}^*\|_2 \le \frac{1}{\mu}\int_0^1 M(1-s)\|\mathbf{x}_t-\mathbf{x}^*\|_2^2\,ds = \frac{M}{2\mu}\|\mathbf{x}_t-\mathbf{x}^*\|_2^2\). \(\blacksquare\)
- Cơ chế Đệ quy Hai vòng
L-BFGS(\(4m_{\text{hist}} d + O(d)\) FLOPs): Giữ \(m_{\text{hist}}\) cặp \(\mathbf{s}_i = \mathbf{x}_{i+1}-\mathbf{x}_i\), \(\mathbf{y}_i = \nabla f(\mathbf{x}_{i+1})-\nabla f(\mathbf{x}_i)\), \(\rho_i = (\mathbf{y}_i^\top\mathbf{s}_i)^{-1} > 0\), khởi hạt \(\gamma_t = \frac{\mathbf{s}_{t-1}^\top\mathbf{y}_{t-1}}{\mathbf{y}_{t-1}^\top\mathbf{y}_{t-1}}\): (1) \(\mathbf{q}\leftarrow\nabla f(\mathbf{x}_t)\); (2) Vòng lùi \(i=t-1\dots t-m_{\text{hist}}\): \(\alpha_i = \rho_i(\mathbf{s}_i^\top\mathbf{q}),\;\mathbf{q}\leftarrow \mathbf{q}-\alpha_i\mathbf{y}_i\); (3) \(\mathbf{r}\leftarrow \gamma_t\mathbf{q}\); (4) Vòng tiến \(i=t-m_{\text{hist}}\dots t-1\): \(\beta = \rho_i(\mathbf{y}_i^\top\mathbf{r}),\;\mathbf{r}\leftarrow \mathbf{r}+\mathbf{s}_i(\alpha_i-\beta)\); (5) Trả hướng \(-\mathbf{r}\).
Đối ngẫu Lagrange, Điều kiện KKT & Phép chiếu Simplex Dạng đóng#
Với bài toán \(\min_{\mathbf{x}} f(\mathbf{x})\) s.t. \(g_i(\mathbf{x}) \le 0\) và \(h_j(\mathbf{x}) = 0\), hàm Lagrange \(\mathcal{L}(\mathbf{x}, \boldsymbol{\lambda}, \boldsymbol{\nu}) = f(\mathbf{x}) + \sum_i \lambda_i g_i(\mathbf{x}) + \sum_j \nu_j h_j(\mathbf{x})\) (\(\boldsymbol{\lambda} \ge \mathbf{0}\)) luôn thỏa đối ngẫu yếu \(d^* \le p^*\); nếu \(f, g_i\) lồi, \(h_j\) affine và thỏa điều kiện Slater (tồn tại điểm trong tương đối khả thi chặt) thì đối ngẫu mạnh \(d^* = p^*\) xảy ra, và bốn điều kiện Karush–Kuhn–Tucker (KKT) là vừa cần vừa đủ cho tối ưu toàn cục:
- Dừng (
Stationarity): \(\nabla_{\mathbf{x}} f(\mathbf{x}^*) + \sum_i \lambda_i^* \nabla g_i(\mathbf{x}^*) + \sum_j \nu_j^* \nabla h_j(\mathbf{x}^*) = \mathbf{0}\). - Khả thi Gốc (
Primal Feasibility): \(g_i(\mathbf{x}^*) \le 0\), \(h_j(\mathbf{x}^*) = 0\). - Khả thi Đối ngẫu (
Dual Feasibility): \(\lambda_i^* \ge 0\). - Bù Lỏng (
Complementary Slackness): \(\lambda_i^* g_i(\mathbf{x}^*) = 0\;\forall i\).
Suy diễn KKT Trọn vẹn — Phép chiếu Euclid lên Đơn hình Xác suất \(\Delta^{n-1}\) (Duchi et al., ICML 2008):
Tìm \(\Pi_{\Delta^{n-1}}(\mathbf{y}) = \arg\min_{\mathbf{p} \ge \mathbf{0}, \sum p_i = 1} \frac{1}{2}\|\mathbf{p} - \mathbf{y}\|_2^2\). Lập Lagrangian \(\mathcal{L}(\mathbf{p}, \boldsymbol{\lambda}, \nu) = \frac{1}{2}\sum_{i=1}^n(p_i-y_i)^2 - \sum_{i=1}^n \lambda_i p_i + \nu(\sum_{i=1}^n p_i - 1)\) (\(\lambda_i \ge 0\)):
- Dừng: \(p_i^* - y_i - \lambda_i^* + \nu^* = 0 \implies p_i^* = y_i - \nu^* + \lambda_i^*\).
- Bù lỏng (\(\lambda_i^* p_i^* = 0\)): Nếu \(p_i^* > 0\) thì \(\lambda_i^* = 0 \implies p_i^* = y_i - \nu^* > 0\); nếu \(p_i^* = 0\) thì \(y_i - \nu^* = -\lambda_i^* \le 0\). Hợp hai nhánh cho công thức dạng đóng ("đổ nước" / water-filling): \(p_i^* = (y_i - \nu^*)_+ := \max(y_i - \nu^*, 0)\).
- Định lý Định danh Ngưỡng \(O(n\log n)\): Sắp giảm \(y_{(1)} \ge \dots \ge y_{(n)}\). Do chỉ số dương tạo tiền tố \(\{1, \dots, k^*\}\), phương trình \(\sum_{i=1}^{k^*}(y_{(i)}-\nu^*) = 1\) cho \(\nu^* = t_{k^*}\) với \(t_j := \frac{1}{j}(\sum_{i=1}^j y_{(i)} - 1)\). Ta chứng minh \(k^* = \max\{j : y_{(j)} - t_j > 0\}\): thật vậy, với \(j > k^*\), \(j(y_{(j)} - t_j) = \sum_{i=1}^{k^*}(y_{(j)}-\nu^*) + \sum_{i=k^*+1}^j(y_{(j)}-y_{(i)}) \le 0\) (vì \(y_{(j)} \le \nu^*\) và \(y_{(j)} \le y_{(i)}\)); còn với \(j \le k^*\), \(j(y_{(j)} - t_j) = \sum_{i=1}^j(y_{(j)}-\nu^*) + \sum_{i=j+1}^{k^*}(y_{(i)}-\nu^*) > 0\) (vì \(y_{(i)} \ge y_{(k^*)} > \nu^*\)). \(\blacksquare\)
Truy vết Số học Cụ thể: Chiếu \(\mathbf{y} = [1.8,\; 1.1,\; 0.2,\; -0.4]^\top\) lên \(\Delta^3\):
- \(j=1\): \(t_1 = (1.8-1)/1 = 0.80\), \(y_{(1)} - t_1 = +1.00 > 0\).
- \(j=2\): \(t_2 = (1.8+1.1-1)/2 = 0.95\), \(y_{(2)} - t_2 = +0.15 > 0\).
- \(j=3\): \(t_3 = (1.8+1.1+0.2-1)/3 = 0.70\), \(y_{(3)} - t_3 = -0.50 \le 0\).
- \(j=4\): \(t_4 = (1.8+1.1+0.2-0.4-1)/4 = 0.425\), \(y_{(4)} - t_4 = -0.825 \le 0\). Do đó \(k^* = 2\), \(\nu^* = 0.95\), và \(\mathbf{p}^* = [0.85,\; 0.15,\; 0,\; 0]^\top\). Kiểm chứng 4 điều kiện KKT: (1) \(p_i^* \ge 0\), \(\sum p_i^* = 1.0\); (2) nhân tử đối ngẫu \(\boldsymbol{\lambda}^* = [0,\; 0,\; 0.75,\; 1.35]^\top \ge \mathbf{0}\); (3) dừng \(\mathbf{p}^* - \mathbf{y} - \boldsymbol{\lambda}^* + \nu^*\mathbf{1} = \mathbf{0}\); (4) \(\lambda_i^* p_i^* = 0\;\forall i\).
Trụ cột 2 — Kiến trúc Hệ thống Autodiff, RandNLA, Bộ tối ưu 2026 & Roofline Phần cứng (Production Systems Architecture & SOTA 2026 Mechanics)#
2.1 Kiến trúc Tự động Vi phân (JVP vs. VJP, SAC, HVP) & Điều kiện Số học (Conditioning & Numerical Stability)#
Đồ thị Tính toán Wengert DAG: Lan truyền Xuôi JVP vs. Lan truyền Ngược VJP#
Xét hàm hợp trơn \(\mathbf{f} = \mathbf{f}_L \circ \dots \circ \mathbf{f}_1 : \mathbb{R}^n \to \mathbb{R}^m\) biểu diễn dưới dạng đồ thị có hướng không chu trình (Wengert tape / DAG) gồm \(K\) phép toán sơ cấp \(v_i = \phi_i(\operatorname{pa}(v_i))\). Theo quy tắc dây chuyền Numerator Layout, Jacobian toàn phần là tích các Jacobian cục bộ:
Thay vì nhân tường minh các ma trận trung gian khổng lồ, cơ chế Tự động Vi phân (Automatic Differentiation — Autodiff) tính hai toán tử tích ma trận–vector cơ bản:
- Chế độ Xuôi — Tích Jacobian–Vector (
JVP/ Tangent Pushforward): Nâng mỗi biến vô hướng \(v\) lên số đối ngẫu (dual number) \(v + \dot{v}\varepsilon\) trên vành \(\mathbb{R}[\varepsilon]/(\varepsilon^2)\) với \(\varepsilon^2 = 0\). Khai triển Taylor bậc nhất chính xác cho \(\phi(v + \dot{v}\varepsilon) = \phi(v) + \phi'(v)\dot{v}\varepsilon\), tính đồng thời giá trị gốc và đạo hàm tiếp tuyến \(\operatorname{JVP}_{\mathbf{f}}(\mathbf{x}, \dot{\mathbf{x}}) := (\mathbf{f}(\mathbf{x}),\, \mathbf{J}_{\mathbf{f}}(\mathbf{x})\dot{\mathbf{x}})\) chỉ trong 1 lượt xuôi mà không cần lưu băng kích hoạt (\(O(1)\) RAM đồ thị). Để dựng toàn bộ \(\mathbf{J}_{\mathbf{f}} \in \mathbb{R}^{m\times n}\) bằng cách đặt \(\dot{\mathbf{x}} = \mathbf{e}_1, \dots, \mathbf{e}_n\) cần \(O(n)\) lượt xuôi — tối ưu khi \(n \ll m\). - Chế độ Ngược — Tích Vector–Jacobian (
VJP/ Adjoint Pullback): Lưu trữ kích hoạt trung gian trong pha xuôi, rồi duyệt ngược đồ thị Wengert để tích lũy biến liên hợp \(\bar{v}_j = \sum_{i \in \operatorname{ch}(j)} (\frac{\partial\phi_i}{\partial v_j})^\top \bar{v}_i\), cho ra \(\operatorname{VJP}_{\mathbf{f}}(\mathbf{x}, \bar{\mathbf{y}}) := (\mathbf{f}(\mathbf{x}),\, \mathbf{J}_{\mathbf{f}}(\mathbf{x})^\top\bar{\mathbf{y}})\). Dựng toàn bộ \(\mathbf{J}_{\mathbf{f}}\) cần \(O(m)\) lượt ngược. Vì hàm mất mát học sâu luôn thu về vô hướng (\(m = 1\), \(\mathcal{L}: \mathbb{R}^d \to \mathbb{R}\), hạt giống \(\bar{y} = 1\)), chỉ 1 lượt ngược duy nhất (O(1)sweep, tốn \(\approx 2\text{–}3\times\) FLOPs pha xuôi chodgradvàwgrad) tính đủ toàn bộ gradient \(\nabla_{\boldsymbol{\theta}}\mathcal{L} \in \mathbb{R}^d\) dù \(d \sim 10^{11}\)!
| Nguyên thủy Autodiff | Phép toán Đại số | Bộ nhớ Đồ thị | Số lượt cho Full \(\mathbf{J}_{\mathbf{f}} \in \mathbb{R}^{m\times n}\) | Chế độ Tối ưu | API 2026 (PyTorch / JAX) |
|---|---|---|---|---|---|
JVP (Forward) |
\(\dot{\mathbf{y}} = \mathbf{J}_{\mathbf{f}}(\mathbf{x})\dot{\mathbf{x}}\) | \(O(1)\) (không băng tape) | \(O(n)\) lượt xuôi | \(n \ll m\), lớp ngoài HVP, độ nhạy ODE |
torch.func.jvp, jax.jvp |
VJP (Reverse) |
\(\bar{\mathbf{x}} = \mathbf{J}_{\mathbf{f}}(\mathbf{x})^\top\bar{\mathbf{y}}\) | \(O(L)\) kích hoạt (hoặc checkpoint) | \(O(m)\) lượt ngược | \(m \ll n\) (hàm mất mát vô hướng \(m=1\): \(O(1)\) lượt) | torch.func.vjp, jax.vjp |
Băng Kích hoạt vs. Lưu Điểm kiểm tra (Uniform, Revolve, SAC Min-Cut)#
Trong mạng sâu \(L\) tầng, pha ngược của phép nhân \(\mathbf{Y} = \mathbf{X}\mathbf{W}^\top\) đòi hỏi giữ lại tensor đầu vào \(\mathbf{X}\) để tính \(\nabla_{\mathbf{W}}\mathcal{L} = \bar{\mathbf{Y}}^\top\mathbf{X}\), đẩy dung lượng HBM tăng tuyến tính \(O(L)\). Có ba cấp độ tái tính toán (rematerialization):
- Chia đoạn Đồng đều (\(O(\sqrt{L})\) RAM — Chen et al., 2016): Chia \(L\) tầng thành \(k\) đoạn cỡ \(L/k\), chỉ giữ \(k\) tensor ranh giới và tính lại kích hoạt nội bộ khi quay lui. Đỉnh bộ nhớ \(M(k) = k + L/k\) đạt cực tiểu tại \(k^* = \sqrt{L}\), hạ RAM xuống \(O(\sqrt{L})\) với chi phí đúng \(1\) lượt xuôi phụ (\(\approx +33\%\) tổng FLOPs huấn luyện).
- Nhị thức
Revolve(\(O(\log L)\) RAM — Griewank & Walther, 2000): Với \(c\) khe nhớ và tối đa \(r\) lần tái tính toán mỗi bước, số bước dài nhất đảo ngược được tuân theo định danh nhị thức \(L_{\max}(c, r) = \binom{c+r}{c}\), đạt trần bộ nhớ \(O(\log L)\) cho chuỗi dài và ODE. - Lưu Điểm kiểm tra Chọn lọc 2024–2026 (
SAC/ AOTAutograd Min-Cut): Thay vì tính lại mù quáng các phépGEMMđắt đỏ,torch.compile(AOTAutogradmin-cut) vàtorch.utils.checkpointgiải bài toán lát cắt cực tiểu (min-cut / 0-1 knapsack) trên đồ thị FX: tái tính toán các toán tử bị nghẽn băng thông nhưng tốn ít FLOP và ăn nhiều HBM (RMSNorm,SwiGLU,dropout, xác suất softmax trong FlashAttention) trong khi lưu giữ đầu vào các khốiGEMMnặng tính toán. Kết quả thực tế cắt giảm 60%–80% bộ nhớ HBM kích hoạt nhưng chỉ tăng< 10%–15%thời gian mỗi bước.
Tích Hessian–Vector Chính xác của Pearlmutter (FoR HVP)#
Lưu trữ tường minh Hessian \(\mathbf{H} \in \mathbb{R}^{d\times d}\) với \(d=10^8\) tốn \(40\text{ PB}\) (fp32). Pearlmutter (1994) chứng minh có thể tính chính xác \(\mathbf{H}(\mathbf{x})\mathbf{v}\) chỉ trong chi phí \(O(1)\) lượt qua đẳng thức:
Kiến trúc Forward-over-Reverse (FoR) lồng phép tính gradient bằng VJP bên trong phép đẩy tiếp tuyến JVP (bằng cách cho thực thi DualArray đi qua băng ReverseTensor): vì lớp ngoài là chế độ xuôi, không hề có đồ thị ngược bậc hai nào được cấp phát, giữ bộ nhớ ở mức \(\approx 2\times\) một lượt gradient đơn (vượt trội so với Reverse-over-Reverse vốn dựng băng ngược kép). Kỹ thuật này trực tiếp vận hành ước lượng vết Hutchinson (\(\operatorname{tr}(\mathbf{H}) = \mathbb{E}_{\mathbf{z}}[\mathbf{z}^\top\mathbf{H}\mathbf{z}]\) trong lượng tử hóa GPTQ/QuIP#) và theo dõi độ sắc nét cực đại \(\lambda_{\max}(\mathbf{H})\).
Bình phương Số điều kiện, slogdet, Jitter & Bước Sai phân Trung tâm Tối ưu#
Cho ma trận thiết kế \(\mathbf{X} \in \mathbb{R}^{N_{\text{obs}}\times d}\) (\(N_{\text{obs}} \ge d\)) có SVD rút gọn \(\mathbf{X} = \mathbf{U}\boldsymbol{\Sigma}\mathbf{V}^\top\) với \(\sigma_1 \ge \dots \ge \sigma_d > 0\) và \(\kappa_2(\mathbf{X}) = \sigma_1/\sigma_d\):
Trong chuẩn IEEE-754 float64 (\(\varepsilon_{\text{mach}} = 2^{-53} \approx 1.11\times 10^{-16}\), có ~15.95 chữ số thập phân), phương trình chuẩn solve(X.T @ X, X.T @ y) chịu sai số \(O(\varepsilon_{\text{mach}}\,\kappa_2(\mathbf{X})^2)\), đánh mất \(2\log_{10}\kappa_2(\mathbf{X})\) chữ số thập phân! Chỉ cần đa cộng tuyến vừa phải \(\kappa_2(\mathbf{X}) = 10^8\), ma trận Gram đạt \(\kappa_2(\mathbf{X}^\top\mathbf{X}) = 10^{16}\), thổi bay toàn bộ 16/16 chữ số chính xác. Ngược lại, Householder QR hoặc SVD (np.linalg.lstsq) thao tác trực tiếp bằng phép biến đổi trực giao ổn định lùi (backward-stable), giữ sai số tỷ lệ với \(\kappa_2(\mathbf{X})\) cho hệ thặng dư nhỏ, bảo toàn ~8 chữ số chính xác tại \(\kappa = 10^8\).
Song song đó, hai hàng rào số học bắt buộc khác là:
slogdet& Cholesky Jitter: Ở \(d = 500\),np.log(np.linalg.det(K))tràn trên (5^{500} > 1.8e308) hoặc tràn dưới (0.2^{500} < 4.94e-324), trả rainf/-inf. Luôn dùngsign, logdet = np.linalg.slogdet(K)hoặc cộng thang nhiễu chéo tăng dần \(\mathbf{K} + \lambda\mathbf{I}\) cho phân rã Cholesky và tính \(2\sum_{i=1}^d \ln L_{ii}\).- Bước Sai phân Trung tâm Tối ưu (
float64): Công thức \(\frac{f(\mathbf{x}+\epsilon\mathbf{e}_j)-f(\mathbf{x}-\epsilon\mathbf{e}_j)}{2\epsilon}\) chịu sai số cắt cụt Taylor bậc hai \(O(\epsilon^2)\) và sai số triệt tiêu làm tròn dấu chấm động \(O(\varepsilon_{\text{mach}} / \epsilon)\). Cực tiểu hóa tổng sai số \(\epsilon^2 + \varepsilon_{\text{mach}}/\epsilon\) cho bước tối ưu \(\epsilon^* \approx \varepsilon_{\text{mach}}^{1/3} \approx 6\times 10^{-6}\) (eps = 1e-6), đạt độ chính xác \(\sim 10^{-11}\), tránh hoàn toàn bẫy sai phân ở \(\epsilon = 10^{-2}\) (lệch cắt cụt) và \(\epsilon = 10^{-14}\) (triệt tiêu mất14chữ số).
2.2 Đại số Tuyến tính Ngẫu nhiên (rSVD, CholeskyQR2) & Kiến trúc Hạng Thấp 2024–2026 (LoRA/DoRA/PiSSA/GaLore/MLA/SSD)#
Randomized SVD (Halko–Martinsson–Tropp, 2011) & Chuẩn hóa GPU 2024–2026#
SVD truyền thống tốn \(O(mn\min(m,n))\) FLOPs với các bước khử hai đường chéo tuần tự kém thân thiện với Tensor Cores. Randomized SVD (rSVD) chuyển nút cổ chai thành phép nhân ma trận BLAS-3 GEMM theo hai giai đoạn:
- Giai đoạn A (Tìm Không gian Cột gần đúng bằng Phác thảo & Lũy thừa QR xen kẽ): Chọn hạng mục tiêu \(k\) và bề rộng lấy dư \(p_{\text{ov}} \in [5, 10]\) (\(\ell = k + p_{\text{ov}} \ll \min(m, n)\)). Sinh ma trận thử Gaussian \(\boldsymbol{\Omega} \in \mathbb{R}^{n\times\ell}\) với phần tử \(\mathcal{N}(0, 1)\), tính \(\mathbf{Y}_0 = \mathbf{A}\boldsymbol{\Omega}\), \(\mathbf{Q}_0 = \operatorname{qr}(\mathbf{Y}_0)\). Thực hiện \(q \in \{1, 2\}\) vòng lặp không gian con (subspace power iteration) có trực giao hóa QR xen kẽ để ngăn các giá trị kỳ dị nhỏ bị xóa sổ bởi \((\epsilon_{\text{mach}})^{1/(2q+1)}\):
\[\tilde{\mathbf{Q}}_j = \operatorname{qr}(\mathbf{A}^\top\mathbf{Q}_{j-1}), \qquad \mathbf{Q}_j = \operatorname{qr}(\mathbf{A}\tilde{\mathbf{Q}}_j) \quad (j = 1, \dots, q)\]
- Giai đoạn B (Chiếu & SVD Kích thước Nhỏ): Tính \(\mathbf{B} = \mathbf{Q}_q^\top\mathbf{A} \in \mathbb{R}^{\ell\times n}\), phân rã SVD chính xác kích thước nhỏ \(\mathbf{B} = \tilde{\mathbf{U}}\boldsymbol{\Sigma}\mathbf{V}^\top\), rồi khôi phục \(\mathbf{U} = \mathbf{Q}_q\tilde{\mathbf{U}}[:, :k]\), \(\boldsymbol{\Sigma}_k\), \(\mathbf{V}_k^\top\).
Tổng chi phí giảm ngoạn mục xuống \(O\big((q+1)mn\ell + (m+n)\ell^2\big)\) FLOPs. Theo Định lý HMT (2011), kỳ vọng sai số phổ thỏa mãn:
Khi phổ suy giảm chậm, chỉ cần \(q = 2\) bước lũy thừa đã áp số mũ \(\frac{1}{2q+1} = \frac{1}{5}\) lên thừa số kích thước (kéo hệ số \(100\times\) xuống còn \(100^{0.2} \approx 2.51\times\)!). Trên hạ tầng GPU 2024–2026, chuẩn hóa RandBLAS / RandLAPACK (CQRRPT_GPU, BQRRP_GPU), thuật toán CholeskyQR2 (thay Householder QR chậm trễ truyền thông bằng 2 lượt \(\mathbf{R}_1 = \operatorname{chol}(\mathbf{Y}^\top\mathbf{Y}), \mathbf{Q}_1 = \mathbf{Y}\mathbf{R}_1^{-1}\) chạy thuần trên TensorCore GEMM), và thư viện phần cứng cusolverDnXgesvdr giúp rSVD đạt tốc độ cấp mili-giây cho ma trận trọng số \(10^4 \times 10^4\).
So sánh Kiến trúc PEFT Hạng thấp & Tiền huấn luyện Tiết kiệm Bộ nhớ#
| Phương pháp | Tham số hóa / Cơ chế Cập nhật | Thành phần Học vs. Đóng băng | Ý tưởng Đại số Tuyến tính | Lợi thế Bộ nhớ & Hội tụ |
|---|---|---|---|---|
LoRA (Hu et al., 2022) |
\(\mathbf{W} = \mathbf{W}_0 + \frac{\alpha}{r}\mathbf{B}\mathbf{A}\) (\(\mathbf{A}\sim\mathcal{N}\), \(\mathbf{B}=\mathbf{0}\)) | Khóa \(\mathbf{W}_0\); học \(\mathbf{A}\in\mathbb{R}^{r\times d_{\text{in}}}, \mathbf{B}\in\mathbb{R}^{d_{\text{out}}\times r}\) | Ép độ lệch \(\Delta\mathbf{W}\) vào không gian con hạng \(r \ll \min(d_{\text{out}}, d_{\text{in}})\) | Cắt \(>99\%\) tham số & trạng thái bộ tối ưu; gộp thẳng \(\mathbf{W}_0 + \frac{\alpha}{r}\mathbf{B}\mathbf{A}\) cho độ trễ suy luận \(0\) |
DoRA (Liu et al., ICML 2024) |
\(\mathbf{W}' = \mathbf{m} \odot \dfrac{\mathbf{W}_0 + \mathbf{B}\mathbf{A}}{\|\mathbf{W}_0 + \mathbf{B}\mathbf{A}\|_{\text{row}, 2}}\) | Học vector biên độ \(\mathbf{m}\) + hướng \(\mathbf{B}\mathbf{A}\) | Tách rời cập nhật biên độ và hướng; khắc phục tương quan dương giả tạo giữa chuẩn và góc của LoRA | Thu hẹp khoảng cách độ chính xác giữa LoRA và Full Fine-Tuning trên LLM/VLM |
PiSSA (Meng et al., NeurIPS 2024) |
\(\mathbf{W} = \underbrace{\mathbf{B}\mathbf{A}}_{\mathbf{U}_r\boldsymbol{\Sigma}_r\mathbf{V}_r^\top} + \mathbf{W}^{\text{res}}\) (\(\mathbf{B}=\mathbf{U}_r\boldsymbol{\Sigma}_r^{1/2}, \mathbf{A}=\boldsymbol{\Sigma}_r^{1/2}\mathbf{V}_r^\top\)) | Khóa phần dư \(\mathbf{W}^{\text{res}} = \sum_{i>r}\sigma_i\mathbf{u}_i\mathbf{v}_i^\top\); học \(\mathbf{A}, \mathbf{B}\) | Khởi tạo trực tiếp trên không gian kỳ dị chính (bằng Fast rSVD) thay vì nhiễu Gaussian có gradient ban đầu bằng \(0\) | Hội tụ nhanh hơn rõ rệt; QPiSSA chỉ lượng tử hóa NF4 lên \(\mathbf{W}^{\text{res}}\) năng lượng thấp nên giảm sai số lượng tử |
GaLore (Zhao et al., ICML 2024) |
Chiếu gradient \(\mathbf{R}_t = \mathbf{P}_t^\top\mathbf{G}_t\) theo SVD chu kỳ \(T\) | Cập nhật đầy đủ \(\mathbf{W}_t\); nén trạng thái Adam (\(\mathbf{M}_t, \mathbf{V}_t\)) về \(\mathbb{R}^{r\times n}\) | Trọng số pretraining không hạng thấp, nhưng quỹ đạo gradient trôi trong không gian con hạng thấp thay đổi chậm | Cho phép pretraining toàn tham số (vd. LLaMA-7B trên 1× RTX 4090 24 GB), tiết kiệm 65.5%–82.5% RAM bộ tối ưu |
DeepSeek-V2 / V3 MLA & Mamba-2 SSD (Đại số Tuyến tính trong Kiến trúc Chuỗi 2024–2026)#
- Multi-Head Latent Attention (
MLA, DeepSeek-V2/V3): Thay vì lưu \(2 n_h d_h\) phần tử/token/tầng của MHA (\(128 \times 128 \times 2 = 32{,}768\) phần tử trong DeepSeek-V3),MLAnén chung key–value vào một vector tiềm ẩn hạng thấp duy nhất \(\mathbf{c}_t^{KV} = \mathbf{W}^{DKV}\mathbf{h}_t \in \mathbb{R}^{d_c}\) (\(d_c = 512\), nén riêng vector tiềm ẩn \(32{,}768 / 512 = 64\times\)) kèm một khóa vị trí RoPE tách rời \(\mathbf{k}_t^R = \operatorname{RoPE}(\mathbf{W}^{KR}\mathbf{h}_t) \in \mathbb{R}^{d_h^R}\) (\(d_h^R = 64\)). Vì ma trận quay RoPE \(\mathbf{R}_{\Theta, t}\) phụ thuộc vị trí \(t\) sẽ chặn phép kết hợp ma trận nếu đặt chung, việc tách \(\mathbf{k}_t^R\) cho phép hấp thụ trọng số tĩnh ngoại tuyến (offline weight absorption) vào lúc suy luận: \(\tilde{\mathbf{W}}_i^Q = (\mathbf{W}_i^{UQ})^\top\mathbf{W}_i^{UK}\) và gộp \(\mathbf{W}_i^{UV}\) vào \(\mathbf{W}^O\):\[(\mathbf{q}_{t,i}^C)^\top\mathbf{k}_{j,i}^C = \big((\mathbf{W}_i^{UQ}\mathbf{c}_t^Q)^\top\mathbf{W}_i^{UK}\big)\,\mathbf{c}_j^{KV}\]Nhờ đó KV cache ở DeepSeek-V3 chỉ phải lưu \((\mathbf{c}_j^{KV}, \mathbf{k}_j^R)\) gồm \(512 + 64 = 576\) phần tử (1,152 bytes/token/layerởbf16), cắt \(1 - 576 / 32{,}768 = 98.24\%\) chiều KV mỗi token/tầng so với MHA chuẩn (khác với con số hệ thống nổi tiếng93.3%giảm KV cache và5.76xthông lượng giải mã tối đa của DeepSeek-V2 60 tầngMLAkhi đối chiếu vớiDeepSeek 67BDenseGQA95 tầng). - Structured State Space Duality (
Mamba-2 SSD, Dao & Gu, ICML 2024): Khi thu hẹp ma trận chuyển trạng thái thành \(\mathbf{A}_t = a_t\mathbf{I}_N\), hệ truy hồi \(\mathbf{h}_t = \mathbf{A}_t\mathbf{h}_{t-1}+\mathbf{B}_t\mathbf{x}_t,\; \mathbf{y}_t = \mathbf{C}_t^\top\mathbf{h}_t\) trải phẳng thành toán tử ma trận \(\mathbf{y} = \mathbf{M}\mathbf{x}\) với \(\mathbf{M} = \mathbf{L}\circ(\mathbf{C}\mathbf{B}^\top)\), trong đó \(L_{ji} = \prod_{k=i+1}^j a_k\) là ma trận tam giác dưới 1-semiseparable (mọi khối con dưới đường chéo đều có hạng \(\le 1\)). Bằng cách chia chuỗi \(T\) thành các khối cỡ \(Q \in \{64, 128\}\), các khối đường chéo được tính song song bằng TensorCoreBMM, còn các khối ngoài đường chéo truyền qua trạng thái khối hạng \(N\) — bảo toàn độ phức tạp tuyến tính \(O(T)\) nhưng chạy nhanh hơn Mamba-1 từ \(2\text{–}8\times\) nhờ thực thi \(>90\%\) FLOPs trên Tensor Cores.
2.3 Bộ tối ưu SOTA 2024–2026 (AdamW, Muon, Moonlight, SOAP, Schedule-Free)#
Tại sao Coupled \(L_2\) Hỏng trong Adam & Cách AdamW Sửa lỗi#
Trong SGD thuần, thêm phạt \(\frac{\lambda}{2}\|\boldsymbol{\theta}\|_2^2\) sinh bước \(\boldsymbol{\theta}_t = (1-\eta_t\lambda)\boldsymbol{\theta}_{t-1} - \eta_t\mathbf{g}_t\). Nhưng trong Adam gắn cặp \(L_2\) (coupled L2), thành phần \(\lambda\boldsymbol{\theta}_{t-1}\) bị cộng vào gradient trước khi chia cho mô-men bậc hai \(\sqrt{\hat{\mathbf{v}}_t}\):
Các tham số có lịch sử gradient lớn (\(\sqrt{\hat{v}_{t,j}} \gg 1\)) chịu mức co rút suy giảm yếu hơn hẳn các tham số có gradient nhỏ, phá vỡ bất biến tỷ lệ. AdamW (Loshchilov & Hutter, ICLR 2019) tách rời hoàn toàn suy giảm trọng số ra ngoài bộ tiền điều kiện thích nghi:
Muon (MomentUm Orthogonalized by Newton–Schulz) & Cơ sở Toán học Đa thức Bậc 5#
Được đề xuất bởi Keller Jordan (2024), đặt nền móng đối ngẫu chuẩn bởi Bernstein & Newhouse (2024) và mở rộng lên quy mô nghìn tỷ token bởi Moonshot AI (Moonlight, 2025), Muon đã được chuẩn hóa gốc trong PyTorch 2.9 (torch.optim.Muon).
- Giảm dốc nhất dưới Chuẩn Toán tử Phổ / RMS-to-RMS: Với chuẩn RMS vector \(\|\mathbf{x}\|_{\text{RMS}} := \frac{1}{\sqrt{d}}\|\mathbf{x}\|_2\), chuẩn toán tử cảm sinh của tầng \(\mathbf{W} \in \mathbb{R}^{d_{\text{out}} \times d_{\text{in}}}\) quy về chuẩn phổ có tỷ lệ:
\[\|\mathbf{W}\|_{\text{RMS}\to\text{RMS}} := \max_{\|\mathbf{x}\|_{\text{RMS}}=1} \|\mathbf{W}\mathbf{x}\|_{\text{RMS}} = \sqrt{\frac{d_{\text{in}}}{d_{\text{out}}}}\,\|\mathbf{W}\|_2 = \sqrt{\frac{d_{\text{in}}}{d_{\text{out}}}}\,\sigma_{\max}(\mathbf{W})\]Theo Định lý 2.3 (Đối ngẫu Phổ–Hạt nhân) và bất đẳng thức vết von Neumann, bài toán \(\arg\min_{\|\Delta\mathbf{W}\|_2 \le 1}\operatorname{tr}(\mathbf{G}^\top\Delta\mathbf{W})\) trên \(\mathbf{G} = \mathbf{U}_r\boldsymbol{\Sigma}_r\mathbf{V}_r^\top\) đạt cực tiểu duy nhất tại thừa số cực trực giao \(-\mathbf{U}_r\mathbf{V}_r^\top = -\operatorname{msign}(\mathbf{G})\) (hoặc \(-\sqrt{\frac{d_{\text{out}}}{d_{\text{in}}}}\mathbf{U}_r\mathbf{V}_r^\top\) dưới chuẩn RMS-to-RMS), san phẳng mọi giá trị kỳ dị khác không về \(1\) để mọi phương có độ cong nhỏ không bị lép vế.
- Động lượng Nesterov, Chuẩn hóa Frobenius & Đa thức Bậc 5 (
zeropower_via_newtonschulz5): Tính SVD chính xác mỗi bước quá chậm trên GPU.Muonthay thế bằng \(5\) phép nhân ma trậnbf16:- Cập nhật động lượng Nesterov (\(\mu_{\text{mom}} \approx 0.95\)): \(\mathbf{B}_t = \mu_{\text{mom}}\mathbf{B}_{t-1} + \mathbf{G}_t\), \(\tilde{\mathbf{G}}_t = \mathbf{G}_t + \mu_{\text{mom}}\mathbf{B}_t\).
- Chuẩn hóa Frobenius (và chuyển vị nếu \(d_{\text{out}} > d_{\text{in}}\) để ma trận Gram nhỏ hơn): \(\mathbf{X}_0 = \tilde{\mathbf{G}}_t / (\|\tilde{\mathbf{G}}_t\|_F + \epsilon)\). Do \(\|\tilde{\mathbf{G}}_t\|_2 \le \|\tilde{\mathbf{G}}_t\|_F\), mọi giá trị kỳ dị khởi đầu đảm bảo nằm trong \([0, 1]\).
- Lặp 5 bước đa thức lẻ bậc 5 với hệ số Jordan
(a, b, c) = (3.4445, -4.7750, 2.0315):\[\mathbf{A}_k = \mathbf{X}_k\mathbf{X}_k^\top, \qquad \mathbf{X}_{k+1} = a\mathbf{X}_k + b\mathbf{A}_k\mathbf{X}_k + c\mathbf{A}_k^2\mathbf{X}_k\]Vì \(\mathbf{X}_k = \mathbf{U}\boldsymbol{\Sigma}_k\mathbf{V}^\top\), phép lặp tác động độc lập đa thức vô hướng \(\phi(s) = 3.4445s - 4.7750s^3 + 2.0315s^5\) lên từng giá trị kỳ dị. Đa thức bậc ba kinh điển \(\phi_{\text{std}}(s) = 1.5s - 0.5s^3\) có độ dốc \(\phi'(0)=1.5\), sau \(5\) bước chỉ kéo \(s_0=0.01\) lên \(\approx 0.076\); trái lại, độ dốc lớn \(\phi'(0) = 3.4445\) của đa thức bậc 5 thổi bùng \(s_0=0.01 \xrightarrow{5\text{ bước}} 0.6989\), nén gọn toàn bộ đoạn \([0.01, 1.0]\) vào dải ổn định \([0.6818, 1.1344]\) mà không bao giờ phân kỳ!
Kỹ thuật Mở rộng Quy mô Moonlight (arXiv:2502.16982) & Các Biến thể 2025–2026#
Để Muon huấn luyện ổn định mô hình Moonlight-16B-A3B qua 5.7 nghìn tỷ token (đạt hiệu suất FLOP \(\sim 2\times\), tức chỉ tốn ~52% FLOPs của AdamW), nhóm nghiên cứu Moonshot AI đã tìm ra ba quy tắc không cần chỉnh siêu tham số:
- Suy giảm Trọng số Tách rời (
MuonW): Ngăn chuẩn RMS của trọng số và giá trị kích hoạt tăng đơn điệu gây trànbf16. - Hệ số Tỷ lệ RMS Bất biến Hình dạng (\(0.2\sqrt{\max(d_{\text{out}}, d_{\text{in}})}\)): Với ma trận bán trực giao \(\mathbf{O}_t \in \mathbb{R}^{d_{\text{out}}\times d_{\text{in}}}\) có hạng \(r = \min(d_{\text{out}}, d_{\text{in}})\) và \(\sigma_i \approx 1\), ta có \(\|\mathbf{O}_t\|_F \approx \sqrt{\min(d_{\text{out}}, d_{\text{in}})}\), suy ra biên độ RMS từng phần tử là:
\[\operatorname{RMS}(\mathbf{O}_t) = \sqrt{\frac{\min(d_{\text{out}}, d_{\text{in}})}{d_{\text{out}}\,d_{\text{in}}}} = \frac{1}{\sqrt{\max(d_{\text{out}}, d_{\text{in}})}}\]Trong khi đó
AdamWgiữ RMS bước cập nhật ổn định ở \([0.2, 0.4]\). Nhân thêm hệ số \(0.2\sqrt{\max(d_{\text{out}}, d_{\text{in}})}\) ép \(\operatorname{RMS}(\Delta\mathbf{W}_t) = 0.2\eta_t\) đồng nhất trên mọi lớp hình chữ nhật lẫn hình vuông (tích hợp trong PyTorch 2.9 quaadjust_lr_fn="match_rms_adamw"), cho phép dùng lại nguyên vẹn tốc độ học \(\eta_t\) và \(\lambda\) củaAdamW:\[\mathbf{W}_t = \mathbf{W}_{t-1} - \eta_t\Big(0.2\sqrt{\max(d_{\text{out}}, d_{\text{in}})}\;\mathbf{O}_t + \lambda\,\mathbf{W}_{t-1}\Big)\] - Định tuyến Tham số Lai (
Hybrid Parameter Routing): Chỉ định tuyếnMuoncho các ma trận ẩn 2D (Q/K/V/O,MLP,MoEexperts); bắt buộc định tuyếnAdamWchoembed_tokens(gradient thưa theo hàng Zipfian),lm_head(hiệu chuẩn logit), chuẩn hóa 1D (RMSNorm/LayerNorm) và vectorbias. - Cập nhật Frontier 2025–2026:
Polar Express(Amsel et al., 2025) thay bộ \((a,b,c)\) tĩnh bằng đa thức minimax thay đổi theo từng bước để tối ưu sai sốbf16, cònDion/Dion2/Dion3(Ahn et al., 2025–2026) giải bài toánall-gatherphân tán choMuonbằng trực giao hóa phân mảnh hạng thấp và Gram Newton–Schulz.
SOAP & Schedule-Free: Các Bộ tối ưu Bổ trợ 2024–2025#
SOAP(Vyas et al., ICLR 2025): Duy trì cặp nhân tử Kronecker Shampoo \(\mathbf{L}_t = \beta_2\mathbf{L}_{t-1} + (1-\beta_2)\mathbf{G}_t\mathbf{G}_t^\top\), \(\mathbf{R}_t = \beta_2\mathbf{R}_{t-1} + (1-\beta_2)\mathbf{G}_t^\top\mathbf{G}_t\), cập nhật cơ sở riêng \(\mathbf{Q}_L, \mathbf{Q}_R\) định kỳ qua QR + power iteration, xoay gradient \(\tilde{\mathbf{G}}_t = \mathbf{Q}_L^\top\mathbf{G}_t\mathbf{Q}_R\) để chạyAdamWtrong cơ sở riêng rồi xoay ngược lại — giảm ~40% số bước lặp (~35% thời gian thực) so vớiAdamW.Schedule-Free AdamW(Defazio et al., NeurIPS 2024 Oral): Kết hợp trung bình Polyak–Ruppert với đánh giá gradient tại điểm nội suy \(\mathbf{y}_t = (1-\beta_1)\mathbf{z}_t + \beta_1\mathbf{x}_t\), cập nhật gốc \(\mathbf{z}_{t+1}\) và cập nhật đánh giá \(\mathbf{x}_{t+1} = (1-c_{t+1})\mathbf{x}_t + c_{t+1}\mathbf{z}_{t+1}\) (\(c_{t+1} = 1/(t+1)\)) — loại bỏ hoàn toàn lịch giảm tốc cosine theo chân trời \(T\) cố định (lưu ý phải chuyển chế độ.eval_weights()trước khi kiểm định/lưu checkpoint).
2.4 Mô hình Roofline Phần cứng GPU (GEMV vs. GEMM trên H100/B200) & Độ ổn định bf16/fp8#
Mô hình Roofline & Điểm gãy Kiến trúc (Ridge Point)#
Theo mô hình Roofline (Williams et al., 2009), hiệu năng đạt được \(P\) (FLOP/s) bị chặn bởi trần tính toán đỉnh \(P_{\max}\) và băng thông bộ nhớ HBM \(B_{\max}\):
- NVIDIA H100 SXM5 (Hopper): \(P_{\max}^{\text{BF16}} \approx 989\text{ TFLOPS}\), \(P_{\max}^{\text{FP8}} \approx 1{,}979\text{ TFLOPS}\), \(B_{\max}^{\text{HBM3}} = 3.35\text{ TB/s} \implies\) Điểm gãy \(I_{\text{BF16}}^* \approx 295\text{ FLOP/B}\) (\(I_{\text{FP8}}^* \approx 591\text{ FLOP/B}\)).
- NVIDIA B200 (Blackwell): Băng thông HBM3e nhảy vọt lên \(8.0\text{ TB/s}\), kéo theo \(P_{\max}\) và điểm gãy FP8/FP4 càng đòi hỏi mật độ phép toán khối dày hơn.
| Cấp độ BLAS / Kernel | Quy mô Điển hình (\(b\) byte/phần tử) | Cường độ Số học (\(\text{AI}\)) | Giá trị Cụ thể (bf16, \(b=2\)) |
Chế độ trên H100 (\(I^*=295\)) |
|---|---|---|---|---|
BLAS-1 (axpy, norm, scale) |
Vector \(N\) chiều (\(2\) đọc, \(1\) ghi) | \(\frac{2N}{3Nb} = \frac{2}{3b}\) | \(0.33\text{ FLOP/B}\) | Nghẽn Băng thông HBM (~0.1% TensorCore) |
BLAS-2 (GEMV, decode batch=1) |
\(\mathbf{W}\in\mathbb{R}^{M\times K}, \mathbf{x}\in\mathbb{R}^K\) | \(\frac{2MK}{(MK+M+K)b} \approx \frac{2}{b}\) | \(1.0\text{ FLOP/B}\) | Nghẽn Băng thông HBM (lý do decode chậm) |
BLAS-3 (GEMM, prefill / NS5) |
\(\mathbf{A}\in\mathbb{R}^{M\times K}, \mathbf{B}\in\mathbb{R}^{K\times N}\) | \(\frac{2MNK}{(MK+KN+MN)b}\) | Với \(4096^2\): \(\approx 1{,}365\text{ FLOP/B}\) | Bão hòa Tính toán (lý do NS5 thắng SVD) |
Bẫy Đóng băng bf16 & Phát hiện Cộng dồn 14-bit Hopper FP8 của DeepSeek-V3#
- Đóng băng Cập nhật
bf16(Update Stagnation): Chuẩnbfloat16(1s/8e/7m) giữ nguyên dải độngfp32(\(\sim 10^{\pm 38}\)) nhưng phần định trị chỉ có \(\varepsilon_{\text{bf16}} = 2^{-7} \approx 7.81\times 10^{-3}\). Nếu lưu trọng số trực tiếp bằngbf16mà không giữ bản sao chủfp32master weights, mọi bước cập nhật có \(|\eta g_t| < \frac{1}{2}\varepsilon_{\text{bf16}}|w_t|\) bị phép làm tròn chẵn (round-to-nearest-even) nuốt chửng về đúng \(0.0\), làm mô hình đứng hình hoàn toàn ở pha học tinh. - Bẫy Cộng dồn 14-bit
WGMMA FP8trên Hopper (DeepSeek-V3,arXiv:2412.19437, 12/2024 & thư việnDeepGEMM, 2025): Báo cáo Kỹ thuật DeepSeek-V3 (12/2024) phát hiện lệnh TensorCoreWGMMA FP8trên Hopper thực chất chỉ giữ 14 bit định trị (14-bit fixed-point accumulator) sau dịch bit phải thay vì chuẩnfp3223-bit đủ — gây sai số triệt tiêu tích lũy trên các chiều nhân \(K\) dài! Cơ chế lượng tử hóa khối mịn của DeepSeek-V3 (1x128cho tensor kích hoạt,128x128cho ma trận trọng số ởE4M3, kèm thúc đẩy tổng riêng phần từ Tensor Cores sang thanh ghifp32của CUDA Cores sau mỗi \(N_C = 128\) phần tử — tức 4 bước WGMMA) ép độ lệch loss so vớibf16xuống dưới0.25%; sang năm 2025, thiết kế nhân FP8 GEMM này được DeepSeek mở nguồn thành thư việnDeepGEMM.
Trụ cột 3 — Công nghệ 2026, Case Studies Công nghiệp & Kỹ thuật Phòng vệ Số học (Modern Stack, Named Industry Case Studies & Numerical Failure Modes)#
3.1 Năm Nghiên cứu Tình huống Thực tế Từ Các Hệ thống Production (5 Named Industry Case Studies)#
Case 1 — Moonshot AI (Kimi / Moonlight 16B-A3B MoE, 5.7T Tokens, 2025): Mở rộng Muon + AdamW lên Quy mô Nghìn tỷ Token#
- Hệ thống & Quy mô: Moonlight-16B-A3B (16B tổng tham số / 3B kích hoạt, 27 tầng decoder, MoE kiểu DeepSeek-V3 với 64 expert định tuyến + 8 expert chia sẻ) tiền huấn luyện trên 5.7 nghìn tỷ token.
- Cơ chế & Kết quả: Khắc phục hoàn toàn hiện tượng bùng nổ chuẩn trọng số và phân kỳ biên độ theo kích thước lớp bằng cặp quy tắc
MuonW(decoupled weight decay) + hệ sốRMS\(0.2\sqrt{\max(d_{\text{out}}, d_{\text{in}})}\) + táchembed_tokens/lm_head/1D vềAdamW. Kết quả đạt hiệu suất FLOP gấp \(\sim 2\times\) (chỉ cần ~52% tổng FLOPs so vớiAdamWđể đạt cùng validation loss theo quy luật Chinchilla).
Case 2 — DeepSeek-V2 / V3 (MLA, 2024 & DeepGEMM, 2025): Nén KV Cache & Sửa lỗi Cộng dồn Hopper FP8#
- Hệ thống & Quy mô: Trong DeepSeek-V3 (\(n_h = 128\) đầu, \(d_h = 128\)), MHA tiêu chuẩn phải lưu \(128 \times 128 \times 2 = 32{,}768\) phần tử/token/tầng.
- Cơ chế & Kết quả:
MLAnén chung sang vector tiềm ẩn hạng512(\(32{,}768 / 512 = 64\times\)) kết hợp RoPE tách rời64chiều — tổng576phần tử (1,152 bytesởbf16), tức cắt98.24%số chiều KV mỗi tầng (\(1 - 576 / 32{,}768\)) so với MHA cùng kích thước; còn ở cấp kiến trúc hệ thống, DeepSeek-V2 (MLA60 tầng vs. DeepSeek 67B DenseGQA95 tầng) đạt kết quả nổi tiếng giảm93.3%KV cache, gấp \(5.76\times\) thông lượng giải mã tối đa và giảm42.5%chi phí huấn luyện cùng DeepSeekMoE. Ở pha tính toán FP8, DeepSeek-V3 (arXiv:2412.19437, 12/2024) giải quyết mất bit trên bộ cộng dồn14-bit WGMMAHopper bằng lượng tử khối mịn1x128/128x128kèm thúc đẩy tổng vềfp32sau mỗi \(N_C=128\), thiết kế sau đó được mở nguồn thành thư việnDeepGEMM(2025).
Case 3 — Phục vụ Đa khách hàng LoRA (Punica / S-LoRA / vLLM, 2023–2025): Kinh tế học Eckart–Young trên 1 GPU#
- Hệ thống & Quy mô: Một mô hình nền 7B FP16 chiếm ~14 GB VRAM, trong khi mỗi adapter LoRA hạng \(r \in \{8, 16, 32, 64\}\) chỉ nặng 10–80 MB (nhỏ hơn \(175\times\text{–}1{,}400\times\)).
- Cơ chế & Kết quả: Punica đạt thông lượng cao hơn \(12\times\) với độ trễ cộng thêm chỉ
~2 ms/token nhờ CUDA kernelBGMV/SGMV(Segmented Gather Matrix-Vector); S-LoRA mở rộng lên 2,000 adapter đồng thời trên 1× NVIDIA A100-80GB (nhanh hơn \(4\times\) vLLM thuần và \(30\times\) Hugging Face PEFT) bằng cách gộp toàn bộ adapter vào chung bể trang nhớ Unified Paging cùng KV blocks, tách phép chiếu nền chung \(X W_0\) khỏi phép nhân hạng thấp riêng lẻ \(x_i A_i B_i\).
Case 4 — Hiệp phương sai Tài chính Định lượng & Hồi quy CTR Quảng cáo (Ledoit–Wolf & Google FTRL-Proximal)#
- Bẫy Ma trận Ngẫu nhiên (\(p_{\text{assets}} \sim n_{\text{bars}}\)): Với danh mục S&P 500 (\(p_{\text{assets}} = 450\text{–}500\) cổ phiếu qua \(n_{\text{bars}} = 252\text{–}500\) phiên ngày, \(c = p_{\text{assets}}/n_{\text{bars}} \approx 1\)), Định lý Marchenko–Pastur (1967) chứng minh ngay cả khi hiệp phương sai thực bằng \(\sigma^2\mathbf{I}\), trị riêng mẫu vẫn trải rộng trên \([\lambda_-, \lambda_+] = \sigma^2(1 \pm \sqrt{c})^2\): khi \(c \to 1\), \(\lambda_{\min} \to 0\). Bộ tối ưu phương sai tối thiểu \(\mathbf{w}^* \propto \hat{\boldsymbol{\Sigma}}^{-1}\mathbf{1}\) nghịch đảo các trị riêng nhiễu nhỏ làm đòn bẩy gộp \(\sum|w_i|\) phình lên
10x–1,000x(thực tế thường vọt400x). - Giải pháp Sản xuất:
Ledoit–WolfShrinkage (2004) co rút tuyến tính \(\hat{\boldsymbol{\Sigma}}_{\text{LW}} = (1-\delta)\hat{\boldsymbol{\Sigma}} + \delta \mu_F \mathbf{I}\) (\(\mu_F = \operatorname{tr}(\hat{\boldsymbol{\Sigma}})/p_{\text{assets}}\)) theo hệ số \(\delta \in [0, 1]\) tối ưu MSE dạng đóng, nâng sàn trị riêng và ép \(\kappa\) xuống sâu. Tương tự trong Ad-Tech CTR hàng tỷ đặc trưng thưa (GoogleFTRL-Proximal, KDD 2013), việc nhúng phạt Ridge \(\lambda_2\) trực tiếp vào mẫu số từng tọa độ \((\frac{\beta + \sqrt{n_i}}{\alpha} + \lambda_2)^{-1}\) chặn đứng hiện tượng bùng nổ trọng số ở các đặc trưng hiển thị hiếm gặp.
Case 5 — Truy xuất Vector Quy mô lớn & Nén Embedding (OpenAI Matryoshka, Spotify Voyager, Su et al. Truncated Whitening)#
OpenAI text-embedding-3& Matryoshka (MRL, NeurIPS 2022): Huấn luyện lồng ghép hàm mất mát trên các tiền tố \(\{256, 512, 1024, 3072\}\) chiều cho phép cắt thẳng về 256 chiều (chỉ tốn \(\frac{1}{6}\) RAM so vớiada-0021536d) mà vẫn đạt MTEB ~62.0% — vượt mặt cả bảnada-002đầy đủ (61.0%), trong khi bản 3072d đạt64.6%.Spotify Voyager: ThayAnnoybằngHNSWkết hợp lượng tử hóaFP8 E4M3đạt tốc độ tìm kiếm láng giềng gần nhất nhanh gấp \(10\times\) và giảm \(4\times\) RAM (thường ghép PCA tiền xử lý để khử tương quan trước lượng tử hóa vô hướng).- Bẫy Làm trắng Đuôi Trị riêng (
Trailing Eigenvalue Whitening Trap): Embedding của BERT mang tính dị hướng (anisotropy). Phép làm trắng \(\tilde{\mathbf{x}} = (\mathbf{x}-\boldsymbol{\mu})\mathbf{U}\boldsymbol{\Lambda}^{-1/2}\) giúp đưa về đẳng hướng, nhưng trên các chiều đuôi 768d chứa nhiễu có \(\lambda_i \approx 10^{-4}\text{–}10^{-6}\), hệ số \(1/\sqrt{\lambda_i}\) khuếch đại nhiễu \(100\times\text{–}1{,}000\times\) (thường \(\sim 300\times\)), làm tụt thảm hại chất lượng xếp hạng tinh. Giải pháp chuẩn (Su et al., 2021): dùng Truncated Whitening (chỉ giữ và làm trắng top \(k = 256\) thành phần đầu, đồng thời giảm \(3\times\) RAM chỉ mục) hoặc điều chuẩn \((\boldsymbol{\Lambda} + \epsilon\mathbf{I})^{-1/2}\).
3.2 Sáu Chế độ Lỗi Số học & Tối ưu hóa Kinh điển (Six Numerical & Optimization Failure Modes Matrix)#
| Chế độ Lỗi | Nguyên nhân Toán học & Phần cứng | Triệu chứng Quan sát trong Production | Biện pháp Sửa lỗi Chuẩn xác |
|---|---|---|---|
| 1. Sụp đổ Số điều kiện Phương trình Chuẩn | inv(X.T @ X) @ X.T @ y bình phương \(\kappa_2(\mathbf{X}^\top\mathbf{X}) = \kappa_2(\mathbf{X})^2\). Tại \(\kappa_2(\mathbf{X}) = 10^8\), mất trọn 16/16 chữ số float64. |
Trọng số nhảy loạn qua mỗi lần chạy, văng LinAlgError, sai số dự báo \(O(1)\). |
Giải qua Householder QR hoặc SVD (np.linalg.lstsq) bảo toàn ~8 chữ số; hoặc thêm Ridge \(\lambda\mathbf{I}\). |
| 2. Hẻm núi Đặc trưng Chưa chuẩn hóa | Đặc trưng lệch thang đo (age \(\sim 10^2\) vs. revenue \(\sim 10^7\)) đẩy \(\kappa(\mathbf{H}) \sim 10^{10}\). GD cần \(O(\kappa)\) bước; L-BFGS tràn line-search bước 1. |
Loss dao động răng cưa (zigzag) dữ dội hoặc nổ thành NaN ngay epoch đầu. |
Chuẩn hóa \(z\)-score hoặc tiền điều kiện chéo Jacobi \(\mathbf{D}^{-1/2}\mathbf{H}\mathbf{D}^{-1/2}\) đưa \(\kappa \approx 1\). |
3. Bẫy \(L_2\) Gắn cặp trong Adam |
Phạt \(\lambda\mathbf{w}_t\) cộng vào \(\mathbf{g}_t\) bị chia cho \(\sqrt{\hat{\mathbf{v}}_t}\), làm trọng số gradient lớn chịu suy giảm yếu hơn. | Tối ưu \(\lambda\) dính chặt vào LR \(\eta\); khả năng tổng quát hóa kém. | Dùng suy giảm trọng số tách rời AdamW: \((1-\eta\lambda)\mathbf{w}_{t-1}\). |
4. Áp dụng Muon lên 1D / Embeddings |
Trực giao hóa \(\mathbf{U}\mathbf{V}^\top\) xóa tín hiệu biên độ trên 1D RMSNorm/bias và phá hỏng thang đo tần suất hàng thưa ở embed_tokens/lm_head. |
Loss giật cục trên token hiếm; nhiệt độ logit đầu ra trôi mất kiểm soát. | Giới hạn Muon (\(0.2\sqrt{\max(d_{\text{out}},d_{\text{in}})}\operatorname{NS}_5\)) cho ma trận ẩn 2D; định tuyến 1D/embed/head về AdamW. |
5. Tràn np.log(np.linalg.det(K)) |
Tại \(d=500\), \(\det(\mathbf{K}) = \prod \lambda_i\) vượt trần 1.8e308 hoặc tụt dưới ngưỡng subnormal 4.94e-324 \(\implies \ln(0) = -\infty\). |
Huấn luyện GP hoặc Normalizing Flow chết inf/-inf/NaN ngay khi \(d \ge 100\text{–}500\). |
Dùng np.linalg.slogdet(K) hoặc Cholesky + jitter leo thang (\(2\sum\ln L_{ii}\)). |
6. Silent Broadcasting, einsum mất trục & Sai phân sai bước |
(N, 1) - (N,) âm thầm tạo (N, N) (Karpathy bug); gõ thiếu chỉ số einsum ("bij,bjk->bi"); sai phân \(\epsilon = 10^{-2}\) (cắt cụt) hoặc \(10^{-14}\) (triệt tiêu). |
Loss đứng im tại phương sai mục tiêu, OOM bất ngờ, hoặc kiểm thử grad_check báo giả. |
Ép assert preds.shape == targets.shape, kiểm tra hình dạng sau einsum, dùng sai phân trung tâm \(\epsilon^* = 10^{-6}\). |
3.3 Cẩm nang Quyết định Bộ giải Tuyến tính & Bộ tối ưu (Solver & Optimizer Decision Playbooks)#
Cẩm nang 1: Ma trận Lựa chọn Bộ giải Hệ Tuyến tính#
| Bộ giải / Phân rã | Điều kiện Ma trận | Quy mô (\(n \times d\)) | Ngưỡng Chịu đựng \(\kappa\) | Độ phức tạp Thời gian / RAM | Hàng rào An toàn Production |
|---|---|---|---|---|---|
Cholesky (cholesky) |
Đối xứng SPD (\(\mathbf{A} \succ 0\)) |
Nhỏ–Vừa (\(d \le 15{,}000\)) | \(\kappa(\mathbf{A}) \lesssim 10^{12}\) (cấm lập \(\mathbf{X}^\top\mathbf{X}\) nếu \(\kappa(\mathbf{X}) > 10^6\)) | \(\frac{1}{3}d^3\) FLOPs (\(2\times\) nhanh hơn LU); \(O(d^2)\) RAM | Đối xứng hóa 0.5*(A+A.T); bọc thang jitter (1e-8 -> 1e-2); tái dùng \(\mathbf{L}\) cho \(2\sum\ln L_{ii}\). |
Householder QR / lstsq |
Chữ nhật đủ hạng (\(\mathbf{X}\in\mathbb{R}^{n\times d}, n\ge d\)) | Nhỏ–Vừa (\(n\le 10^6, d\le 10^4\)) | Tới \(\kappa(\mathbf{X}) \lesssim 10^{12}\) ở fp64 (tránh \(\kappa^2\)) |
\(2nd^2 - \frac{2}{3}d^3\) FLOPs (QR); \(O(nd)\) RAM | Truyền rõ rcond=None; kiểm tra rank và tỷ lệ s[0]/s[-1]. |
Full SVD (svd) |
Thiếu hạng, suy biến hoặc \(\kappa > 10^{10}\) | Nhỏ (\(m, n \le 5{,}000\)) | Bất kỳ (kể cả \(\kappa = \infty\)) | \(O(\min(mn^2, m^2n))\) FLOPs; \(O(mn)\) RAM | Cắt ngưỡng tol = max(m,n)*eps*s[0] hoặc điều chuẩn Tikhonov thay vì nghịch đảo nhiễu. |
Conjugate Gradient (CG) |
SPD thưa lớn hoặc không lưu ma trận (Ax operator) |
Rất lớn (\(d = 10^5\text{–}10^8\)) | Cần tiền điều kiện nếu \(\kappa > 10^4\) (\(O(\sqrt{\kappa})\) vòng) | \(O(k\cdot\operatorname{nnz}(\mathbf{A}))\) FLOPs; \(O(d)\) RAM | Bắt buộc tiền điều kiện Jacobi/IC; chuyển GMRES/MINRES nếu không đối xứng hoặc bất định. |
Randomized SVD (HMT) |
Ma trận lớn hạng thấp (\(k \ll \min(m,n)\)) | Rất lớn (\(m, n \le 10^7, k \le 512\)) | Phổ suy giảm nhanh hoặc phổ phẳng dùng \(q=1\text{–}2\) | \(O((q+1)mn\ell)\) GEMM; \(O((m+n)\ell)\) RAM |
Luôn dùng lấy dư \(p_{\text{ov}} \in [10, 20]\) và \(q \ge 1\) bước lũy thừa với QR xen kẽ. |
Cẩm nang 2: Ma trận Lựa chọn Bộ tối ưu#
| Bộ tối ưu | Quy mô Tham số | Độ cong / Tính lồi | Cỡ Batch | Hạng Tensor Tham số | Quy tắc Vận hành & Phòng lỗi |
|---|---|---|---|---|---|
SGD + Nesterov |
\(10^4\text{–}10^8\) | Trơn / điều kiện vừa (CNN, ResNet) | Nhỏ–Vừa (\(32\text{–}1024\)) | Mọi tensor | Tiêu tốn ít bộ nhớ nhất (\(1\times\) buffer); đòi hỏi chuẩn hóa đặc trưng chặt chẽ. |
L-BFGS |
\(\le 10^5\text{–}10^6\) | Lồi trơn hoặc giả Newton tất định | Toàn batch (deterministic) | Vector 1D làm phẳng | Hội tụ siêu tuyến tính gần cực tiểu; gãy ngay trên mini-batch nhiễu (\(\mathbf{s}_k^\top\mathbf{y}_k \le 0\)). Dùng float64 + tìm kiếm đường Armijo/Wolfe. |
AdamW |
\(10^6\text{–}10^{12}\) | Phi lồi, gradient thưa, dị hướng mạnh | Vừa–Lớn | Toàn bộ (nhất là 1D, embed, lm_head) |
Mặc định tin cậy (\(2\times\) trạng thái fp32); bắt buộc bật decoupled weight decay. |
Muon + AdamW Hybrid |
\(10^8\text{–}10^{12}+\) | Tầng ẩn Transformer / MoE sâu | Lớn (\(512\text{K–}4\text{M}\) token) | Muon: 2D ẩn; AdamW: 1D/embed/head | Hiệu suất FLOP \(\sim 2\times\) AdamW; bắt buộc \(0.2\sqrt{\max(d_{\text{out}},d_{\text{in}})}\) + weight decay tách rời + 5 bước NS5. |
Schedule-Free AdamW |
\(10^6\text{–}10^{10}\) | Phi lồi chưa biết trước tổng bước \(T\) | Nhỏ–Lớn | Như AdamW | Bỏ hoàn toàn lịch giảm tốc cosine; luôn bật .eval_weights() trước khi đo kiểm hoặc lưu checkpoint! |
3.4 Mã nguồn Phòng vệ NumPy Chuẩn Mực (Side-by-Side Defensive NumPy Snippets)#
Toàn bộ đoạn mã mẫu dưới đây tuân thủ tuyệt đối chuẩn pure-NumPy (0 import scipy, sklearn, hay torch), chạy trực tiếp trên Python 3.10+:
from __future__ import annotations
import math
import warnings
from typing import Callable
import numpy as np
# ==============================================================================
# 1. LOG-DETERMINANT MA TRẬN KERNEL SPD (Chống Overflow/Underflow tại d >= 500)
# ==============================================================================
def broken_logdet(K: np.ndarray) -> float:
# LỖI: det(K) tràn trên (> 1.8e308) hoặc tràn dưới về 0.0 -> log(0.0) = -inf.
return float(np.log(np.linalg.det(K)))
def safe_logdet_cholesky(
K: np.ndarray, base_jitter: float = 1e-8, max_tries: int = 7
) -> float:
"""Tính ln det(K) an toàn bằng Cholesky + thang jitter lũy tiến và fallback slogdet."""
assert K.ndim == 2 and K.shape[0] == K.shape[1], f"Expected square matrix, got {K.shape}"
K_sym = 0.5 * (K + K.T)
eye = np.eye(K_sym.shape[0], dtype=np.float64)
for attempt in range(max_tries):
jitter = 0.0 if attempt == 0 else base_jitter * (10.0 ** (attempt - 1))
try:
L = np.linalg.cholesky(K_sym + jitter * eye)
return float(2.0 * np.sum(np.log(np.diag(L))))
except np.linalg.LinAlgError:
continue
final_jitter = base_jitter * (10.0 ** max_tries)
sign, logdet = np.linalg.slogdet(K_sym + final_jitter * eye)
if sign <= 0.0:
raise np.linalg.LinAlgError("Matrix remained non-positive-definite after max jitter.")
return float(logdet)
# ==============================================================================
# 2. HỒI QUY BÌNH PHƯƠNG TỐI THIỂU (Tránh bình phương số điều kiện kappa^2)
# ==============================================================================
def broken_ols(X: np.ndarray, y: np.ndarray) -> np.ndarray:
# LỖI: Lập X.T @ X bình phương kappa(X)^2 -> mất sạch 16 chữ số float64 tại kappa=1e8.
return np.linalg.inv(X.T @ X) @ (X.T @ y)
def safe_ols(
X: np.ndarray, y: np.ndarray, cond_warn_threshold: float = 1e8
) -> np.ndarray:
"""Giải min ||X w - y||_2 bằng SVD/QR lstsq giữ độ chính xác tỷ lệ kappa(X)."""
assert X.ndim == 2 and y.ndim == 1 and X.shape[0] == y.shape[0], "Incompatible shapes"
w, _, rank, s = np.linalg.lstsq(X, y, rcond=None)
kappa = float(s[0] / s[-1]) if (s.size > 0 and s[-1] > 0.0) else math.inf
if rank < X.shape[1] or kappa > cond_warn_threshold:
warnings.warn(
f"Ill-conditioned design matrix: rank={rank}/{X.shape[1]}, kappa={kappa:.2e}.",
RuntimeWarning,
stacklevel=2,
)
return w
# ==============================================================================
# 3. KIỂM ĐỊNH ĐẠO HÀM SAI PHÂN TRUNG TÂM (Bước tối ưu eps* ~ 6e-6 trong float64)
# ==============================================================================
def broken_grad_check(
fn: Callable[[np.ndarray], float],
grad_fn: Callable[[np.ndarray], np.ndarray],
x: np.ndarray,
eps: float = 1e-14,
) -> float:
# LỖI: Bước 1e-14 triệt tiêu 14/16 chữ số float64; sai phân tiến chỉ đạt bậc O(eps).
g_ana = grad_fn(x)
g_num = np.zeros_like(x, dtype=np.float64)
f0 = float(fn(x))
for idx in np.ndindex(x.shape):
x_p = np.array(x, dtype=np.float64, copy=True)
x_p[idx] += eps
g_num[idx] = (float(fn(x_p)) - f0) / eps
return float(np.max(np.abs(g_ana - g_num)))
def safe_central_grad_check(
fn: Callable[[np.ndarray], float],
grad_fn: Callable[[np.ndarray], np.ndarray],
x: np.ndarray,
eps: float = 1e-6,
rtol: float = 1e-5,
atol: float = 1e-7,
) -> tuple[bool, float]:
"""Kiểm định gradient bằng sai phân trung tâm cân bằng cắt cụt O(eps^2) và làm tròn."""
x_f64 = np.asarray(x, dtype=np.float64)
g_ana = np.asarray(grad_fn(x_f64), dtype=np.float64)
assert g_ana.shape == x_f64.shape, f"Shape mismatch: {g_ana.shape} vs {x_f64.shape}"
g_num = np.zeros_like(x_f64)
for idx in np.ndindex(x_f64.shape):
x_plus = x_f64.copy()
x_minus = x_f64.copy()
x_plus[idx] += eps
x_minus[idx] -= eps
g_num[idx] = (float(fn(x_plus)) - float(fn(x_minus))) / (2.0 * eps)
denom = max(float(np.linalg.norm(g_ana) + np.linalg.norm(g_num)), 1e-12)
rel_err = float(np.linalg.norm(g_ana - g_num) / denom)
passed = bool(np.allclose(g_ana, g_num, rtol=rtol, atol=atol))
return passed, rel_err
# ==============================================================================
# 4. CHỐNG SILENT BROADCASTING & EINSUM MẤT TRỤC
# ==============================================================================
def broken_mse_and_bmm(
preds: np.ndarray, targets: np.ndarray, A: np.ndarray, B: np.ndarray
) -> tuple[float, np.ndarray]:
# LỖI 1: (N, 1) - (N,) tự động broadcast thành (N, N)!
loss = float(np.mean((preds - targets) ** 2))
# LỖI 2: Thiếu 'k' ở vế phải âm thầm cộng dồn mất trục cuối.
bmm = np.einsum("bij,bjk->bi", A, B)
return loss, bmm
def safe_mse_and_bmm(
preds: np.ndarray, targets: np.ndarray, A: np.ndarray, B: np.ndarray
) -> tuple[float, np.ndarray]:
"""Kiểm soát chặt hình dạng chống silent broadcasting và mất trục einsum."""
preds_1d = np.squeeze(preds, axis=-1) if (preds.ndim == 2 and preds.shape[1] == 1) else preds
assert preds_1d.ndim == 1 and targets.ndim == 1, "Expected 1D vectors"
assert preds_1d.shape == targets.shape, f"Shape mismatch: {preds_1d.shape} vs {targets.shape}"
loss = float(np.mean((preds_1d - targets) ** 2))
assert A.ndim == 3 and B.ndim == 3 and A.shape[0] == B.shape[0] and A.shape[2] == B.shape[1]
bmm = np.einsum("bij,bjk->bik", A, B)
assert bmm.shape == (A.shape[0], A.shape[1], B.shape[2]), f"Bad einsum shape: {bmm.shape}"
return loss, bmm
# ==============================================================================
# 5. MUON 5-STEP QUINTIC NEWTON-SCHULZ + MOONLIGHT RMS SCALING
# ==============================================================================
def zeropower_via_newtonschulz5(
G: np.ndarray, steps: int = 5, eps: float = 1e-7
) -> np.ndarray:
"""Xấp xỉ thừa số cực U V^T bằng đa thức lẻ bậc 5 của Keller Jordan."""
assert G.ndim == 2, f"Muon requires 2D weight gradients, got ndim={G.ndim}"
a, b, c = 3.4445, -4.7750, 2.0315
X = np.asarray(G, dtype=np.float64)
transposed = X.shape[0] > X.shape[1]
if transposed:
X = X.T
X = X / (float(np.linalg.norm(X)) + eps)
for _ in range(steps):
A = X @ X.T
B = b * A + c * (A @ A)
X = a * X + B @ X
return X.T if transposed else X
def moonlight_muon_step(
W: np.ndarray,
G: np.ndarray,
lr: float = 1e-2,
weight_decay: float = 0.01,
) -> np.ndarray:
"""Áp dụng bước Muon chuẩn Moonlight với hệ số RMS 0.2*sqrt(max(d_out, d_in))."""
assert W.ndim == 2 and W.shape == G.shape
d_out, d_in = W.shape
O_t = zeropower_via_newtonschulz5(G, steps=5)
rms_scale = 0.2 * math.sqrt(max(d_out, d_in))
return (1.0 - lr * weight_decay) * W - lr * rms_scale * O_t
Trụ cột 4 — Thực hành Lab 02 (linalg_lab) & Kiểm định Chất lượng Số học (Hands-On Workbench & Numerical Verification Rubric)#
Bài thực hành đồng hành tại labs/ch02-linalg-and-optimizers-workbench/ triển khai trọn vẹn hệ thống linalg_lab từ nguyên lý gốc bằng thuần Python + NumPy—biến mọi định lý ở Trụ cột 1, cơ chế Autodiff/RandNLA/Muon ở Trụ cột 2 và hàng rào phòng vệ ở Trụ cột 3 thành mã nguồn kiểm chứng tự động qua 14 ca kiểm thử pytest.
4.1 Kiến trúc Gói linalg_lab & Hợp đồng Không Phụ thuộc ABI Ngoài#
labs/ch02-linalg-and-optimizers-workbench/
├── pyproject.toml
├── README.md
├── src/
│ └── linalg_lab/
│ ├── __init__.py
│ ├── svd_and_lowrank.py
│ ├── calculus_and_autodiff.py
│ └── optimizers.py
├── scripts/
│ └── run_lab_demo.py
└── tests/
└── test_linalg_lab.py
Hợp đồng pyproject.toml & Môi trường Tương thích Host (Python >=3.10):
- Khai báo
name = "linalg-lab",version = "0.1.0",requires-python = ">=3.10", vàdependencies = ["numpy>=1.26", "pandas>=2.0"], cùng nhóm tùy chọndev = ["pytest>=8.0", "ruff>=0.4"]. - Cấu hình
[tool.setuptools.packages.find](where = ["src"]) và[tool.pytest.ini_options](testpaths = ["tests"],pythonpath = ["src"],addopts = "-v"). - Tuyệt đối
0import hoặc phụ thuộc vàoscipy,scikit-learnhaytorchtrong toàn bộsrc/,scripts/, vàtests/. Thiết kế tự chủ hoàn toàn này triệt tiêu rủi ro xung đột ABI nhị phân (ví dụAttributeError: _ARRAY_API not foundkhi góiscipy/scikit-learncũ gặpnumpy 2.x), đồng thời buộc học viên làm chủ mọi thuật toán từ gốc. Toàn bộ public@dataclassvà hàm lõi được tái xuất tạisrc/linalg_lab/__init__.pyqua__all__.
4.2 Hướng dẫn Từng bước Qua 3 Mô-đun Cốt lõi & CLI Workbench#
Bước 1: Chuẩn Ma trận, SVD/rSVD, Tuần hoàn FFT, Bộ thích nghi Hạng thấp & Điều kiện (src/linalg_lab/svd_and_lowrank.py)#
Mô-đun đóng gói kết quả chuẩn hóa bằng 6 @dataclass(frozen=True, slots=True):
MatrixNormProfile: lưushape,rank,frobenius_norm,spectral_norm,nuclear_norm,condition_number,singular_values.EckartYoungResult: lưurank_k,approx_matrix,spectral_error,theoretical_spectral_error,frobenius_error,theoretical_frobenius_error,retained_energy_ratio.RandomizedSVDResult: lưuU,singular_values,Vt,rank_k,oversampling,n_power_iter,approx_matrix,spectral_error,frobenius_error,exact_spectral_error,exact_frobenius_error.PiSSAInit: lưuB,A,W_residual,rank_r,reconstruction_error.ConditioningBenchmarkResult: lưukappa_design,kappa_gram,normal_eq_rel_error,qr_rel_error,svd_lstsq_rel_error,normal_eq_succeeded.LowRankAdapterBenchmarkRow: lưumethod("lora" | "dora" | "pissa"),rank_r,n_steps,initial_loss,final_loss,loss_history.
Các hàm kiểm chứng cốt lõi:
compute_matrix_norms(matrix: np.ndarray, tol: float | None = None) -> MatrixNormProfile: Kiểm tramatrix.ndim == 2, dùng thin SVDnp.linalg.svd(A, full_matrices=False), đặt ngưỡng hạng mặc địnhtol = max(m, n) * np.finfo(np.float64).eps * s[0], tính đủ chuẩn Frobenius, Phổ, Hạt nhân vàcondition_number(math.infkhi thiếu hạng).eckart_young_approximation(matrix: np.ndarray, rank_k: int) -> EckartYoungResult: Dựng \(\mathbf{A}_k\), đối chiếu sai số thực nghiệm với dự đoán lý thuyết \(\sigma_{k+1}\) và \(\sqrt{\sum_{i>k}\sigma_i^2}\) kèm tỷ lệ năng lượng giữ lại.randomized_svd(matrix: np.ndarray, rank_k: int, oversampling: int = 10, n_power_iter: int = 2, seed: int = 42) -> RandomizedSVDResult: Triển khai thuật toánHMTvớinp.random.default_rng(seed), bề rộng phác thảo \(\ell = \min(n, \text{rank\_k} + \text{oversampling})\), \(q\) bước lũy thừa xen kẽnp.linalg.qrvà SVD nhỏ trên \(\mathbf{B} = \mathbf{Q}^\top\mathbf{A}\).circulant_matvec_direct(first_col: np.ndarray, x: np.ndarray) -> np.ndarrayvàcirculant_matvec_fft(first_col: np.ndarray, x: np.ndarray) -> np.ndarray: Đối chiếu \(O(n^2)\) trực tiếp vớinp.fft.ifft(np.fft.fft(first_col) * np.fft.fft(x)).real(\(O(n\log n)\), Định lý 3.1).pissa_initialize(weight: np.ndarray, rank_r: int) -> PiSSAInit,dora_effective_weight(W0: np.ndarray, B: np.ndarray, A: np.ndarray, magnitude: np.ndarray, eps: float = 1e-12) -> np.ndarray, vàbenchmark_lora_dora_pissa_adaptation(d_out: int = 48, d_in: int = 32, rank_r: int = 4, n_steps: int = 80, lr: float = 0.05, seed: int = 42) -> list[LowRankAdapterBenchmarkRow]: So sánh trực tiếp hội tụ của"lora","dora"(chuẩn hóa hướng theo hàng nhânmagnitude) và"pissa"(\(\mathbf{B}=\mathbf{U}_r\boldsymbol{\Sigma}_r^{1/2}, \mathbf{A}=\boldsymbol{\Sigma}_r^{1/2}\mathbf{V}_r^\top\)) bằng gradient giải tích thuần NumPy.compare_normal_eq_vs_qr_svd(n_rows: int = 120, n_cols: int = 12, target_kappa: float = 1e7, noise_std: float = 1e-10, seed: int = 42) -> ConditioningBenchmarkResult: Chứng minh định lượng hiện tượng \(\kappa(\mathbf{X}^\top\mathbf{X}) = \kappa(\mathbf{X})^2\) khi giảiX.T @ Xso với HouseholderQRvà SVDlstsq.safe_logdet_cholesky(K: np.ndarray, base_jitter: float = 1e-8, max_tries: int = 7) -> floatvàledoit_wolf_shrinkage(returns: np.ndarray) -> tuple[np.ndarray, float, float, float]: Tính log-determinant an toàn qua thang jitter leo thang +slogdet, và tính ma trận hiệp phương sai co rút(sigma_lw, delta, kappa_sample, kappa_lw)cho dữ liệu(n_bars, p_assets).
Bước 2: Động cơ Autodiff JVP/VJP, FoR HVP, Normalizing Flows & Monte Carlo (src/linalg_lab/calculus_and_autodiff.py)#
Xây dựng hai cấu trúc vi phân tự động từ gốc không cần PyTorch:
DualArray(val, dot): Số học đối ngẫu trên vành \(\mathbb{R}[\varepsilon]/(\varepsilon^2)\) hỗ trợ đầy đủ+,-,*,/,@,.T,reshape,sum(),mean(),exp(),log(),tanh(),sigmoid(),sin(),cos(),square().ReverseTensor(data, requires_grad=True): Nút đồ thị Wengert tape hỗ trợ.backward(grad_output=None)và tương thích hoàn toàn khidatalàDualArray(giúp thực hiện Pearlmutter Forward-over-ReverseHVP!), kèm hàm ổn địnhlog1p_exp().- Bốn
@dataclass(frozen=True, slots=True):GradCheckResult(analytic_grad,numeric_grad,max_abs_error,relative_error,eps,passed),AutodiffBenchmarkRow(mode,n_inputs,m_outputs,n_sweeps,elapsed_ms,jacobian_max_error),IntegrationComparisonRow(method,dim,n_evals,estimate,exact_value,abs_error),CheckpointingProfile(n_layers,strategy,peak_activation_bytes,extra_forward_flops_ratio).
Các hàm chức năng chính:
jvp(fn, x, v),vjp(fn, x, cotangent),value_and_grad(fn, x): Trả về chính xác \(\mathbf{J}_{\mathbf{f}}\mathbf{v}\) và \(\mathbf{J}_{\mathbf{f}}^\top\bar{\mathbf{y}}\) theo quy ước Numerator Layout.hvp_forward_over_reverse(fn, x, v): Chạytx = ReverseTensor(DualArray(x_f64, v_f64))quafnrồi gọi.backward(DualArray(1.0, 0.0)), trích trực tiếp(tx.grad.val, tx.grad.dot)trongO(1)lượt mà không dựng băng ngược bậc hai.compute_full_jacobian_jvp,compute_full_jacobian_vjp,benchmark_jvp_vs_vjp(n_in=64, m_out=4, repeats=5, seed=42): Kiểm chứngvjpchỉ tốn4lượt so với64lượt củajvpkhi \(m_{\text{out}} \ll n_{\text{in}}\).central_diff_jacobian(fn, x, eps=1e-6)vàcentral_diff_grad_check(fn, grad_fn, x, eps=1e-6, rtol=1e-5, atol=1e-7): Đối chiếu sai phân trung tâm tại bước tối ưu \(\epsilon^* = 10^{-6}\).triangular_flow_log_prob(z, scale_log, shift): Kiểm chứng Định lý Đổi biến Đa biến \(\ln p_X(\mathbf{x}) = \ln p_Z(\mathbf{z}) - \sum_i \ln|[\mathbf{J}_T]_{ii}|\) trên tầng ghép tam giác \(O(d)\).compare_quadrature_vs_monte_carlo(dims=(2, 6, 10), budget_evals=4096, seed=42): Tích phân hàm kiểm chuẩn \(g_d(\mathbf{x}) = \prod_{i=1}^d \frac{\pi}{2}\sin(\pi x_i)\) trên \([0, 1]^d\) (tích phân chính xác \(= 1.0\)) giữa"trapezoidal_grid"(\(O(N^{-2/d})\)) và"monte_carlo"(\(O(N^{-1/2})\)).simulate_checkpointing_memory(n_layers=64, gemm_act_bytes=16_777_216, norm_act_bytes=8_388_608, gemm_flops_share=0.88): Định lượng mức giảm đỉnh HBM và chi phí tính lại qua ba chiến lược"full_tape","uniform_sqrt", và"selective_sac".
Bước 3: Tối ưu hóa Lồi, KKT Simplex, AdamW, Muon/Moonlight, Schedule-Free & bf16 (src/linalg_lab/optimizers.py)#
Định nghĩa hằng số NS5_COEFFS: tuple[float, float, float] = (3.4445, -4.7750, 2.0315) cùng 2 @dataclass(frozen=True, slots=True):
SimplexKKTReport:projected,nu_star,active_support_size,primal_residual,dual_min_multiplier,stationarity_residual,complementary_slackness_residual,kkt_satisfied.OptimizerTrajectoryResult:optimizer_name,n_steps,initial_loss,final_loss,final_grad_norm,loss_history,update_rms_history.
Các thành phần thuật toán và đánh giá:
project_onto_simplex(y)vàverify_simplex_kkt(y, tol=1e-10): Thực thi thuật toán Duchi et al. (2008) \(O(n\log n)\) trả về(p_star, nu_star, k_star)và kiểm chứng toàn bộ 4 điều kiện KKT.GradientDescent(lr, momentum=0.0, variant="gd")("gd" | "heavy_ball" | "nesterov"),LBFGS(history_size=10, max_backtrack=25, c1=1e-4)(với.compute_direction(grad)và.step(fn_val_grad, x)hai vòng + tìm kiếm đường Armijo + bảo vệ độ cong \(\mathbf{s}_k^\top\mathbf{y}_k > 10^{-12}\)), vàAdamW(..., decoupled=True)(tách bạch chế độdecoupled=Truevs. lỗiL2gắn cặpdecoupled=False).zeropower_via_newtonschulz5(G, steps=5, eps=1e-7),Muon(lr=1e-2, momentum=0.95, weight_decay=0.01, ns_steps=5, rms_match_adamw=True), vàHybridMuonAdamW(định tuyếnndim >= 2ngoài{"embed", "lm_head"}sangMuon; 1D/embed/lm_headsangAdamW).ScheduleFreeAdamW(lr=1e-2, beta1=0.9, beta2=0.999, eps=1e-8, weight_decay=0.0)duy trì bộ ba(z, x_eval, v)với.eval_weights(),.train_weights(),.step(grad).- Bộ công cụ đấu trường & kiểm chứng phần cứng:
make_anisotropic_quadratic,run_convex_optimizer_arena,run_matrix_optimizer_arena, vàverify_bf16_stagnation_vs_fp32_master(mô phỏng làm tròn chẵn bit mantissa0..15củabfloat16chứng minh thuầnbf16đóng băng ở0.0biến thiên khi bản chủfp32tiến triển đều đặn).
Bước 4: Thực thi Một lệnh CLI (scripts/run_lab_demo.py) & Lược đồ workbench_panels#
Từ thư mục gốc labs/ch02-linalg-and-optimizers-workbench/, chạy kịch bản trình diễn:
python scripts/run_lab_demo.py --n-rows 120 --n-cols 12 --target-kappa 1e7 --rsvd-dim 128 --rsvd-rank 12 --convex-kappa 100.0 --n-steps 120 --seed 42 --json-out artifacts/workbench_summary.json
CLI hỗ trợ đầy đủ 9 cờ tham số (--n-rows, --n-cols, --target-kappa, --rsvd-dim, --rsvd-rank, --convex-kappa, --n-steps, --seed, --json-out) và xuất ra chuẩn xác 4 khối báo cáo trên stdout:
[1] Subspaces, Eckart-Young, rSVD, Low-Rank Adapters & Conditioning[2] Autodiff JVP/VJP, Pearlmutter HVP, Flows & Monte Carlo vs. Quadrature[3] Convex & SOTA Optimizers (KKT Simplex, GD/NAG/L-BFGS, AdamW, Muon/Moonlight)[4] Numerical Guardrails Summary (slogdet, Ledoit-Wolf, bf16 Master Rescue)
Tệp JSON xuất từ --json-out chứa 5 khóa cấp cao ("config", "workbench_panels", "svd_and_lowrank", "calculus_and_autodiff", "optimizers"), trong đó "workbench_panels" chứa cấu trúc chuẩn gồm "kpis" (6 chỉ số kpi_normal_eq_vs_qr, kpi_rsvd_q2_error, kpi_hvp_precision, kpi_simplex_kkt, kpi_muon_ns5_band, kpi_bf16_rescue), "bars" (4 biểu đồ bar_conditioning_rel_error, bar_jvp_vs_vjp_sweeps, bar_quadrature_vs_mc_error, bar_optimizer_final_loss), và "tables" (4 bảng table_eckart_young_rsvd, table_lora_dora_pissa, table_convex_optimizers, table_muon_moonlight_spectrum).
4.3 Bảng Kiểm định Số học & Hợp đồng 15 Kiểm thử Tự động (pytest Contract)#
Bảng Kiểm tra Bắt buộc Trước khi Nghiệm thu (Numerical Rigor & Acceptance Checklist)#
- [ ] Lõi Tham chiếu Sạch & Rào chắn AST Chỉ Bảo mật (
Security-Only AST Deserialization Ban): Toàn bộlinalg_labcài đặt thuầnPython >=3.10+numpy>=1.26+pandas>=2.0(chứng minh tính tương đương tham chiếu từ gốc không phụ thuộcscipy/sklearn/torchtrong lõi tính toán); đồng thời bộ kiểm thử quét AST toàn bộsrc/,scripts/,tests/cấm tuyệt đối các import giải tuần tự hóa nguy hiểm (pickle,_pickle,cPickle,joblib,cloudpickle,dill,shelve,marshal). - [ ] Không Bình phương Số điều kiện: Tại
target_kappa = 1e7, sai số tương đối của HouseholderQRnhỏ hơn tối thiểu \(1{,}000\times\) so với phương trình chuẩnX.T @ X. - [ ] Bảo toàn Độ chính xác
HVP,slogdet& Biên-inflogsumexp: Pearlmutter Forward-over-Reversehvp_forward_over_reversekhớp nghiệm giải tích tớiatol = 1e-12không cần đồ thị ngược thứ hai;safe_logdet_choleskyxử lý ổn định ma trận \(d = 500\) kể cả khi cộng nhiễu trị riêng âm-1e-9; vàDualArray.logsumexp/ReverseTensor.logsumexptrả về-infvới gradient0.0(không bao giờ raNaN) khi mọi đầu vào đều bằng-inf. - [ ] Tuân thủ Tuyệt đối KKT & Dải Phổ
Muon NS5: Phép chiếu simplex đạtkkt_satisfied = Truevới cả 4 điều kiện trên 50 vector ngẫu nhiên;zeropower_via_newtonschulz5nén \([0.01, 1.0]\) vào dải \([0.68, 1.14]\) vàMuon(rms_match_adamw=True) giữ RMS bước cập nhật trong \([0.12, 0.28]\times\text{lr}\) bất kể hình dạng chữ nhật. - [ ] Tất cả
15/15kiểm thửpytestđạt 100% không bỏ qua (skip) hay nới lỏng khẳng định (assertion).
Hợp đồng 15 Kiểm thử Bắt buộc (tests/test_linalg_lab.py)#
| # | Tên Hàm Kiểm thử Chính xác | Tiêu chuẩn Khẳng định & Kiểm chứng |
|---|---|---|
| 1 | test_four_subspaces_norms_and_spectral_nuclear_duality |
Kiểm chứng Rank–Nullity, trực giao \(\mathcal{C}(\mathbf{A}^\top)\perp\mathcal{N}(\mathbf{A})\), lũy đẳng phép chiếu \(\mathbf{P}^2=\mathbf{P}=\mathbf{P}^\top\), các bất đẳng thức chuẩn ma trận (Định lý 2.2), và Đối ngẫu Phổ–Hạt nhân \(\operatorname{tr}(\mathbf{A}^\top(\mathbf{U}_r\mathbf{V}_r^\top)) == \|\mathbf{A}\|_*\). |
| 2 | test_cholesky_logdet_and_progressive_jitter_stability |
Xác nhận safe_logdet_cholesky khớp np.linalg.slogdet ở \(d=500\) nơi np.log(np.linalg.det(K)) tràn số (inf/-inf), và tự phục hồi khi thêm nhiễu trị riêng âm -1e-9. |
| 3 | test_circulant_fft_matches_direct_matvec |
Khẳng định circulant_matvec_fft khớp circulant_matvec_direct trong ngưỡng atol=1e-11 trên các kích thước n in (32, 64, 128). |
| 4 | test_eckart_young_optimality_and_3x2_worked_example |
Xác nhận ma trận mẫu [[3,2],[2,3],[2,-2]] cho singular_values == (5.0, 3.0), sai số hạng 1 đúng 3.0 (cả phổ lẫn Frobenius), và 20 ma trận nhiễu hạng \(k\) ngẫu nhiên không bao giờ vượt qua \(\mathbf{A}_k\). |
| 5 | test_randomized_svd_power_iter_and_pissa_dora_adapters |
Kiểm tra sai số randomized_svd giảm đơn điệu theo n_power_iter \(0 \to 1 \to 2\); pissa_initialize đạt sai số tái tạo < 1e-11; và benchmark_lora_dora_pissa_adaptation chứng minh pissa và dora thắng khởi tạo 0 của lora. |
| 6 | test_condition_number_squaring_normal_eq_vs_qr_svd |
Xác nhận compare_normal_eq_vs_qr_svd(target_kappa=1e7) thỏa kappa_gram \(\approx\) kappa_design**2 và qr_rel_error < 1e-3 * normal_eq_rel_error; đồng thời ledoit_wolf_shrinkage ép \(\kappa_{\text{LW}} < 0.2\,\kappa_{\text{sample}}\) tại \(p_{\text{assets}}=45, n_{\text{bars}}=50\). |
| 7 | test_jvp_vjp_exact_jacobian_parity_and_direction_complexity |
Khẳng định compute_full_jacobian_jvp và compute_full_jacobian_vjp khớp Jacobian giải tích Numerator Layout và central_diff_jacobian (eps=1e-6) dưới 1e-8, và benchmark_jvp_vs_vjp(n_in=64, m_out=4) cho vjp tốn 4 lượt so với 64 lượt của jvp. |
| 8 | test_pearlmutter_hvp_forward_over_reverse_and_grad_check |
Xác nhận hvp_forward_over_reverse trên hàm log-sum-exp + toàn phương khớp \(\mathbf{H}\mathbf{v}\) giải tích (atol=1e-12) và nhiễu sai phân trung tâm (atol=1e-8); đồng thời central_diff_grad_check đạt chuẩn ở eps=1e-6 và sai số lớn hơn hẳn ở eps=1e-2 và eps=1e-13. |
| 9 | test_dual_and_reverse_logsumexp_all_neginf_zero_grad |
Kiểm chứng hồi quy cho DualArray.logsumexp và ReverseTensor.logsumexp: khi toàn bộ phần tử đầu vào là -inf (chứa trong phép che mặt nạ toàn cục), giá trị trả về phải là -inf và gradient bằng 0.0 thay vì phát sinh NaN. |
| 10 | test_change_of_variables_and_quadrature_vs_monte_carlo |
Kiểm chứng triangular_flow_log_prob bảo toàn tổng khối xác suất \(\approx 1.0\) qua tích phân Monte Carlo (abs=0.05); compare_quadrature_vs_monte_carlo thắng hình thang tại \(d=10\); và simulate_checkpointing_memory cắt đỉnh HBM \(\ge 60\%\) qua uniform_sqrt & selective_sac. |
| 11 | test_simplex_projection_kkt_conditions_and_worked_example |
Xác nhận project_onto_simplex(np.array([1.8, 1.1, 0.2, -0.4])) trả về chính xác [0.85, 0.15, 0.0, 0.0] (nu_star == 0.95, k_star == 2) và verify_simplex_kkt đạt kkt_satisfied=True trên 50 vector ngẫu nhiên. |
| 12 | test_convex_optimizers_rates_gd_nag_lbfgs_schedule_free |
Chạy run_convex_optimizer_arena(kappa=100.0, dim=16, n_steps=120): nesterov thắng gd tại bước 120, lbfgs đạt độ lệch tối ưu < 1e-10, và schedule_free đạt < 1e-2 không cần lịch giảm LR. |
| 13 | test_adamw_decoupled_decay_vs_coupled_l2 |
Trên hàm mất mát 2 tham số dị hướng (\(g_1 = 100.0, g_2 = 0.01\)), khẳng định AdamW(decoupled=True) suy giảm tỷ lệ đồng đều cả hai tọa độ trong khi decoupled=False thất bại trên tọa độ gradient lớn. |
| 14 | test_muon_newton_schulz5_bounds_and_moonlight_rms_invariance |
Xác nhận zeropower_via_newtonschulz5 nén phổ [0.01, 1.0] vào [0.68, 1.14]; Muon (rms_match_adamw=True) giữ RMS cập nhật trong [0.12, 0.28] * lr qua các kích thước (16, 128), (64, 64), (128, 16); HybridMuonAdamW định tuyến đúng; và verify_bf16_stagnation_vs_fp32_master chứng minh thuần bf16 đứng yên ở 0.0 khi fp32 master tiến triển. |
| 15 | test_cli_demo_script_and_workbench_panels_json |
Thực thi scripts/run_lab_demo.py --json-out <tmp_file> --seed 42 qua subprocess.run, kiểm tra returncode == 0, đủ 4 khối báo cáo stdout, JSON chứa đủ workbench_panels (kpis, bars, tables), và áp dụng rào chắn AST Chỉ Bảo mật trên toàn bộ src/, scripts/, tests/ (cấm import pickle, _pickle, cPickle, joblib, cloudpickle, dill, shelve, marshal). |
Trụ cột 5 — Tài liệu Đọc SOTA 2024–2026 & Bài tập Đánh giá Năng lực (Curated Reading List & Mastery Exercises)#
5.1 Danh mục Tài liệu Kinh điển & Tiên phong 2024–2026 (Curated SOTA Reading List)#
- Golub, G. H., & Van Loan, C. F. (2013) & Higham, N. J. (2002). Matrix Computations (4th ed., Johns Hopkins) và Accuracy and Stability of Numerical Algorithms (2nd ed., SIAM — Ch. 19–20).
Vì sao quan trọng: Nền móng chuẩn mực nhất về phân rã Cholesky, SVD, Eckart–Young và chứng minh giải tích vì sao phương trình chuẩn bình phương \(\kappa_2(\mathbf{X})\) trong khi biến đổi trực giao Householder QR vẫn ổn định lùi. - Halko, N., Martinsson, P.-G., & Tropp, J. A. (2011) — "Finding Structure with Randomness: Probabilistic Algorithms for Constructing Approximate Matrix Decompositions" (SIAM Review 53(2),
arXiv:0909.4061), đọc song hành Murray, R., Demmel, J., Mahoney, M. W., et al. (2023–2025) —RandBLAS/RandLAPACK(arXiv:2302.11474).
Vì sao quan trọng: Chuyển hóa bài toán SVD \(O(mn^2)\) chậm trên GPU thành các phép nhânBLAS-3 GEMMtốc độ cao nhờ phác thảo ngẫu nhiên dư biến thiên và lặp lũy thừa ổn định bằngQR/CholeskyQR2. - Pearlmutter, B. A. (1994) — "Fast Exact Multiplication by the Hessian" (Neural Computation 6(1)), đọc cùng Chen, T., et al. (2016) — "Training Deep Nets with Sublinear Memory Cost" (
arXiv:1604.06174).
Vì sao quan trọng: Đặt nền tảng cho phép nhânHVPchính xác trong \(O(1)\) lượt không cần băng ngược kép (Forward-over-Reverse) và bài toán tối ưu hóa tái tính kích hoạt từ \(O(\sqrt{L})\) tới lát cắt cực tiểuSAChiện đại. - Liu, S.-Y., et al. (
DoRA, ICML 2024,arXiv:2402.09353), Meng, F., et al. (PiSSA, NeurIPS 2024,arXiv:2404.02948), và Zhao, J., et al. (GaLore, ICML 2024,arXiv:2403.03507).
Vì sao quan trọng: Biến Định lý Eckart–Young thành các bộ thích nghi và tiền huấn luyện LLM tiết kiệm tới82.5%bộ nhớ tối ưu thông qua phân tách biên độ–hướng, khởi tạo không gian kỳ dị chính và chiếu gradient chu kỳ. - DeepSeek-AI (2024) — DeepSeek-V2 (
arXiv:2405.04434) & DeepSeek-V3 Technical Report (arXiv:2412.19437, 12/2024), thư viện mã nguồn mởDeepGEMM(2025), đọc song hành Dao, T., & Gu, A. (ICML 2024) — "Transformers are SSMs" (Mamba-2 SSD,arXiv:2405.21060).
Vì sao quan trọng: Minh họa đỉnh cao kỹ thuật đại số tuyến tính trong kiến trúc LLM 2024–2026:MLAcắt98.24%số chiều KV mỗi tầng ở DeepSeek-V3 (và giảm93.3%dung lượng KV cache hệ thống ở DeepSeek-V2), giải quyết lỗi tích lũy 14-bit Hopper FP8 trong DeepSeek-V3/DeepGEMM, và đối ngẫu ma trận 1-semiseparable trên Tensor Cores. - Jordan, K. (2024) — Muon, Bernstein, J., & Newhouse, L. (2024) — "Old Optimizer, New Norm" (
arXiv:2409.20325), và Liu, J., Su, J., et al. / Moonshot AI (2025) — "Muon is Scalable for LLM Training" (Moonlight,arXiv:2502.16982), đọc kèmSOAP(arXiv:2409.11321) vàSchedule-Free(arXiv:2405.15682).
Vì sao quan trọng: Kết nối trực tiếp Đối ngẫu Phổ–Hạt nhân với đa thức bậc 5 Newton–Schulz và quy tắc chuẩn hóa RMS \(0.2\sqrt{\max(d_{\text{out}}, d_{\text{in}})}\) đạt hiệu suất gấp đôiAdamWở quy mô nghìn tỷ token.
5.2 Sáu Bài tập Đánh giá Năng lực (Graded Mastery Exercises)#
Nhóm A — Chứng minh Toán học & Suy diễn Nguyên lý (40%)#
-
Bài tập 1 (20% — Chứng minh Định lý Eckart–Young–Mirsky & Đối ngẫu Cực Phổ):
- Chứng minh hoàn chỉnh bất đẳng thức chuẩn phổ \(\|\mathbf{A} - \mathbf{B}\|_2 \ge \sigma_{k+1}\) của Định lý Eckart–Young–Mirsky bằng lập luận Rank–Nullity và công thức chiều Grassmann.
- Chứng minh Định lý Đối ngẫu Phổ–Hạt nhân \(\sup_{\|\mathbf{X}\|_2 \le 1}\operatorname{tr}(\mathbf{A}^\top\mathbf{X}) = \|\mathbf{A}\|_*\), và giải thích về mặt hình học vì sao hướng giảm dốc nhất của
Muonbên trong quả cầu chuẩn phổ \(\|\Delta\mathbf{W}\|_2 \le 1\) lại đúng bằng \(-\mathbf{U}_r\mathbf{V}_r^\top\).
-
Bài tập 2 (20% — Công thức Jacobi, Đổi biến Đa biến & KKT Phép chiếu Simplex):
- Suy diễn tường minh \(\nabla_{\mathbf{X}}\ln\det\mathbf{X} = \mathbf{X}^{-\top}\) từ khai triển phần bù đại số (adjugate) và kiểm chứng bằng sai phân trực tiếp trên một ma trận bất đối xứng \(2 \times 2\) tự chọn có hai phần tử ngoài đường chéo khác nhau.
- Suy diễn biểu thức water-filling \(p_i^* = (y_i - \nu^*)_+\) từ hàm Lagrange, chứng minh ngưỡng \(k^* = \max\{j : y_{(j)} - t_j > 0\}\), và giải tay kèm kiểm chứng đầy đủ cả 4 điều kiện KKT cho vector \(\mathbf{y} = [2.4,\; 1.0,\; 0.5,\; -0.3]^\top\).
Nhóm B — Kỹ thuật Hệ thống & Độ ổn định Số học (35%)#
-
Bài tập 3 (17.5% — Chẩn đoán & Khắc phục Sụp đổ \(\kappa^2\) và Tràn số
logdet):
Cho tập hồi quy tuyến tính có \(\kappa_2(\mathbf{X}) = 10^8\) và một ma trận hiệp phương sai kernel RBF kích thước \(d = 500\) với trị riêng trung bình \(\bar{\lambda} = 0.25\) bị nhiễu làm tròn âm \(-10^{-11}\).- Định lượng chính xác số chữ số thập phân bị mất khi giải phương trình chuẩn \(\mathbf{X}^\top\mathbf{X}\) so với Householder
QRtrong chuẩnfloat64, và giải thích cơ chế khiếnnp.log(np.linalg.det(K))trả về-inf. - Chạy và kiểm chứng bằng
compare_normal_eq_vs_qr_svdvàsafe_logdet_choleskytronglinalg_lab, chứng minh phương pháp phòng vệ khôi phục độ chính xác mà không dùngscipy.
- Định lượng chính xác số chữ số thập phân bị mất khi giải phương trình chuẩn \(\mathbf{X}^\top\mathbf{X}\) so với Householder
-
Bài tập 4 (17.5% — Phân tích Chi phí
JVPvs.VJP, PearlmutterHVP& Kiểm tra Gradient):
Xét mạng neural ánh xạ \(\mathbf{f}: \mathbb{R}^{10^6} \to \mathbb{R}^4\) theo sau bởi hàm mất mát vô hướng \(\ell: \mathbb{R}^4 \to \mathbb{R}\).- So sánh số lượt duyệt đồ thị tính toán để dựng toàn bộ ma trận \(\mathbf{J}_{\mathbf{f}} \in \mathbb{R}^{4 \times 10^6}\) bằng
JVPso vớiVJP, và chứng minh vì saohvp_forward_over_reversetính được \(\mathbf{H}\mathbf{v}\) trong \(O(1)\) lượt mà không cấp phát đồ thị ngược thứ hai. - Kiểm chứng số học trên
linalg_labrằngcentral_diff_grad_checkđạt ngưỡng sai số cực tiểu ở \(\epsilon = 10^{-6}\), trong khi thất bại nặng nề tại \(\epsilon = 10^{-2}\) (lệch cắt cụt) và \(\epsilon = 10^{-13}\) (triệt tiêu dấu chấm động).
- So sánh số lượt duyệt đồ thị tính toán để dựng toàn bộ ma trận \(\mathbf{J}_{\mathbf{f}} \in \mathbb{R}^{4 \times 10^6}\) bằng
Nhóm C — Thiết kế Kiến trúc Production & Phân tích Lỗi (25%)#
-
Bài tập 5 (12.5% — Thiết kế Ngân sách Đại số Tuyến tính cho LLM 70B Ngữ cảnh 128K trên H100):
Thiết kế kiến trúc huấn luyện và phục vụ cho mô hình Transformer70Btham số với ngữ cảnh128Ktrên cụm GPU NVIDIA H100 SXM5:- Thiết lập quy tắc định tuyến lai
Muon + AdamW, giải thích vai trò hệ sốMoonlight\(0.2\sqrt{\max(d_{\text{out}}, d_{\text{in}})}\) và lý do bắt buộc giữembed_tokens,lm_head,RMSNormởAdamW. - Tính toán mức tiết kiệm bộ nhớ KV cache (
bytes/token/layer) củaMLA(\(d_c = 512, d_h^R = 64\)) so vớiMHAvàGQA, giải thích chính sách cắtSACgiữaGEMMvàRMSNorm/SwiGLU, và bảo vệ thiết kế thúc đẩy tổng từng khối128x128sangfp32kiểuDeepGEMMtrước giới hạn cộng dồn 14-bit HopperWGMMA.
- Thiết lập quy tắc định tuyến lai
-
Bài tập 6 (12.5% — Gỡ lỗi Thảm họa Đòn bẩy Danh mục & Sụp đổ Làm trắng Retrieval):
Một quỹ đầu tư định lượng gặp biến động đòn bẩy gộp tới400xkhi tối ưu danh mục \(p_{\text{assets}} = 450\) cổ phiếu trên \(n_{\text{bars}} = 500\) phiên ngày, trong khi một đội RAG doanh nghiệp thấyNDCGgiảm12%ngay sau khi bật ZCA whitening toàn bộ 768 chiều.- Chẩn đoán chính xác nguyên nhân toán học của cả hai sự cố bằng phổ Marchenko–Pastur (\(\lambda_\pm = \sigma^2(1 \pm \sqrt{c})^2\)) và hệ số khuếch đại đuôi \(\lambda_i^{-1/2}\).
- Thiết kế và kiểm chứng phác đồ khắc phục dùng co rút
Ledoit–Wolf(trênlinalg_lab.ledoit_wolf_shrinkage) kết hợp Truncated Whitening (top-\(k=256\)) hoặc điều chuẩn \((\boldsymbol{\Lambda} + \epsilon\mathbf{I})^{-1/2}\).
5.3 Thang Điểm & Tiêu chuẩn Nghiệm thu (Grading Rubric)#
| Cấp độ | Thang điểm | Tiêu chí Đánh giá Chi tiết |
|---|---|---|
| Principal Standard | 90–100% | Chứng minh chặt chẽ không nhảy bước (Rank–Nullity, Bổ đề Weyl, Jacobi, KKT); mã nguồn pure-NumPy chạy sạch 15/15 kiểm thử với lõi tham chiếu 0 phụ thuộc scipy/sklearn/torch và rào chắn AST chỉ bảo mật; nắm vững dải phổ Newton–Schulz (\([0.6818, 1.1344]\)), sai số rSVD, HVP và QR vs. phương trình chuẩn; tính toán định lượng chính xác Roofline (AI, \(I^*\)) và byte KV cache MLA. |
| Senior Standard | 75–89% | Thuật toán và bộ test 15/15 vượt qua đầy đủ, nhưng còn thiếu sót nhỏ ở điều kiện duy nhất của Eckart–Young (\(\sigma_k > \sigma_{k+1}\)), quên dấu chuyển vị \(\mathbf{X}^{-\top}\) trong công thức Jacobi bất đối xứng, hoặc giải thích ranh giới phân tách Muon + AdamW chưa đủ định lượng. |
| Needs Remediation | < 75% | Dùng nghịch đảo \(\mathbf{X}^\top\mathbf{X}\) trên dữ liệu đa cộng tuyến cao, để tràn log(det(K)), dùng bước sai phân \(\epsilon \in \{10^{-2}, 10^{-14}\}\), áp dụng Muon lên chuẩn 1D/embed_tokens, hoặc vi phạm điều kiện bù lỏng trong phép chiếu simplex KKT. |
Least-Squares Relative Error at kappa=1.0e+07
Full Jacobian Sweep Count (R^64 -> R^4)
10D Integration Absolute Error (4096 Budget)
Convex Arena Final Suboptimality (kappa=100.0, 120 steps)
Eckart-Young Exact vs. Randomized SVD (dim=128, rank=12)
| method | power_iters | spectral_error | frobenius_error |
|---|---|---|---|
| exact_eckart_young | 0 | 0.357143 | 1.454168 |
| rsvd_q0 | 0 | 0.484682 | 1.745645 |
| rsvd_q1 | 1 | 0.363051 | 1.4684 |
| rsvd_q2 | 2 | 0.357192 | 1.455083 |
Low-Rank Adaptation Arena (LoRA vs. DoRA vs. PiSSA)
| method | rank_r | n_steps | initial_loss | final_loss |
|---|---|---|---|---|
| lora | 4 | 80 | 1.725489 | 1.446704 |
| dora | 4 | 80 | 1.725489 | 0.48825 |
| pissa | 4 | 80 | 1.725489 | 0.096685 |
Convex Optimizer Arena (kappa=100.0, dim=16)
| optimizer | n_steps | initial_loss | final_loss | final_grad_norm |
|---|---|---|---|---|
| gd | 120 | 271.643118 | 0.1280344 | 0.6066127 |
| heavy_ball | 120 | 271.643118 | 1.956787e-15 | 6.255084e-07 |
| nesterov | 120 | 271.643118 | 7.901167e-10 | 4.01596e-05 |
| lbfgs | 120 | 271.643118 | 1.654633e-14 | 2.450544e-07 |
| adamw | 120 | 271.643118 | 0.0004295936 | 0.08715355 |
| schedule_free | 120 | 271.643118 | 0.0001552168 | 0.01966285 |
Muon NS5 Spectrum & Moonlight RMS Shape Invariance
| shape | update_rms | rms_over_lr | ns_sigma_min | ns_sigma_max |
|---|---|---|---|---|
| 16x128 | 0.003522 | 0.1761 | 0.7338 | 1.119 |
| 64x64 | 0.003526 | 0.1763 | 0.7338 | 1.119 |
| 128x16 | 0.003398 | 0.1699 | 0.7338 | 1.119 |
02-track-1-data-science-and-ai/part-01-math-stats-and-causal/labs/ch02-linalg-and-optimizers-workbench
[build-system]
requires = ["setuptools>=61.0"]
build-backend = "setuptools.build_meta"
[project]
name = "linalg-lab"
version = "0.1.0"
description = "Linear Algebra, Matrix Calculus, Autodiff, Conditioning, and SOTA Optimizers Workbench (T1-P1-U02)."
readme = "README.md"
requires-python = ">=3.12"
dependencies = [
"numpy>=1.26",
"pandas>=2.0",
]
[project.optional-dependencies]
dev = ["pytest>=8.0", "ruff>=0.4"]
[tool.setuptools.packages.find]
where = ["src"]
[tool.pytest.ini_options]
testpaths = ["tests"]
pythonpath = ["src"]
addopts = "-v"
[tool.ruff]
line-length = 100
target-version = "py310"
"""Pure-NumPy Linear Algebra, Matrix Calculus, Autodiff, Conditioning, and SOTA Optimizers Workbench."""
from __future__ import annotations
from linalg_lab.calculus_and_autodiff import (
AutodiffBenchmarkRow,
CheckpointingProfile,
DualArray,
GradCheckResult,
IntegrationComparisonRow,
ReverseTensor,
benchmark_jvp_vs_vjp,
central_diff_grad_check,
central_diff_jacobian,
compare_quadrature_vs_monte_carlo,
compute_full_jacobian_jvp,
compute_full_jacobian_vjp,
hvp_forward_over_reverse,
jvp,
simulate_checkpointing_memory,
triangular_flow_log_prob,
value_and_grad,
vjp,
)
from linalg_lab.optimizers import (
LBFGS,
NS5_COEFFS,
AdamW,
GradientDescent,
HybridMuonAdamW,
Muon,
OptimizerTrajectoryResult,
ScheduleFreeAdamW,
SimplexKKTReport,
make_anisotropic_quadratic,
project_onto_simplex,
run_convex_optimizer_arena,
run_matrix_optimizer_arena,
verify_bf16_stagnation_vs_fp32_master,
verify_simplex_kkt,
zeropower_via_newtonschulz5,
)
from linalg_lab.svd_and_lowrank import (
ConditioningBenchmarkResult,
EckartYoungResult,
LowRankAdapterBenchmarkRow,
MatrixNormProfile,
PiSSAInit,
RandomizedSVDResult,
benchmark_lora_dora_pissa_adaptation,
circulant_matvec_direct,
circulant_matvec_fft,
compare_normal_eq_vs_qr_svd,
compute_matrix_norms,
dora_effective_weight,
eckart_young_approximation,
ledoit_wolf_shrinkage,
pissa_initialize,
randomized_svd,
safe_logdet_cholesky,
)
__all__ = [
"LBFGS",
"NS5_COEFFS",
"AdamW",
"AutodiffBenchmarkRow",
"CheckpointingProfile",
"ConditioningBenchmarkResult",
"DualArray",
"EckartYoungResult",
"GradCheckResult",
"GradientDescent",
"HybridMuonAdamW",
"IntegrationComparisonRow",
"LowRankAdapterBenchmarkRow",
"MatrixNormProfile",
"Muon",
"OptimizerTrajectoryResult",
"PiSSAInit",
"RandomizedSVDResult",
"ReverseTensor",
"ScheduleFreeAdamW",
"SimplexKKTReport",
"benchmark_jvp_vs_vjp",
"benchmark_lora_dora_pissa_adaptation",
"central_diff_grad_check",
"central_diff_jacobian",
"circulant_matvec_direct",
"circulant_matvec_fft",
"compare_normal_eq_vs_qr_svd",
"compare_quadrature_vs_monte_carlo",
"compute_full_jacobian_jvp",
"compute_full_jacobian_vjp",
"compute_matrix_norms",
"dora_effective_weight",
"eckart_young_approximation",
"hvp_forward_over_reverse",
"jvp",
"ledoit_wolf_shrinkage",
"make_anisotropic_quadratic",
"pissa_initialize",
"project_onto_simplex",
"randomized_svd",
"run_convex_optimizer_arena",
"run_matrix_optimizer_arena",
"safe_logdet_cholesky",
"simulate_checkpointing_memory",
"triangular_flow_log_prob",
"value_and_grad",
"verify_bf16_stagnation_vs_fp32_master",
"verify_simplex_kkt",
"vjp",
"zeropower_via_newtonschulz5",
]
"""SVD, Matrix Norms, Randomized SVD, Low-Rank Adapters (LoRA/DoRA/PiSSA), and Numerical Conditioning."""
from __future__ import annotations
import math
from dataclasses import dataclass
import numpy as np
@dataclass(frozen=True, slots=True)
class MatrixNormProfile:
"""Spectral, Frobenius, nuclear norms, numerical rank, and conditioning summary."""
shape: tuple[int, int]
rank: int
frobenius_norm: float
spectral_norm: float
nuclear_norm: float
condition_number: float
singular_values: tuple[float, ...]
@dataclass(frozen=True, slots=True)
class EckartYoungResult:
"""Rank-k SVD truncation errors compared against Eckart-Young-Mirsky theoretical bounds."""
rank_k: int
approx_matrix: np.ndarray
spectral_error: float
theoretical_spectral_error: float
frobenius_error: float
theoretical_frobenius_error: float
retained_energy_ratio: float
@dataclass(frozen=True, slots=True)
class RandomizedSVDResult:
"""Halko-Martinsson-Tropp randomized SVD result paired with exact SVD error baselines."""
U: np.ndarray
singular_values: np.ndarray
Vt: np.ndarray
rank_k: int
oversampling: int
n_power_iter: int
approx_matrix: np.ndarray
spectral_error: float
frobenius_error: float
exact_spectral_error: float
exact_frobenius_error: float
@dataclass(frozen=True, slots=True)
class PiSSAInit:
"""Principal Singular Values and Singular Vectors Adaptation (PiSSA) decomposition."""
B: np.ndarray
A: np.ndarray
W_residual: np.ndarray
rank_r: int
reconstruction_error: float
@dataclass(frozen=True, slots=True)
class ConditioningBenchmarkResult:
"""Comparison of Normal Equations (kappa^2) against QR and SVD least-squares solvers."""
kappa_design: float
kappa_gram: float
normal_eq_rel_error: float
qr_rel_error: float
svd_lstsq_rel_error: float
normal_eq_succeeded: bool
@dataclass(frozen=True, slots=True)
class LowRankAdapterBenchmarkRow:
"""Adaptation convergence summary for LoRA, DoRA, and PiSSA under matched rank/steps."""
method: str
rank_r: int
n_steps: int
initial_loss: float
final_loss: float
loss_history: tuple[float, ...]
def _as_2d_float64(matrix: np.ndarray, name: str = "matrix") -> np.ndarray:
arr = np.asarray(matrix, dtype=np.float64)
if arr.ndim != 2:
raise ValueError(f"{name} must be a 2D array, got shape={arr.shape}.")
return arr
def compute_matrix_norms(matrix: np.ndarray, tol: float | None = None) -> MatrixNormProfile:
"""Compute matrix norms, numerical rank, condition number, and singular values via thin SVD."""
arr = _as_2d_float64(matrix)
m, n = arr.shape
_, s, _ = np.linalg.svd(arr, full_matrices=False)
if s.size == 0 or s[0] == 0.0:
eff_tol = 0.0
elif tol is None:
eff_tol = float(max(m, n) * np.finfo(np.float64).eps * s[0])
else:
eff_tol = float(tol)
rank = int(np.sum(s > eff_tol))
frobenius_norm = float(np.sqrt(np.sum(s * s)))
spectral_norm = float(s[0]) if s.size > 0 else 0.0
nuclear_norm = float(np.sum(s))
if rank == 0 or rank < min(m, n):
condition_number = math.inf
else:
condition_number = float(s[0] / s[rank - 1])
return MatrixNormProfile(
shape=(m, n),
rank=rank,
frobenius_norm=frobenius_norm,
spectral_norm=spectral_norm,
nuclear_norm=nuclear_norm,
condition_number=condition_number,
singular_values=tuple(float(val) for val in s),
)
def eckart_young_approximation(matrix: np.ndarray, rank_k: int) -> EckartYoungResult:
"""Construct best rank-k approximation and verify empirical vs. theoretical Eckart-Young errors."""
arr = _as_2d_float64(matrix)
max_rank = min(arr.shape)
if not (0 <= rank_k <= max_rank):
raise ValueError(f"rank_k must satisfy 0 <= rank_k <= {max_rank}, got {rank_k}.")
U, s, Vt = np.linalg.svd(arr, full_matrices=False)
if rank_k == 0:
approx = np.zeros_like(arr)
else:
approx = (U[:, :rank_k] * s[:rank_k]) @ Vt[:rank_k, :]
diff = arr - approx
spectral_error = float(np.linalg.norm(diff, ord=2))
frobenius_error = float(np.linalg.norm(diff, ord="fro"))
theoretical_spectral = float(s[rank_k]) if rank_k < s.size else 0.0
theoretical_frobenius = float(np.sqrt(np.sum(s[rank_k:] ** 2))) if rank_k < s.size else 0.0
total_energy = float(np.sum(s * s))
retained_energy = (
float(np.sum(s[:rank_k] * s[:rank_k]) / total_energy) if total_energy > 0.0 else 1.0
)
return EckartYoungResult(
rank_k=rank_k,
approx_matrix=approx,
spectral_error=spectral_error,
theoretical_spectral_error=theoretical_spectral,
frobenius_error=frobenius_error,
theoretical_frobenius_error=theoretical_frobenius,
retained_energy_ratio=retained_energy,
)
def randomized_svd(
matrix: np.ndarray,
rank_k: int,
oversampling: int = 10,
n_power_iter: int = 2,
seed: int = 42,
) -> RandomizedSVDResult:
"""Compute Halko-Martinsson-Tropp (2011) randomized SVD with QR-stabilized power iteration."""
arr = _as_2d_float64(matrix)
m, n = arr.shape
max_rank = min(m, n)
if not (1 <= rank_k <= max_rank):
raise ValueError(f"rank_k must satisfy 1 <= rank_k <= {max_rank}, got {rank_k}.")
if oversampling < 0:
raise ValueError(f"oversampling must be >= 0, got {oversampling}.")
if n_power_iter < 0:
raise ValueError(f"n_power_iter must be >= 0, got {n_power_iter}.")
ell = min(n, rank_k + oversampling)
rng = np.random.default_rng(seed)
omega = rng.standard_normal((n, ell))
Q, _ = np.linalg.qr(arr @ omega, mode="reduced")
# Interleaved QR re-orthogonalization prevents catastrophic floating-point loss during power steps.
for _ in range(n_power_iter):
Z, _ = np.linalg.qr(arr.T @ Q, mode="reduced")
Q, _ = np.linalg.qr(arr @ Z, mode="reduced")
B = Q.T @ arr
Ub, s_b, Vt_b = np.linalg.svd(B, full_matrices=False)
U = (Q @ Ub)[:, :rank_k]
singular_values = s_b[:rank_k]
Vt = Vt_b[:rank_k, :]
approx = (U * singular_values) @ Vt
diff = arr - approx
spectral_error = float(np.linalg.norm(diff, ord=2))
frobenius_error = float(np.linalg.norm(diff, ord="fro"))
exact_ey = eckart_young_approximation(arr, rank_k)
return RandomizedSVDResult(
U=U,
singular_values=singular_values,
Vt=Vt,
rank_k=rank_k,
oversampling=oversampling,
n_power_iter=n_power_iter,
approx_matrix=approx,
spectral_error=spectral_error,
frobenius_error=frobenius_error,
exact_spectral_error=exact_ey.spectral_error,
exact_frobenius_error=exact_ey.frobenius_error,
)
def _validate_circulant_inputs(first_col: np.ndarray, x: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
c = np.asarray(first_col, dtype=np.float64)
v = np.asarray(x, dtype=np.float64)
if c.ndim != 1 or v.ndim != 1:
raise ValueError(f"first_col and x must be 1D, got shapes {c.shape} and {v.shape}.")
if c.shape[0] != v.shape[0] or c.shape[0] < 1:
raise ValueError(f"Incompatible or empty lengths: {c.shape[0]} vs {v.shape[0]}.")
return c, v
def circulant_matvec_direct(first_col: np.ndarray, x: np.ndarray) -> np.ndarray:
"""Compute O(n^2) matrix-vector product with the circulant matrix C_{r,j} = c_{(r-j) mod n}."""
c, v = _validate_circulant_inputs(first_col, x)
n = c.shape[0]
indices = (np.arange(n)[:, None] - np.arange(n)[None, :]) % n
circ_matrix = c[indices]
return circ_matrix @ v
def circulant_matvec_fft(first_col: np.ndarray, x: np.ndarray) -> np.ndarray:
"""Compute O(n log n) circulant matrix-vector product via unitary DFT diagonalization."""
c, v = _validate_circulant_inputs(first_col, x)
return np.fft.ifft(np.fft.fft(c) * np.fft.fft(v)).real
def pissa_initialize(weight: np.ndarray, rank_r: int) -> PiSSAInit:
"""Initialize PiSSA adapters B, A from top-r SVD components and freeze W_residual."""
w_arr = _as_2d_float64(weight, name="weight")
max_rank = min(w_arr.shape)
if not (1 <= rank_r <= max_rank):
raise ValueError(f"rank_r must satisfy 1 <= rank_r <= {max_rank}, got {rank_r}.")
U, s, Vt = np.linalg.svd(w_arr, full_matrices=False)
sqrt_s = np.sqrt(s[:rank_r])
B = U[:, :rank_r] * sqrt_s[None, :]
A = sqrt_s[:, None] * Vt[:rank_r, :]
W_residual = w_arr - B @ A
reconstruction_error = float(np.linalg.norm(w_arr - (B @ A + W_residual), ord="fro"))
return PiSSAInit(
B=B,
A=A,
W_residual=W_residual,
rank_r=rank_r,
reconstruction_error=reconstruction_error,
)
def dora_effective_weight(
W0: np.ndarray,
B: np.ndarray,
A: np.ndarray,
magnitude: np.ndarray,
eps: float = 1e-12,
) -> np.ndarray:
"""Compute DoRA per-row magnitude-direction decoupled effective weight matrix."""
w0_arr = _as_2d_float64(W0, name="W0")
b_arr = _as_2d_float64(B, name="B")
a_arr = _as_2d_float64(A, name="A")
mag = np.asarray(magnitude, dtype=np.float64).reshape(-1, 1)
if b_arr.shape[0] != w0_arr.shape[0] or a_arr.shape[1] != w0_arr.shape[1]:
raise ValueError(
f"Incompatible adapter shapes: W0={w0_arr.shape}, B={b_arr.shape}, A={a_arr.shape}."
)
if b_arr.shape[1] != a_arr.shape[0]:
raise ValueError(f"Rank mismatch between B={b_arr.shape} and A={a_arr.shape}.")
if mag.shape[0] != w0_arr.shape[0]:
raise ValueError(f"magnitude length {mag.shape[0]} != d_out {w0_arr.shape[0]}.")
w_raw = w0_arr + b_arr @ a_arr
row_norms = np.sqrt(np.sum(w_raw * w_raw, axis=1, keepdims=True) + eps)
return mag * (w_raw / row_norms)
def benchmark_lora_dora_pissa_adaptation(
d_out: int = 48,
d_in: int = 32,
rank_r: int = 4,
n_steps: int = 80,
lr: float = 0.05,
seed: int = 42,
) -> list[LowRankAdapterBenchmarkRow]:
"""Benchmark LoRA, DoRA, and PiSSA fitting a planted principal + row-magnitude shift."""
if not (1 <= rank_r <= min(d_out, d_in)):
raise ValueError(f"rank_r={rank_r} exceeds matrix rank cap {min(d_out, d_in)}.")
rng = np.random.default_rng(seed)
u0, _ = np.linalg.qr(rng.standard_normal((d_out, d_out)), mode="complete")
v0, _ = np.linalg.qr(rng.standard_normal((d_in, d_in)), mode="complete")
r_max = min(d_out, d_in)
head_s = np.linspace(3.0, 1.6, rank_r)
tail_s = np.linspace(0.5, 0.1, max(r_max - rank_r, 0))
s0 = np.concatenate([head_s, tail_s])[:r_max]
W0 = (u0[:, :r_max] * s0) @ v0[:r_max, :]
# Planted task target: principal-subspace transformation paired with positive row-magnitude scaling.
u_r = u0[:, :rank_r]
v_r = v0[:rank_r, :]
m_shift = rng.standard_normal((rank_r, rank_r)) * 0.35
row_scale = np.exp(0.35 * rng.standard_normal(d_out))
W_target = row_scale[:, None] * (W0 + u_r @ m_shift @ v_r)
a0 = rng.standard_normal((rank_r, d_in)) * 0.01
rows: list[LowRankAdapterBenchmarkRow] = []
# 1. Standard zero-initialized LoRA: B = 0, A ~ N(0, 0.01^2).
b_lora = np.zeros((d_out, rank_r), dtype=np.float64)
a_lora = a0.copy()
init_lora = float(0.5 * np.sum((W0 + b_lora @ a_lora - W_target) ** 2))
hist_lora: list[float] = []
for _ in range(n_steps):
err = (W0 + b_lora @ a_lora) - W_target
grad_b = err @ a_lora.T
grad_a = b_lora.T @ err
b_lora -= lr * grad_b
a_lora -= lr * grad_a
hist_lora.append(float(0.5 * np.sum((W0 + b_lora @ a_lora - W_target) ** 2)))
rows.append(
LowRankAdapterBenchmarkRow(
method="lora",
rank_r=rank_r,
n_steps=n_steps,
initial_loss=init_lora,
final_loss=hist_lora[-1] if hist_lora else init_lora,
loss_history=tuple(hist_lora),
)
)
# 2. DoRA: decoupled row magnitude vector + directional low-rank adapter.
eps_dora = 1e-12
b_dora = np.zeros((d_out, rank_r), dtype=np.float64)
a_dora = a0.copy()
mag_dora = np.sqrt(np.sum(W0 * W0, axis=1) + eps_dora)
init_dora = float(0.5 * np.sum((dora_effective_weight(W0, b_dora, a_dora, mag_dora, eps_dora) - W_target) ** 2))
hist_dora: list[float] = []
for _ in range(n_steps):
w_raw = W0 + b_dora @ a_dora
row_norms = np.sqrt(np.sum(w_raw * w_raw, axis=1, keepdims=True) + eps_dora)
u_hat = w_raw / row_norms
w_eff = mag_dora[:, None] * u_hat
err = w_eff - W_target
grad_mag = np.sum(err * u_hat, axis=1)
grad_w_raw = (mag_dora[:, None] / row_norms) * (err - grad_mag[:, None] * u_hat)
grad_b = grad_w_raw @ a_dora.T
grad_a = b_dora.T @ grad_w_raw
mag_dora -= lr * grad_mag
b_dora -= lr * grad_b
a_dora -= lr * grad_a
w_next = dora_effective_weight(W0, b_dora, a_dora, mag_dora, eps_dora)
hist_dora.append(float(0.5 * np.sum((w_next - W_target) ** 2)))
rows.append(
LowRankAdapterBenchmarkRow(
method="dora",
rank_r=rank_r,
n_steps=n_steps,
initial_loss=init_dora,
final_loss=hist_dora[-1] if hist_dora else init_dora,
loss_history=tuple(hist_dora),
)
)
# 3. PiSSA: principal singular subspace initialization + frozen residual.
pissa = pissa_initialize(W0, rank_r=rank_r)
b_pissa = pissa.B.copy()
a_pissa = pissa.A.copy()
w_res = pissa.W_residual
init_pissa = float(0.5 * np.sum((w_res + b_pissa @ a_pissa - W_target) ** 2))
hist_pissa: list[float] = []
for _ in range(n_steps):
err = (w_res + b_pissa @ a_pissa) - W_target
grad_b = err @ a_pissa.T
grad_a = b_pissa.T @ err
b_pissa -= lr * grad_b
a_pissa -= lr * grad_a
hist_pissa.append(float(0.5 * np.sum((w_res + b_pissa @ a_pissa - W_target) ** 2)))
rows.append(
LowRankAdapterBenchmarkRow(
method="pissa",
rank_r=rank_r,
n_steps=n_steps,
initial_loss=init_pissa,
final_loss=hist_pissa[-1] if hist_pissa else init_pissa,
loss_history=tuple(hist_pissa),
)
)
return rows
def compare_normal_eq_vs_qr_svd(
n_rows: int = 120,
n_cols: int = 12,
target_kappa: float = 1e7,
noise_std: float = 1e-10,
seed: int = 42,
) -> ConditioningBenchmarkResult:
"""Demonstrate kappa^2 condition collapse in Normal Equations vs. QR and SVD least squares."""
if n_rows < n_cols or n_cols < 2:
raise ValueError(f"Expected n_rows >= n_cols >= 2, got ({n_rows}, {n_cols}).")
rng = np.random.default_rng(seed)
U, _ = np.linalg.qr(rng.standard_normal((n_rows, n_cols)), mode="reduced")
V, _ = np.linalg.qr(rng.standard_normal((n_cols, n_cols)), mode="complete")
singular_vals = np.geomspace(1.0, 1.0 / target_kappa, n_cols)
X = (U * singular_vals) @ V.T
w_true = rng.standard_normal(n_cols)
raw_noise = rng.standard_normal(n_rows)
# Orthogonal residual keeps w_true as the exact least-squares minimizer so solver drift isolates floating-point conditioning.
orth_residual = raw_noise - U @ (U.T @ raw_noise)
y = X @ w_true + noise_std * orth_residual
w_norm = float(np.linalg.norm(w_true))
kappa_design = float(np.linalg.cond(X, 2))
gram = X.T @ X
kappa_gram = float(np.linalg.cond(gram, 2))
normal_eq_succeeded = True
try:
w_ne = np.linalg.solve(gram, X.T @ y)
if not np.all(np.isfinite(w_ne)):
normal_eq_succeeded = False
normal_eq_rel_error = math.inf
else:
normal_eq_rel_error = float(np.linalg.norm(w_ne - w_true) / w_norm)
except np.linalg.LinAlgError:
normal_eq_succeeded = False
normal_eq_rel_error = math.inf
Q, R = np.linalg.qr(X, mode="reduced")
w_qr = np.linalg.solve(R, Q.T @ y)
qr_rel_error = float(np.linalg.norm(w_qr - w_true) / w_norm)
w_svd, _, _, _ = np.linalg.lstsq(X, y, rcond=None)
svd_rel_error = float(np.linalg.norm(w_svd - w_true) / w_norm)
return ConditioningBenchmarkResult(
kappa_design=kappa_design,
kappa_gram=kappa_gram,
normal_eq_rel_error=normal_eq_rel_error,
qr_rel_error=qr_rel_error,
svd_lstsq_rel_error=svd_rel_error,
normal_eq_succeeded=normal_eq_succeeded,
)
def safe_logdet_cholesky(
K: np.ndarray,
base_jitter: float = 1e-8,
max_tries: int = 7,
) -> float:
"""Compute log(det(K)) without overflow/underflow using Cholesky + progressive jitter + slogdet fallback."""
arr = _as_2d_float64(K, name="K")
n, m = arr.shape
if n != m:
raise ValueError(f"K must be square, got shape={arr.shape}.")
k_sym = 0.5 * (arr + arr.T)
eye_n = np.eye(n, dtype=np.float64)
jitters = [0.0] + [base_jitter * (10.0 ** idx) for idx in range(max_tries)]
for jitter in jitters:
candidate = k_sym if jitter == 0.0 else k_sym + jitter * eye_n
try:
chol = np.linalg.cholesky(candidate)
diag_l = np.diag(chol)
if np.all(diag_l > 0.0):
logdet = float(2.0 * np.sum(np.log(diag_l)))
if math.isfinite(logdet):
return logdet
except np.linalg.LinAlgError:
continue
sign, logabs = np.linalg.slogdet(k_sym)
if sign > 0 and math.isfinite(float(logabs)):
return float(logabs)
final_jitter = base_jitter * (10.0 ** max_tries)
sign_jit, logabs_jit = np.linalg.slogdet(k_sym + final_jitter * eye_n)
if sign_jit <= 0 or not math.isfinite(float(logabs_jit)):
raise np.linalg.LinAlgError("safe_logdet_cholesky failed to stabilize non-PD matrix.")
return float(logabs_jit)
def ledoit_wolf_shrinkage(returns: np.ndarray) -> tuple[np.ndarray, float, float, float]:
"""Compute exact analytical Ledoit-Wolf shrinkage toward scaled identity target mu_F * I."""
arr = _as_2d_float64(returns, name="returns")
n_bars, p_assets = arr.shape
if n_bars < 2 or p_assets < 1:
raise ValueError(f"returns requires n_bars >= 2 and p_assets >= 1, got {arr.shape}.")
centered = arr - np.mean(arr, axis=0, keepdims=True)
sample_cov = (centered.T @ centered) / float(n_bars)
sample_cov = 0.5 * (sample_cov + sample_cov.T)
mu_target = float(np.trace(sample_cov) / p_assets)
target = mu_target * np.eye(p_assets, dtype=np.float64)
diff_sq = float(np.sum((sample_cov - target) ** 2))
if diff_sq <= 0.0:
delta = 1.0
else:
row_sq_norms = np.sum(centered * centered, axis=1)
# (1/n) * sum_t ||x_t x_t^T - S||_F^2 = mean(||x_t||^4) - ||S||_F^2
pi_hat = float(np.mean(row_sq_norms * row_sq_norms) - np.sum(sample_cov * sample_cov))
beta_sq = max(0.0, pi_hat / float(n_bars))
delta = float(min(1.0, beta_sq / diff_sq))
sigma_lw = (1.0 - delta) * sample_cov + delta * target
sigma_lw = 0.5 * (sigma_lw + sigma_lw.T)
kappa_sample = float(np.linalg.cond(sample_cov, 2))
kappa_lw = float(np.linalg.cond(sigma_lw, 2))
return sigma_lw, delta, kappa_sample, kappa_lw
"""Matrix Calculus, Forward/Reverse Autodiff (JVP/VJP/HVP), Flows, Monte Carlo vs. Quadrature, and Checkpointing."""
from __future__ import annotations
import math
import time
from collections.abc import Callable, Sequence
from dataclasses import dataclass
from typing import Any
import numpy as np
def _np_sigmoid(x: np.ndarray) -> np.ndarray:
arr = np.asarray(x, dtype=np.float64)
return np.where(arr >= 0.0, 1.0 / (1.0 + np.exp(-arr)), np.exp(arr) / (1.0 + np.exp(arr)))
class DualArray:
"""Forward-mode dual array over R[eps]/(eps^2) supporting scalar, vector, and matrix ops."""
__array_ufunc__ = None
def __init__(self, val: np.ndarray | float, dot: np.ndarray | float) -> None:
v_arr = np.asarray(val, dtype=np.float64)
d_arr = np.asarray(dot, dtype=np.float64)
b_val, b_dot = np.broadcast_arrays(v_arr, d_arr)
self.val: np.ndarray = np.array(b_val, dtype=np.float64, copy=True)
self.dot: np.ndarray = np.array(b_dot, dtype=np.float64, copy=True)
@property
def shape(self) -> tuple[int, ...]:
return self.val.shape
@property
def ndim(self) -> int:
return self.val.ndim
@property
def size(self) -> int:
return self.val.size
@property
def T(self) -> DualArray:
return DualArray(self.val.T, self.dot.T)
def _coerce(self, other: Any) -> DualArray | None:
if isinstance(other, DualArray):
return other
if isinstance(other, ReverseTensor):
return None
return DualArray(other, 0.0)
def __neg__(self) -> DualArray:
return DualArray(-self.val, -self.dot)
def __pos__(self) -> DualArray:
return self
def __add__(self, other: Any) -> DualArray:
rhs = self._coerce(other)
if rhs is None:
return NotImplemented
return DualArray(self.val + rhs.val, self.dot + rhs.dot)
def __radd__(self, other: Any) -> DualArray:
return self.__add__(other)
def __sub__(self, other: Any) -> DualArray:
rhs = self._coerce(other)
if rhs is None:
return NotImplemented
return DualArray(self.val - rhs.val, self.dot - rhs.dot)
def __rsub__(self, other: Any) -> DualArray:
lhs = self._coerce(other)
if lhs is None:
return NotImplemented
return DualArray(lhs.val - self.val, lhs.dot - self.dot)
def __mul__(self, other: Any) -> DualArray:
rhs = self._coerce(other)
if rhs is None:
return NotImplemented
return DualArray(self.val * rhs.val, self.dot * rhs.val + self.val * rhs.dot)
def __rmul__(self, other: Any) -> DualArray:
return self.__mul__(other)
def __truediv__(self, other: Any) -> DualArray:
rhs = self._coerce(other)
if rhs is None:
return NotImplemented
return DualArray(
self.val / rhs.val,
(self.dot * rhs.val - self.val * rhs.dot) / (rhs.val * rhs.val),
)
def __rtruediv__(self, other: Any) -> DualArray:
lhs = self._coerce(other)
if lhs is None:
return NotImplemented
return DualArray(
lhs.val / self.val,
(lhs.dot * self.val - lhs.val * self.dot) / (self.val * self.val),
)
def __matmul__(self, other: Any) -> DualArray:
rhs = self._coerce(other)
if rhs is None:
return NotImplemented
return DualArray(self.val @ rhs.val, self.dot @ rhs.val + self.val @ rhs.dot)
def __rmatmul__(self, other: Any) -> DualArray:
lhs = self._coerce(other)
if lhs is None:
return NotImplemented
return DualArray(lhs.val @ self.val, lhs.dot @ self.val + lhs.val @ self.dot)
def __pow__(self, power: float) -> DualArray:
p = float(power)
if p == 0.0:
return DualArray(np.ones_like(self.val), np.zeros_like(self.dot))
if p == 1.0:
return DualArray(self.val.copy(), self.dot.copy())
if p == 2.0:
return self.square()
return DualArray(self.val ** p, p * (self.val ** (p - 1.0)) * self.dot)
def __getitem__(self, idx: Any) -> DualArray:
return DualArray(self.val[idx], self.dot[idx])
def reshape(self, *shape: int) -> DualArray:
return DualArray(self.val.reshape(*shape), self.dot.reshape(*shape))
def sum(self, axis: int | tuple[int, ...] | None = None, keepdims: bool = False) -> DualArray:
return DualArray(
self.val.sum(axis=axis, keepdims=keepdims),
self.dot.sum(axis=axis, keepdims=keepdims),
)
def mean(self, axis: int | tuple[int, ...] | None = None, keepdims: bool = False) -> DualArray:
return DualArray(
self.val.mean(axis=axis, keepdims=keepdims),
self.dot.mean(axis=axis, keepdims=keepdims),
)
def exp(self) -> DualArray:
e = np.exp(self.val)
return DualArray(e, e * self.dot)
def log(self) -> DualArray:
return DualArray(np.log(self.val), self.dot / self.val)
def tanh(self) -> DualArray:
t = np.tanh(self.val)
return DualArray(t, (1.0 - t * t) * self.dot)
def sigmoid(self) -> DualArray:
s = _np_sigmoid(self.val)
return DualArray(s, s * (1.0 - s) * self.dot)
def sin(self) -> DualArray:
return DualArray(np.sin(self.val), np.cos(self.val) * self.dot)
def cos(self) -> DualArray:
return DualArray(np.cos(self.val), -np.sin(self.val) * self.dot)
def square(self) -> DualArray:
return DualArray(self.val * self.val, 2.0 * self.val * self.dot)
def log1p_exp(self) -> DualArray:
sp = np.logaddexp(0.0, self.val)
sig = _np_sigmoid(self.val)
return DualArray(sp, sig * self.dot)
def logsumexp(
self,
axis: int | tuple[int, ...] | None = None,
keepdims: bool = False,
) -> DualArray:
m_val = np.asarray(np.max(self.val, axis=axis, keepdims=True), dtype=np.float64)
all_neg_inf = np.isneginf(m_val)
has_pos_inf = np.isposinf(m_val)
m_safe = np.where(np.isfinite(m_val), m_val, 0.0)
exp_shifted = np.exp(self.val - m_safe)
sum_exp = np.sum(exp_shifted, axis=axis, keepdims=True)
denom = np.where(all_neg_inf | has_pos_inf, 1.0, sum_exp)
softmax = np.where(exp_shifted > 0.0, exp_shifted / denom, 0.0)
dot_num = np.sum(softmax * self.dot, axis=axis, keepdims=True)
dot_kd = np.where(all_neg_inf, 0.0, np.where(has_pos_inf, np.nan, dot_num))
with np.errstate(divide="ignore", invalid="ignore"):
log_sum = np.log(np.where(all_neg_inf, 1.0, sum_exp))
val_kd = np.where(all_neg_inf, -np.inf, np.where(has_pos_inf, np.inf, m_val + log_sum))
if not keepdims:
val_out = np.squeeze(val_kd, axis=axis)
dot_out = np.squeeze(dot_kd, axis=axis)
else:
val_out = val_kd
dot_out = dot_kd
return DualArray(val_out, dot_out)
def _zero_like_primal(data: np.ndarray | DualArray) -> np.ndarray | DualArray:
if isinstance(data, DualArray):
return DualArray(np.zeros_like(data.val), np.zeros_like(data.dot))
return np.zeros_like(data, dtype=np.float64)
def _ones_like_primal(data: np.ndarray | DualArray) -> np.ndarray | DualArray:
if isinstance(data, DualArray):
return DualArray(np.ones_like(data.val), np.zeros_like(data.dot))
return np.ones_like(data, dtype=np.float64)
def _unbroadcast(
grad: np.ndarray | DualArray,
target_shape: tuple[int, ...],
) -> np.ndarray | DualArray:
if grad.shape == target_shape:
return grad
if len(target_shape) == 0:
return grad.sum()
g = grad
while g.ndim > len(target_shape):
g = g.sum(axis=0)
for axis, (g_dim, t_dim) in enumerate(zip(g.shape, target_shape)):
if t_dim == 1 and g_dim > 1:
g = g.sum(axis=axis, keepdims=True)
return g
class ReverseTensor:
"""Reverse-mode Wengert tape node compatible with np.ndarray or DualArray primals for FoR HVP."""
__array_ufunc__ = None
def __init__(
self,
data: np.ndarray | DualArray | float,
requires_grad: bool = True,
_children: tuple[ReverseTensor, ...] = (),
_op: str = "",
) -> None:
if isinstance(data, DualArray):
self.data: np.ndarray | DualArray = data
else:
self.data = np.asarray(data, dtype=np.float64)
self.requires_grad: bool = requires_grad
self.grad: np.ndarray | DualArray | None = None
self._backward: Callable[[], None] = lambda: None
self._prev: tuple[ReverseTensor, ...] = _children
self._op: str = _op
@property
def shape(self) -> tuple[int, ...]:
return self.data.shape
@property
def ndim(self) -> int:
return self.data.ndim
@property
def size(self) -> int:
return self.data.size
@property
def T(self) -> ReverseTensor:
out = ReverseTensor(self.data.T, requires_grad=self.requires_grad, _children=(self,), _op="T")
def _backward() -> None:
if out.grad is not None:
self._acc_grad(out.grad.T)
out._backward = _backward
return out
def _acc_grad(self, delta: np.ndarray | DualArray) -> None:
if not self.requires_grad:
return
delta_ub = _unbroadcast(delta, self.data.shape)
if self.grad is None:
self.grad = delta_ub
else:
self.grad = self.grad + delta_ub
def _ensure_tensor(self, other: Any) -> ReverseTensor:
if isinstance(other, ReverseTensor):
return other
if isinstance(other, DualArray):
return ReverseTensor(other, requires_grad=False)
if isinstance(self.data, DualArray):
return ReverseTensor(DualArray(other, 0.0), requires_grad=False)
return ReverseTensor(np.asarray(other, dtype=np.float64), requires_grad=False)
def __neg__(self) -> ReverseTensor:
out = ReverseTensor(-self.data, requires_grad=self.requires_grad, _children=(self,), _op="neg")
def _backward() -> None:
if out.grad is not None:
self._acc_grad(-out.grad)
out._backward = _backward
return out
def __pos__(self) -> ReverseTensor:
return self
def __add__(self, other: Any) -> ReverseTensor:
rhs = self._ensure_tensor(other)
req = self.requires_grad or rhs.requires_grad
out = ReverseTensor(self.data + rhs.data, requires_grad=req, _children=(self, rhs), _op="add")
def _backward() -> None:
if out.grad is not None:
self._acc_grad(out.grad)
rhs._acc_grad(out.grad)
out._backward = _backward
return out
def __radd__(self, other: Any) -> ReverseTensor:
return self.__add__(other)
def __sub__(self, other: Any) -> ReverseTensor:
rhs = self._ensure_tensor(other)
req = self.requires_grad or rhs.requires_grad
out = ReverseTensor(self.data - rhs.data, requires_grad=req, _children=(self, rhs), _op="sub")
def _backward() -> None:
if out.grad is not None:
self._acc_grad(out.grad)
rhs._acc_grad(-out.grad)
out._backward = _backward
return out
def __rsub__(self, other: Any) -> ReverseTensor:
return self._ensure_tensor(other).__sub__(self)
def __mul__(self, other: Any) -> ReverseTensor:
rhs = self._ensure_tensor(other)
req = self.requires_grad or rhs.requires_grad
out = ReverseTensor(self.data * rhs.data, requires_grad=req, _children=(self, rhs), _op="mul")
def _backward() -> None:
if out.grad is not None:
self._acc_grad(out.grad * rhs.data)
rhs._acc_grad(out.grad * self.data)
out._backward = _backward
return out
def __rmul__(self, other: Any) -> ReverseTensor:
return self.__mul__(other)
def __truediv__(self, other: Any) -> ReverseTensor:
rhs = self._ensure_tensor(other)
req = self.requires_grad or rhs.requires_grad
out = ReverseTensor(self.data / rhs.data, requires_grad=req, _children=(self, rhs), _op="div")
def _backward() -> None:
if out.grad is not None:
self._acc_grad(out.grad / rhs.data)
rhs._acc_grad(-out.grad * self.data / (rhs.data * rhs.data))
out._backward = _backward
return out
def __rtruediv__(self, other: Any) -> ReverseTensor:
return self._ensure_tensor(other).__truediv__(self)
def __matmul__(self, other: Any) -> ReverseTensor:
rhs = self._ensure_tensor(other)
req = self.requires_grad or rhs.requires_grad
a = self.data
b = rhs.data
if a.ndim not in (1, 2) or b.ndim not in (1, 2):
raise ValueError(f"ReverseTensor @ supports 1D/2D operands, got {a.shape} and {b.shape}.")
out = ReverseTensor(a @ b, requires_grad=req, _children=(self, rhs), _op="matmul")
def _backward() -> None:
if out.grad is None:
return
g = out.grad
if a.ndim == 2 and b.ndim == 2:
self._acc_grad(g @ b.T)
rhs._acc_grad(a.T @ g)
elif a.ndim == 2 and b.ndim == 1:
self._acc_grad(g.reshape(-1, 1) @ b.reshape(1, -1))
rhs._acc_grad(a.T @ g)
elif a.ndim == 1 and b.ndim == 2:
self._acc_grad(b @ g)
rhs._acc_grad(a.reshape(-1, 1) @ g.reshape(1, -1))
else:
self._acc_grad(g * b)
rhs._acc_grad(g * a)
out._backward = _backward
return out
def __rmatmul__(self, other: Any) -> ReverseTensor:
return self._ensure_tensor(other).__matmul__(self)
def __pow__(self, power: float) -> ReverseTensor:
p = float(power)
out = ReverseTensor(self.data ** p, requires_grad=self.requires_grad, _children=(self,), _op="pow")
def _backward() -> None:
if out.grad is not None:
if p == 0.0:
self._acc_grad(_zero_like_primal(self.data))
else:
self._acc_grad(out.grad * (p * (self.data ** (p - 1.0))))
out._backward = _backward
return out
def __getitem__(self, idx: Any) -> ReverseTensor:
out = ReverseTensor(self.data[idx], requires_grad=self.requires_grad, _children=(self,), _op="slice")
def _backward() -> None:
if out.grad is None:
return
if isinstance(self.data, DualArray):
g_val = np.zeros_like(self.data.val)
g_dot = np.zeros_like(self.data.dot)
g_out = out.grad if isinstance(out.grad, DualArray) else DualArray(out.grad, 0.0)
np.add.at(g_val, idx, g_out.val)
np.add.at(g_dot, idx, g_out.dot)
self._acc_grad(DualArray(g_val, g_dot))
else:
g_val = np.zeros_like(self.data, dtype=np.float64)
np.add.at(g_val, idx, out.grad)
self._acc_grad(g_val)
out._backward = _backward
return out
def reshape(self, *shape: int) -> ReverseTensor:
out = ReverseTensor(
self.data.reshape(*shape),
requires_grad=self.requires_grad,
_children=(self,),
_op="reshape",
)
def _backward() -> None:
if out.grad is not None:
self._acc_grad(out.grad.reshape(*self.data.shape))
out._backward = _backward
return out
def sum(self, axis: int | tuple[int, ...] | None = None, keepdims: bool = False) -> ReverseTensor:
out = ReverseTensor(
self.data.sum(axis=axis, keepdims=keepdims),
requires_grad=self.requires_grad,
_children=(self,),
_op="sum",
)
def _backward() -> None:
if out.grad is None:
return
g = out.grad
if axis is not None and not keepdims:
axes = (axis,) if isinstance(axis, int) else tuple(axis)
norm_axes = sorted(a % self.data.ndim for a in axes)
target_shape = list(self.data.shape)
for a in norm_axes:
target_shape[a] = 1
g = g.reshape(*target_shape)
self._acc_grad(_zero_like_primal(self.data) + g)
out._backward = _backward
return out
def mean(self, axis: int | tuple[int, ...] | None = None, keepdims: bool = False) -> ReverseTensor:
if axis is None:
count = self.data.size
elif isinstance(axis, int):
count = self.data.shape[axis]
else:
count = math.prod(self.data.shape[a] for a in axis)
return self.sum(axis=axis, keepdims=keepdims) * (1.0 / float(count))
def exp(self) -> ReverseTensor:
e = self.data.exp() if isinstance(self.data, DualArray) else np.exp(self.data)
out = ReverseTensor(e, requires_grad=self.requires_grad, _children=(self,), _op="exp")
def _backward() -> None:
if out.grad is not None:
self._acc_grad(out.grad * e)
out._backward = _backward
return out
def log(self) -> ReverseTensor:
l_val = self.data.log() if isinstance(self.data, DualArray) else np.log(self.data)
out = ReverseTensor(l_val, requires_grad=self.requires_grad, _children=(self,), _op="log")
def _backward() -> None:
if out.grad is not None:
self._acc_grad(out.grad / self.data)
out._backward = _backward
return out
def tanh(self) -> ReverseTensor:
t = self.data.tanh() if isinstance(self.data, DualArray) else np.tanh(self.data)
out = ReverseTensor(t, requires_grad=self.requires_grad, _children=(self,), _op="tanh")
def _backward() -> None:
if out.grad is not None:
self._acc_grad(out.grad * (1.0 - t * t))
out._backward = _backward
return out
def sigmoid(self) -> ReverseTensor:
s = self.data.sigmoid() if isinstance(self.data, DualArray) else _np_sigmoid(self.data)
out = ReverseTensor(s, requires_grad=self.requires_grad, _children=(self,), _op="sigmoid")
def _backward() -> None:
if out.grad is not None:
self._acc_grad(out.grad * s * (1.0 - s))
out._backward = _backward
return out
def square(self) -> ReverseTensor:
sq = self.data.square() if isinstance(self.data, DualArray) else np.square(self.data)
out = ReverseTensor(sq, requires_grad=self.requires_grad, _children=(self,), _op="square")
def _backward() -> None:
if out.grad is not None:
self._acc_grad(out.grad * (2.0 * self.data))
out._backward = _backward
return out
def log1p_exp(self) -> ReverseTensor:
sp = self.data.log1p_exp() if isinstance(self.data, DualArray) else np.logaddexp(0.0, self.data)
sig = self.data.sigmoid() if isinstance(self.data, DualArray) else _np_sigmoid(self.data)
out = ReverseTensor(sp, requires_grad=self.requires_grad, _children=(self,), _op="log1p_exp")
def _backward() -> None:
if out.grad is not None:
self._acc_grad(out.grad * sig)
out._backward = _backward
return out
def logsumexp(
self,
axis: int | tuple[int, ...] | None = None,
keepdims: bool = False,
) -> ReverseTensor:
raw = self.data.val if isinstance(self.data, DualArray) else self.data
m_val = np.asarray(np.max(raw, axis=axis, keepdims=True), dtype=np.float64)
if not np.any(np.isneginf(m_val)):
shifted = self - m_val
m_out = m_val if keepdims else np.squeeze(m_val, axis=axis)
return shifted.exp().sum(axis=axis, keepdims=keepdims).log() + m_out
# Fallback for slices where all entries are -inf (avoid (-inf) - (-inf) -> NaN)
all_neg_inf = np.isneginf(m_val)
m_safe = np.where(np.isfinite(m_val), m_val, 0.0)
if isinstance(self.data, DualArray):
out_data = self.data.logsumexp(axis=axis, keepdims=keepdims)
shifted_d = self.data - DualArray(m_safe, 0.0)
exp_d = shifted_d.exp()
sum_d = exp_d.sum(axis=axis, keepdims=True)
safe_sum_val = np.where(all_neg_inf, 1.0, sum_d.val)
safe_sum_d = DualArray(safe_sum_val, np.where(all_neg_inf, 0.0, sum_d.dot))
raw_sm = exp_d / safe_sum_d
mask = (exp_d.val > 0.0) & (~all_neg_inf)
softmax: np.ndarray | DualArray = DualArray(
np.where(mask, raw_sm.val, 0.0),
np.where(mask, raw_sm.dot, 0.0),
)
else:
exp_s = np.exp(raw - m_safe)
sum_e = np.sum(exp_s, axis=axis, keepdims=True)
denom = np.where(all_neg_inf, 1.0, sum_e)
softmax = np.where(exp_s > 0.0, exp_s / denom, 0.0)
with np.errstate(divide="ignore", invalid="ignore"):
val_kd = np.where(all_neg_inf, -np.inf, m_val + np.log(np.where(all_neg_inf, 1.0, sum_e)))
out_data = val_kd if keepdims else np.squeeze(val_kd, axis=axis)
out = ReverseTensor(out_data, requires_grad=self.requires_grad, _children=(self,), _op="logsumexp")
def _backward() -> None:
if out.grad is None:
return
g = out.grad
if axis is not None and not keepdims:
axes = (axis,) if isinstance(axis, int) else tuple(axis)
norm_axes = sorted(a % self.data.ndim for a in axes)
target_shape = list(self.data.shape)
for a in norm_axes:
target_shape[a] = 1
g = g.reshape(*target_shape)
self._acc_grad(g * softmax)
out._backward = _backward
return out
def backward(self, grad_output: np.ndarray | DualArray | float | None = None) -> None:
"""Execute reverse-mode topological sweep from this output node back to leaves."""
topo: list[ReverseTensor] = []
visited: set[int] = set()
def _build_topo(node: ReverseTensor) -> None:
nid = id(node)
if nid not in visited:
visited.add(nid)
for parent in node._prev:
_build_topo(parent)
topo.append(node)
_build_topo(self)
if grad_output is None:
seed = _ones_like_primal(self.data)
elif isinstance(self.data, DualArray):
if isinstance(grad_output, DualArray):
seed = DualArray(
np.broadcast_to(grad_output.val, self.data.shape),
np.broadcast_to(grad_output.dot, self.data.shape),
)
else:
seed = DualArray(
np.broadcast_to(np.asarray(grad_output, dtype=np.float64), self.data.shape),
np.zeros(self.data.shape, dtype=np.float64),
)
else:
seed = np.array(
np.broadcast_to(np.asarray(grad_output, dtype=np.float64), self.data.shape),
dtype=np.float64,
copy=True,
)
self.grad = seed if self.grad is None else self.grad + seed
for node in reversed(topo):
node._backward()
@dataclass(frozen=True, slots=True)
class GradCheckResult:
"""Comparison of analytical/AD gradient against central finite differences."""
analytic_grad: np.ndarray
numeric_grad: np.ndarray
max_abs_error: float
relative_error: float
eps: float
passed: bool
@dataclass(frozen=True, slots=True)
class AutodiffBenchmarkRow:
"""Sweep count, latency, and Jacobian accuracy comparing Forward JVP vs. Reverse VJP."""
mode: str
n_inputs: int
m_outputs: int
n_sweeps: int
elapsed_ms: float
jacobian_max_error: float
@dataclass(frozen=True, slots=True)
class IntegrationComparisonRow:
"""High-dimensional integration accuracy comparison: tensor Trapezoidal vs. Monte Carlo."""
method: str
dim: int
n_evals: int
estimate: float
exact_value: float
abs_error: float
@dataclass(frozen=True, slots=True)
class CheckpointingProfile:
"""Activation HBM memory footprint and recomputation overhead for rematerialization strategies."""
n_layers: int
strategy: str
peak_activation_bytes: int
extra_forward_flops_ratio: float
def jvp(
fn: Callable[[DualArray], DualArray],
x: np.ndarray,
v: np.ndarray,
) -> tuple[np.ndarray, np.ndarray]:
"""Evaluate forward-mode Jacobian-vector product (y, J @ v) in a single forward sweep."""
x_arr = np.asarray(x, dtype=np.float64)
v_arr = np.asarray(v, dtype=np.float64)
out = fn(DualArray(x_arr, v_arr))
return np.asarray(out.val, dtype=np.float64), np.asarray(out.dot, dtype=np.float64)
def vjp(
fn: Callable[[ReverseTensor], ReverseTensor],
x: np.ndarray,
cotangent: np.ndarray,
) -> tuple[np.ndarray, np.ndarray]:
"""Evaluate reverse-mode vector-Jacobian product (y, J^T @ cotangent) via Wengert tape."""
x_arr = np.asarray(x, dtype=np.float64)
c_arr = np.asarray(cotangent, dtype=np.float64)
tx = ReverseTensor(x_arr, requires_grad=True)
out = fn(tx)
out.backward(c_arr)
grad = np.zeros_like(x_arr) if tx.grad is None else np.asarray(tx.grad, dtype=np.float64)
return np.asarray(out.data, dtype=np.float64), grad
def value_and_grad(
fn: Callable[[ReverseTensor], ReverseTensor],
x: np.ndarray,
) -> tuple[float, np.ndarray]:
"""Compute scalar objective value and gradient via reverse-mode VJP."""
val, grad = vjp(fn, x, np.asarray(1.0, dtype=np.float64))
if val.size != 1:
raise ValueError(f"value_and_grad expects scalar output, got shape={val.shape}.")
return float(val.item()), grad
def hvp_forward_over_reverse(
fn: Callable[[ReverseTensor], ReverseTensor],
x: np.ndarray,
v: np.ndarray,
) -> tuple[np.ndarray, np.ndarray]:
"""Compute exact (grad_f(x), H_f(x) @ v) using Pearlmutter Forward-over-Reverse AD."""
x_arr = np.asarray(x, dtype=np.float64)
v_arr = np.asarray(v, dtype=np.float64)
tx = ReverseTensor(DualArray(x_arr, v_arr), requires_grad=True)
out = fn(tx)
if not isinstance(out.data, DualArray):
out_dual = DualArray(out.data, 0.0)
out.data = out_dual
if out.data.val.size != 1:
raise ValueError(f"hvp_forward_over_reverse expects scalar output, got shape={out.data.shape}.")
out.backward(DualArray(np.ones_like(out.data.val), np.zeros_like(out.data.dot)))
if tx.grad is None:
return np.zeros_like(x_arr), np.zeros_like(x_arr)
if isinstance(tx.grad, DualArray):
return (
np.asarray(tx.grad.val, dtype=np.float64),
np.asarray(tx.grad.dot, dtype=np.float64),
)
return np.asarray(tx.grad, dtype=np.float64), np.zeros_like(x_arr)
def compute_full_jacobian_jvp(
fn: Callable[[DualArray], DualArray],
x: np.ndarray,
) -> np.ndarray:
"""Assemble Numerator-Layout Jacobian J in R^{m x n} column-by-column via n JVP sweeps."""
x_arr = np.asarray(x, dtype=np.float64)
n = x_arr.size
cols: list[np.ndarray] = []
for j in range(n):
tangent = np.zeros(n, dtype=np.float64)
tangent[j] = 1.0
_, y_dot = jvp(fn, x_arr, tangent.reshape(x_arr.shape))
cols.append(y_dot.ravel())
return np.column_stack(cols)
def compute_full_jacobian_vjp(
fn: Callable[[ReverseTensor], ReverseTensor],
x: np.ndarray,
) -> np.ndarray:
"""Assemble Numerator-Layout Jacobian J in R^{m x n} row-by-row via m VJP sweeps."""
x_arr = np.asarray(x, dtype=np.float64)
y_probe = fn(ReverseTensor(x_arr, requires_grad=False)).data
y_shape = np.asarray(y_probe).shape
m = int(np.asarray(y_probe).size)
rows: list[np.ndarray] = []
for i in range(m):
cot = np.zeros(m, dtype=np.float64)
cot[i] = 1.0
_, grad_row = vjp(fn, x_arr, cot.reshape(y_shape))
rows.append(grad_row.ravel())
return np.vstack(rows)
def benchmark_jvp_vs_vjp(
n_in: int = 64,
m_out: int = 4,
repeats: int = 5,
seed: int = 42,
) -> list[AutodiffBenchmarkRow]:
"""Benchmark full Jacobian assembly via Forward JVP (n_in sweeps) vs. Reverse VJP (m_out sweeps)."""
rng = np.random.default_rng(seed)
hidden = 16
w1 = rng.standard_normal((hidden, n_in)) / math.sqrt(n_in)
b1 = rng.standard_normal(hidden) * 0.1
w2 = rng.standard_normal((m_out, hidden)) / math.sqrt(hidden)
b2 = rng.standard_normal(m_out) * 0.1
x = rng.standard_normal(n_in)
def net(z: Any) -> Any:
return w2 @ (w1 @ z + b1).tanh() + b2
h = np.tanh(w1 @ x + b1)
j_exact = (w2 * (1.0 - h * h)[None, :]) @ w1
jvp_times: list[float] = []
j_jvp = np.empty((m_out, n_in), dtype=np.float64)
for _ in range(repeats):
t0 = time.perf_counter()
j_jvp = compute_full_jacobian_jvp(net, x)
jvp_times.append((time.perf_counter() - t0) * 1000.0)
vjp_times: list[float] = []
j_vjp = np.empty((m_out, n_in), dtype=np.float64)
for _ in range(repeats):
t0 = time.perf_counter()
j_vjp = compute_full_jacobian_vjp(net, x)
vjp_times.append((time.perf_counter() - t0) * 1000.0)
return [
AutodiffBenchmarkRow(
mode="jvp_forward",
n_inputs=n_in,
m_outputs=m_out,
n_sweeps=n_in,
elapsed_ms=float(min(jvp_times)),
jacobian_max_error=float(np.max(np.abs(j_jvp - j_exact))),
),
AutodiffBenchmarkRow(
mode="vjp_reverse",
n_inputs=n_in,
m_outputs=m_out,
n_sweeps=m_out,
elapsed_ms=float(min(vjp_times)),
jacobian_max_error=float(np.max(np.abs(j_vjp - j_exact))),
),
]
def central_diff_jacobian(
fn: Callable[[np.ndarray], np.ndarray],
x: np.ndarray,
eps: float = 1e-6,
) -> np.ndarray:
"""Compute Numerator-Layout central finite-difference Jacobian J in R^{m x n}."""
x_arr = np.asarray(x, dtype=np.float64)
y0 = np.asarray(fn(x_arr), dtype=np.float64)
m = y0.size
n = x_arr.size
jac = np.zeros((m, n), dtype=np.float64)
x_flat = x_arr.ravel()
for j in range(n):
xp = x_flat.copy()
xm = x_flat.copy()
xp[j] += eps
xm[j] -= eps
yp = np.asarray(fn(xp.reshape(x_arr.shape)), dtype=np.float64).ravel()
ym = np.asarray(fn(xm.reshape(x_arr.shape)), dtype=np.float64).ravel()
jac[:, j] = (yp - ym) / (2.0 * eps)
return jac
def central_diff_grad_check(
fn: Callable[[np.ndarray], float],
grad_fn: Callable[[np.ndarray], np.ndarray],
x: np.ndarray,
eps: float = 1e-6,
rtol: float = 1e-5,
atol: float = 1e-7,
) -> GradCheckResult:
"""Verify analytical gradient against float64 central finite differences."""
x_arr = np.asarray(x, dtype=np.float64)
analytic = np.asarray(grad_fn(x_arr), dtype=np.float64)
numeric = central_diff_jacobian(
lambda z: np.asarray([float(fn(z))], dtype=np.float64),
x_arr,
eps=eps,
).reshape(x_arr.shape)
max_abs_err = float(np.max(np.abs(analytic - numeric)))
denom = max(float(np.linalg.norm(analytic)), float(np.linalg.norm(numeric)), 1e-15)
rel_err = float(np.linalg.norm(analytic - numeric) / denom)
passed = bool(np.allclose(analytic, numeric, rtol=rtol, atol=atol))
return GradCheckResult(
analytic_grad=analytic,
numeric_grad=numeric,
max_abs_error=max_abs_err,
relative_error=rel_err,
eps=float(eps),
passed=passed,
)
def triangular_flow_log_prob(
z: np.ndarray,
scale_log: np.ndarray,
shift: np.ndarray,
) -> tuple[np.ndarray, float, float]:
"""Evaluate a strictly lower-triangular coupling flow x = T(z) and exact Change-of-Variables log p_X(x)."""
z_arr = np.asarray(z, dtype=np.float64)
s_arr = np.asarray(scale_log, dtype=np.float64)
t_arr = np.asarray(shift, dtype=np.float64)
if z_arr.ndim != 1 or s_arr.shape != z_arr.shape or t_arr.shape != z_arr.shape:
raise ValueError(
f"Expected 1D arrays of matching length, got z={z_arr.shape}, scale_log={s_arr.shape}, shift={t_arr.shape}."
)
d = z_arr.shape[0]
eff_s = np.empty(d, dtype=np.float64)
eff_t = np.empty(d, dtype=np.float64)
eff_s[0] = s_arr[0]
eff_t[0] = t_arr[0]
if d > 1:
eff_s[1:] = s_arr[1:] * np.tanh(z_arr[:-1])
eff_t[1:] = t_arr[1:] + 0.25 * np.sin(z_arr[:-1])
x = z_arr * np.exp(eff_s) + eff_t
log_pz = -0.5 * float(np.sum(z_arr * z_arr) + d * math.log(2.0 * math.pi))
log_abs_det_j = float(np.sum(eff_s))
log_px = log_pz - log_abs_det_j
return x, log_px, log_abs_det_j
def compare_quadrature_vs_monte_carlo(
dims: Sequence[int] = (2, 6, 10),
budget_evals: int = 4096,
seed: int = 42,
) -> list[IntegrationComparisonRow]:
"""Compare O(N^{-2/d}) composite trapezoidal grid against O(N^{-1/2}) Monte Carlo on [0, 1]^d."""
rng = np.random.default_rng(seed)
rows: list[IntegrationComparisonRow] = []
exact_value = 1.0
for d in dims:
if d < 1:
raise ValueError(f"Dimension must be >= 1, got {d}.")
m_per_axis = max(2, math.floor(budget_evals ** (1.0 / d)))
n_grid_evals = int(m_per_axis ** d)
pts = np.linspace(0.0, 1.0, m_per_axis, dtype=np.float64)
weights = np.full(m_per_axis, 1.0 / float(m_per_axis - 1), dtype=np.float64)
weights[0] *= 0.5
weights[-1] *= 0.5
one_d_integral = float(np.sum(weights * (0.5 * math.pi * np.sin(math.pi * pts))))
trap_est = float(one_d_integral ** d)
rows.append(
IntegrationComparisonRow(
method="trapezoidal_grid",
dim=int(d),
n_evals=n_grid_evals,
estimate=trap_est,
exact_value=exact_value,
abs_error=abs(trap_est - exact_value),
)
)
samples = rng.uniform(0.0, 1.0, size=(budget_evals, d))
vals = np.prod(0.5 * math.pi * np.sin(math.pi * samples), axis=1)
mc_est = float(np.mean(vals))
rows.append(
IntegrationComparisonRow(
method="monte_carlo",
dim=int(d),
n_evals=int(budget_evals),
estimate=mc_est,
exact_value=exact_value,
abs_error=abs(mc_est - exact_value),
)
)
return rows
def simulate_checkpointing_memory(
n_layers: int = 64,
gemm_act_bytes: int = 16_777_216,
norm_act_bytes: int = 8_388_608,
gemm_flops_share: float = 0.88,
) -> list[CheckpointingProfile]:
"""Compare peak activation HBM bytes and extra forward FLOP overhead across tape strategies."""
if n_layers < 1:
raise ValueError(f"n_layers must be >= 1, got {n_layers}.")
layer_bytes = gemm_act_bytes + norm_act_bytes
k_segments = math.ceil(math.sqrt(n_layers))
seg_len = math.ceil(n_layers / k_segments)
full_bytes = n_layers * layer_bytes
sqrt_bytes = (k_segments + seg_len) * layer_bytes
# Selective Activation Checkpointing (SAC) preserves segment GEMM boundaries and recomputes lightweight norm/pointwise ops.
sac_bytes = (k_segments + seg_len) * gemm_act_bytes + norm_act_bytes
return [
CheckpointingProfile(
n_layers=n_layers,
strategy="full_tape",
peak_activation_bytes=int(full_bytes),
extra_forward_flops_ratio=0.0,
),
CheckpointingProfile(
n_layers=n_layers,
strategy="uniform_sqrt",
peak_activation_bytes=int(sqrt_bytes),
extra_forward_flops_ratio=float((n_layers - k_segments) / n_layers),
),
CheckpointingProfile(
n_layers=n_layers,
strategy="selective_sac",
peak_activation_bytes=int(sac_bytes),
extra_forward_flops_ratio=float(max(0.0, 1.0 - gemm_flops_share)),
),
]
"""Simplex KKT Projection, Convex/Quasi-Newton Solvers, Decoupled AdamW, Muon (NS5 + Moonlight), and Schedule-Free."""
from __future__ import annotations
import math
from collections import deque
from collections.abc import Callable
from dataclasses import dataclass
from typing import Any
import numpy as np
NS5_COEFFS: tuple[float, float, float] = (3.4445, -4.7750, 2.0315)
@dataclass(frozen=True, slots=True)
class SimplexKKTReport:
"""KKT primal, dual, stationarity, and complementary slackness audit for Delta^{n-1} projection."""
projected: np.ndarray
nu_star: float
active_support_size: int
primal_residual: float
dual_min_multiplier: float
stationarity_residual: float
complementary_slackness_residual: float
kkt_satisfied: bool
@dataclass(frozen=True, slots=True)
class OptimizerTrajectoryResult:
"""Loss and update-RMS trajectory summary across optimization steps."""
optimizer_name: str
n_steps: int
initial_loss: float
final_loss: float
final_grad_norm: float
loss_history: tuple[float, ...]
update_rms_history: tuple[float, ...]
def project_onto_simplex(y: np.ndarray) -> tuple[np.ndarray, float, int]:
"""Project vector y onto the unit probability simplex Delta^{n-1} in O(n log n) via Duchi et al. (2008)."""
y_arr = np.asarray(y, dtype=np.float64)
if y_arr.ndim != 1 or y_arr.size < 1:
raise ValueError(f"Expected non-empty 1D vector y, got shape={y_arr.shape}.")
u = np.sort(y_arr)[::-1]
cssv = np.cumsum(u) - 1.0
indices = np.arange(1, y_arr.size + 1, dtype=np.float64)
cond = (u - cssv / indices) > 0.0
if not np.any(cond):
k_star = y_arr.size
else:
k_star = int(np.max(np.flatnonzero(cond)) + 1)
nu_star = float(cssv[k_star - 1] / float(k_star))
p_star = np.maximum(y_arr - nu_star, 0.0)
return p_star, nu_star, k_star
def verify_simplex_kkt(y: np.ndarray, tol: float = 1e-10) -> SimplexKKTReport:
"""Verify all 4 Karush-Kuhn-Tucker optimality conditions for Euclidean projection onto Delta^{n-1}."""
y_arr = np.asarray(y, dtype=np.float64)
p_star, nu_star, k_star = project_onto_simplex(y_arr)
lam = np.maximum(nu_star - y_arr, 0.0)
sum_err = abs(float(np.sum(p_star)) - 1.0)
neg_violation = max(0.0, float(-np.min(p_star)))
primal_residual = float(max(sum_err, neg_violation))
dual_min_multiplier = float(np.min(lam))
stationarity_residual = float(np.max(np.abs(p_star - y_arr - lam + nu_star)))
complementary_slackness_residual = float(np.max(np.abs(lam * p_star)))
kkt_satisfied = bool(
primal_residual <= tol
and dual_min_multiplier >= -tol
and stationarity_residual <= tol
and complementary_slackness_residual <= tol
)
return SimplexKKTReport(
projected=p_star,
nu_star=nu_star,
active_support_size=k_star,
primal_residual=primal_residual,
dual_min_multiplier=dual_min_multiplier,
stationarity_residual=stationarity_residual,
complementary_slackness_residual=complementary_slackness_residual,
kkt_satisfied=kkt_satisfied,
)
class GradientDescent:
"""First-order Gradient Descent supporting vanilla GD, Polyak Heavy-Ball, and Nesterov NAG."""
def __init__(self, lr: float, momentum: float = 0.0, variant: str = "gd") -> None:
if variant not in {"gd", "heavy_ball", "nesterov"}:
raise ValueError(f"Unsupported variant '{variant}'; expected 'gd', 'heavy_ball', or 'nesterov'.")
if lr <= 0.0:
raise ValueError(f"lr must be > 0, got {lr}.")
if not (0.0 <= momentum < 1.0):
raise ValueError(f"momentum must lie in [0, 1), got {momentum}.")
self.lr = float(lr)
self.momentum = float(momentum)
self.variant = variant
self._buf: np.ndarray | None = None
def step(self, x: np.ndarray, grad: np.ndarray) -> np.ndarray:
"""Apply one optimization step given iterate x and gradient grad at x."""
x_arr = np.asarray(x, dtype=np.float64)
g_arr = np.asarray(grad, dtype=np.float64)
if self.variant == "gd" or self.momentum == 0.0:
return x_arr - self.lr * g_arr
if self._buf is None:
self._buf = np.zeros_like(g_arr)
self._buf = self.momentum * self._buf + g_arr
if self.variant == "heavy_ball":
return x_arr - self.lr * self._buf
# Sutskever Nesterov form matching lookahead evaluation directly at x.
return x_arr - self.lr * (g_arr + self.momentum * self._buf)
class LBFGS:
"""Limited-memory BFGS quasi-Newton solver with two-loop recursion and Armijo backtracking."""
def __init__(
self,
history_size: int = 10,
max_backtrack: int = 25,
c1: float = 1e-4,
) -> None:
if history_size < 1:
raise ValueError(f"history_size must be >= 1, got {history_size}.")
self.history_size = int(history_size)
self.max_backtrack = int(max_backtrack)
self.c1 = float(c1)
self._s_hist: deque[np.ndarray] = deque(maxlen=self.history_size)
self._y_hist: deque[np.ndarray] = deque(maxlen=self.history_size)
self._rho_hist: deque[float] = deque(maxlen=self.history_size)
def compute_direction(self, grad: np.ndarray) -> np.ndarray:
"""Compute quasi-Newton search direction -H_k grad via Nocedal-Wright two-loop recursion."""
q = np.asarray(grad, dtype=np.float64).copy()
m = len(self._s_hist)
if m == 0:
return -q
s_list = list(self._s_hist)
y_list = list(self._y_hist)
rho_list = list(self._rho_hist)
alphas = [0.0] * m
for idx in range(m - 1, -1, -1):
alpha_i = rho_list[idx] * float(np.vdot(s_list[idx], q))
alphas[idx] = alpha_i
q = q - alpha_i * y_list[idx]
s_last = s_list[-1]
y_last = y_list[-1]
yy = float(np.vdot(y_last, y_last))
gamma = float(np.vdot(s_last, y_last)) / yy if yy > 1e-30 else 1.0
r = gamma * q
for idx in range(m):
beta_i = rho_list[idx] * float(np.vdot(y_list[idx], r))
r = r + s_list[idx] * (alphas[idx] - beta_i)
return -r
def step(
self,
fn_val_grad: Callable[[np.ndarray], tuple[float, np.ndarray]],
x: np.ndarray,
) -> tuple[np.ndarray, float, np.ndarray]:
"""Perform one L-BFGS step with Armijo line search and secant curvature guard."""
x_arr = np.asarray(x, dtype=np.float64)
f0, g0_raw = fn_val_grad(x_arr)
f0 = float(f0)
g0 = np.asarray(g0_raw, dtype=np.float64)
direction = self.compute_direction(g0)
dir_deriv = float(np.vdot(g0, direction))
if dir_deriv >= 0.0:
direction = -g0
dir_deriv = float(np.vdot(g0, direction))
step_size = 1.0
x_next = x_arr
f_next = f0
g_next = g0
for _ in range(self.max_backtrack):
cand = x_arr + step_size * direction
f_cand, g_cand = fn_val_grad(cand)
if float(f_cand) <= f0 + self.c1 * step_size * dir_deriv:
x_next = cand
f_next = float(f_cand)
g_next = np.asarray(g_cand, dtype=np.float64)
break
step_size *= 0.5
else:
x_next = x_arr + step_size * direction
f_cand, g_cand = fn_val_grad(x_next)
f_next = float(f_cand)
g_next = np.asarray(g_cand, dtype=np.float64)
s_vec = x_next - x_arr
y_vec = g_next - g0
sy = float(np.vdot(s_vec, y_vec))
if sy > 1e-12:
self._s_hist.append(s_vec)
self._y_hist.append(y_vec)
self._rho_hist.append(1.0 / sy)
return x_next, f_next, g_next
class AdamW:
"""Adam optimizer with explicit toggle between decoupled AdamW decay and coupled L2 penalty."""
def __init__(
self,
lr: float = 1e-3,
beta1: float = 0.9,
beta2: float = 0.999,
eps: float = 1e-8,
weight_decay: float = 0.01,
decoupled: bool = True,
) -> None:
self.lr = float(lr)
self.beta1 = float(beta1)
self.beta2 = float(beta2)
self.eps = float(eps)
self.weight_decay = float(weight_decay)
self.decoupled = bool(decoupled)
self._m: np.ndarray | None = None
self._v: np.ndarray | None = None
self._t: int = 0
def step(self, w: np.ndarray, grad: np.ndarray) -> np.ndarray:
"""Apply one AdamW (decoupled=True) or Adam+L2 (decoupled=False) update step."""
w_arr = np.asarray(w, dtype=np.float64)
g_eff = np.asarray(grad, dtype=np.float64)
self._t += 1
if self._m is None or self._v is None:
self._m = np.zeros_like(w_arr)
self._v = np.zeros_like(w_arr)
if not self.decoupled and self.weight_decay != 0.0:
g_eff = g_eff + self.weight_decay * w_arr
self._m = self.beta1 * self._m + (1.0 - self.beta1) * g_eff
self._v = self.beta2 * self._v + (1.0 - self.beta2) * (g_eff * g_eff)
m_hat = self._m / (1.0 - self.beta1 ** self._t)
v_hat = self._v / (1.0 - self.beta2 ** self._t)
w_next = w_arr * (1.0 - self.lr * self.weight_decay) if (self.decoupled and self.weight_decay != 0.0) else w_arr
return w_next - self.lr * m_hat / (np.sqrt(v_hat) + self.eps)
def zeropower_via_newtonschulz5(
G: np.ndarray,
steps: int = 5,
eps: float = 1e-7,
) -> np.ndarray:
"""Orthogonalize 2D matrix G via Keller Jordan's 5-step quintic Newton-Schulz odd polynomial."""
g_arr = np.asarray(G, dtype=np.float64)
if g_arr.ndim != 2:
raise ValueError(f"Expected 2D matrix G for Newton-Schulz, got shape={g_arr.shape}.")
a, b, c = NS5_COEFFS
X = g_arr.copy()
transposed = X.shape[0] > X.shape[1]
if transposed:
X = X.T
X = X / (float(np.linalg.norm(X, ord="fro")) + eps)
for _ in range(steps):
A = X @ X.T
B = b * A + c * (A @ A)
X = a * X + B @ X
if transposed:
X = X.T
return X
class Muon:
"""MomentUm Orthogonalized by Newton-Schulz (Muon) with optional Moonlight RMS matching."""
def __init__(
self,
lr: float = 1e-2,
momentum: float = 0.95,
weight_decay: float = 0.01,
ns_steps: int = 5,
rms_match_adamw: bool = True,
) -> None:
self.lr = float(lr)
self.momentum = float(momentum)
self.weight_decay = float(weight_decay)
self.ns_steps = int(ns_steps)
self.rms_match_adamw = bool(rms_match_adamw)
self._buf: np.ndarray | None = None
def step(self, W: np.ndarray, grad: np.ndarray) -> tuple[np.ndarray, float]:
"""Update 2D matrix W using Nesterov momentum, NS5 orthogonalization, and Moonlight RMS scaling."""
w_arr = np.asarray(W, dtype=np.float64)
g_arr = np.asarray(grad, dtype=np.float64)
if w_arr.ndim != 2 or g_arr.shape != w_arr.shape:
raise ValueError(f"Expected matching 2D arrays, got W={w_arr.shape}, grad={g_arr.shape}.")
if self._buf is None:
self._buf = np.zeros_like(g_arr)
self._buf = self.momentum * self._buf + g_arr
g_tilde = g_arr + self.momentum * self._buf
o_t = zeropower_via_newtonschulz5(g_tilde, steps=self.ns_steps)
d_out, d_in = w_arr.shape
if self.rms_match_adamw:
scale = 0.2 * math.sqrt(float(max(d_out, d_in)))
else:
scale = math.sqrt(max(1.0, float(d_out) / float(d_in)))
step_matrix = self.lr * scale * o_t
w_next = w_arr * (1.0 - self.lr * self.weight_decay) - step_matrix
update_rms = float(np.sqrt(np.mean(step_matrix * step_matrix)))
return w_next, update_rms
class HybridMuonAdamW:
"""Production parameter partitioner routing 2D hidden weights to Muon and 1D/embed/head to AdamW."""
def __init__(
self,
params: dict[str, np.ndarray],
param_roles: dict[str, str] | None = None,
muon_lr: float = 1e-2,
adamw_lr: float = 1e-3,
momentum: float = 0.95,
weight_decay: float = 0.01,
ns_steps: int = 5,
rms_match_adamw: bool = True,
) -> None:
self.routing: dict[str, str] = {}
self.muon_optimizers: dict[str, Muon] = {}
self.adamw_optimizers: dict[str, AdamW] = {}
roles = param_roles or {}
for name, arr in params.items():
param = np.asarray(arr, dtype=np.float64)
role = roles.get(name)
lower = name.lower()
excluded_role = (role in {"embed", "lm_head"}) or (
role is None and ("embed" in lower or "lm_head" in lower)
)
if param.ndim >= 2 and not excluded_role:
self.routing[name] = "muon"
self.muon_optimizers[name] = Muon(
lr=muon_lr,
momentum=momentum,
weight_decay=weight_decay,
ns_steps=ns_steps,
rms_match_adamw=rms_match_adamw,
)
else:
self.routing[name] = "adamw"
self.adamw_optimizers[name] = AdamW(
lr=adamw_lr,
weight_decay=weight_decay,
decoupled=True,
)
def step(
self,
params: dict[str, np.ndarray],
grads: dict[str, np.ndarray],
) -> dict[str, np.ndarray]:
"""Update every parameter dictionary entry using its assigned Muon or AdamW engine."""
updated: dict[str, np.ndarray] = {}
for name, arr in params.items():
if name not in grads:
raise KeyError(f"Missing gradient for parameter '{name}'.")
if self.routing[name] == "muon":
w_next, _ = self.muon_optimizers[name].step(arr, grads[name])
updated[name] = w_next
else:
updated[name] = self.adamw_optimizers[name].step(arr, grads[name])
return updated
class ScheduleFreeAdamW:
"""Schedule-Free AdamW (Defazio et al., NeurIPS 2024) maintaining dual iterates z, x_eval, v."""
def __init__(
self,
lr: float = 1e-2,
beta1: float = 0.9,
beta2: float = 0.999,
eps: float = 1e-8,
weight_decay: float = 0.0,
weight_power: float = 2.0,
init_params: np.ndarray | None = None,
) -> None:
self.lr = float(lr)
self.beta1 = float(beta1)
self.beta2 = float(beta2)
self.eps = float(eps)
self.weight_decay = float(weight_decay)
self.weight_power = float(weight_power)
self.z: np.ndarray | None = None
self.x_eval: np.ndarray | None = None
self.v: np.ndarray | None = None
self._t: int = 0
self._weight_sum: float = 0.0
if init_params is not None:
self.initialize(init_params)
def initialize(self, params: np.ndarray) -> None:
"""Initialize primal and averaged iterates from starting parameter array."""
w0 = np.array(params, dtype=np.float64, copy=True)
self.z = w0
self.x_eval = w0.copy()
self.v = np.zeros_like(w0)
self._t = 0
self._weight_sum = 0.0
def train_weights(self) -> np.ndarray:
"""Return interpolated training iterate y_t = (1 - beta1) z + beta1 x_eval."""
if self.z is None or self.x_eval is None:
raise RuntimeError("ScheduleFreeAdamW is not initialized; call initialize() or step() first.")
return (1.0 - self.beta1) * self.z + self.beta1 * self.x_eval
def eval_weights(self) -> np.ndarray:
"""Return polynomially averaged evaluation iterate x_eval."""
if self.x_eval is None:
raise RuntimeError("ScheduleFreeAdamW is not initialized; call initialize() or step() first.")
return self.x_eval.copy()
def step(self, grad: np.ndarray) -> np.ndarray:
"""Update z, v, and x_eval given gradient evaluated at train_weights()."""
g_arr = np.asarray(grad, dtype=np.float64)
if self.z is None or self.x_eval is None or self.v is None:
self.initialize(np.zeros_like(g_arr))
assert self.z is not None and self.x_eval is not None and self.v is not None
self._t += 1
y_t = self.train_weights()
self.v = self.beta2 * self.v + (1.0 - self.beta2) * (g_arr * g_arr)
v_hat = self.v / (1.0 - self.beta2 ** self._t)
decay_term = self.weight_decay * y_t if self.weight_decay != 0.0 else 0.0
self.z = self.z - self.lr * (g_arr / (np.sqrt(v_hat) + self.eps) + decay_term)
w_t = float(self._t) ** self.weight_power
self._weight_sum += w_t
c_t = w_t / self._weight_sum
self.x_eval = (1.0 - c_t) * self.x_eval + c_t * self.z
return self.x_eval.copy()
def make_anisotropic_quadratic(
dim: int = 16,
kappa: float = 100.0,
seed: int = 42,
) -> tuple[np.ndarray, np.ndarray, np.ndarray, float, float]:
"""Build SPD quadratic f(x) = 0.5 x^T A x - b^T x with condition number kappa = L / mu."""
if dim < 2 or kappa < 1.0:
raise ValueError(f"Expected dim >= 2 and kappa >= 1.0, got dim={dim}, kappa={kappa}.")
rng = np.random.default_rng(seed)
Q, _ = np.linalg.qr(rng.standard_normal((dim, dim)), mode="complete")
mu = 1.0
L = float(kappa)
eigs = np.geomspace(mu, L, dim)
A = (Q * eigs) @ Q.T
A = 0.5 * (A + A.T)
x_star = rng.standard_normal(dim)
b = A @ x_star
return A, b, x_star, mu, L
def _rms(arr: np.ndarray) -> float:
return float(np.sqrt(np.mean(arr * arr)))
def run_convex_optimizer_arena(
kappa: float = 100.0,
dim: int = 16,
n_steps: int = 120,
seed: int = 42,
) -> list[OptimizerTrajectoryResult]:
"""Benchmark GD, Heavy-Ball, Nesterov, L-BFGS, AdamW, and Schedule-Free on identical quadratic."""
A, _b, x_star, mu, L = make_anisotropic_quadratic(dim=dim, kappa=kappa, seed=seed)
rng = np.random.default_rng(seed + 101)
x0 = rng.standard_normal(dim)
def subopt_val_grad(x: np.ndarray) -> tuple[float, np.ndarray]:
diff = x - x_star
grad = A @ diff
loss = 0.5 * float(diff @ grad)
return loss, grad
init_loss, _ = subopt_val_grad(x0)
results: list[OptimizerTrajectoryResult] = []
sqrt_k = math.sqrt(kappa)
beta_nag = (sqrt_k - 1.0) / (sqrt_k + 1.0)
beta_hb = beta_nag * beta_nag
lr_hb = 4.0 / ((math.sqrt(L) + math.sqrt(mu)) ** 2)
# 1-3: First-order GradientDescent variants
gd_configs = [
("gd", GradientDescent(lr=1.0 / L, momentum=0.0, variant="gd")),
("heavy_ball", GradientDescent(lr=lr_hb, momentum=beta_hb, variant="heavy_ball")),
("nesterov", GradientDescent(lr=1.0 / L, momentum=beta_nag, variant="nesterov")),
]
for name, opt in gd_configs:
x = x0.copy()
losses: list[float] = []
rms_hist: list[float] = []
g = np.zeros_like(x0)
for _ in range(n_steps):
_, g = subopt_val_grad(x)
x_next = opt.step(x, g)
rms_hist.append(_rms(x_next - x))
x = x_next
l_next, g = subopt_val_grad(x)
losses.append(l_next)
results.append(
OptimizerTrajectoryResult(
optimizer_name=name,
n_steps=n_steps,
initial_loss=init_loss,
final_loss=losses[-1] if losses else init_loss,
final_grad_norm=float(np.linalg.norm(g)),
loss_history=tuple(losses),
update_rms_history=tuple(rms_hist),
)
)
# 4: L-BFGS
x_lbfgs = x0.copy()
lbfgs_opt = LBFGS(history_size=10)
lbfgs_losses: list[float] = []
lbfgs_rms: list[float] = []
g_lbfgs = np.zeros_like(x0)
for _ in range(n_steps):
x_next, l_next, g_lbfgs = lbfgs_opt.step(subopt_val_grad, x_lbfgs)
lbfgs_rms.append(_rms(x_next - x_lbfgs))
x_lbfgs = x_next
lbfgs_losses.append(l_next)
results.append(
OptimizerTrajectoryResult(
optimizer_name="lbfgs",
n_steps=n_steps,
initial_loss=init_loss,
final_loss=lbfgs_losses[-1] if lbfgs_losses else init_loss,
final_grad_norm=float(np.linalg.norm(g_lbfgs)),
loss_history=tuple(lbfgs_losses),
update_rms_history=tuple(lbfgs_rms),
)
)
# 5: AdamW
x_aw = x0.copy()
aw_opt = AdamW(lr=0.25, weight_decay=0.0, decoupled=True)
aw_losses: list[float] = []
aw_rms: list[float] = []
g_aw = np.zeros_like(x0)
for _ in range(n_steps):
_, g_aw = subopt_val_grad(x_aw)
x_next = aw_opt.step(x_aw, g_aw)
aw_rms.append(_rms(x_next - x_aw))
x_aw = x_next
l_next, g_aw = subopt_val_grad(x_aw)
aw_losses.append(l_next)
results.append(
OptimizerTrajectoryResult(
optimizer_name="adamw",
n_steps=n_steps,
initial_loss=init_loss,
final_loss=aw_losses[-1] if aw_losses else init_loss,
final_grad_norm=float(np.linalg.norm(g_aw)),
loss_history=tuple(aw_losses),
update_rms_history=tuple(aw_rms),
)
)
# 6: Schedule-Free AdamW
sf_opt = ScheduleFreeAdamW(lr=0.5, weight_decay=0.0, init_params=x0)
sf_losses: list[float] = []
sf_rms: list[float] = []
x_eval_prev = sf_opt.eval_weights()
g_eval = np.zeros_like(x0)
for _ in range(n_steps):
y_train = sf_opt.train_weights()
_, g_train = subopt_val_grad(y_train)
x_eval_next = sf_opt.step(g_train)
sf_rms.append(_rms(x_eval_next - x_eval_prev))
x_eval_prev = x_eval_next
l_next, g_eval = subopt_val_grad(x_eval_next)
sf_losses.append(l_next)
results.append(
OptimizerTrajectoryResult(
optimizer_name="schedule_free",
n_steps=n_steps,
initial_loss=init_loss,
final_loss=sf_losses[-1] if sf_losses else init_loss,
final_grad_norm=float(np.linalg.norm(g_eval)),
loss_history=tuple(sf_losses),
update_rms_history=tuple(sf_rms),
)
)
return results
def run_matrix_optimizer_arena(
d_out: int = 48,
d_in: int = 24,
n_steps: int = 100,
lr: float = 0.05,
seed: int = 42,
) -> list[OptimizerTrajectoryResult]:
"""Benchmark AdamW vs. Muon (Moonlight RMS scaling) on ill-conditioned matrix regression."""
rng = np.random.default_rng(seed)
n_samples = max(64, 2 * d_in)
U, _ = np.linalg.qr(rng.standard_normal((d_in, d_in)), mode="complete")
V, _ = np.linalg.qr(rng.standard_normal((n_samples, d_in)), mode="reduced")
sx = np.geomspace(1.0, 0.05, d_in)
X = (U * sx) @ V.T
W_true = rng.standard_normal((d_out, d_in)) * 0.25
Y = W_true @ X
W0 = rng.standard_normal((d_out, d_in)) * 0.25
def matrix_loss_grad(W: np.ndarray) -> tuple[float, np.ndarray]:
residual = W @ X - Y
loss = 0.5 * float(np.sum(residual * residual))
grad = residual @ X.T
return loss, grad
init_loss, _ = matrix_loss_grad(W0)
# 1. AdamW matched to Moonlight initial step RMS (0.2 * lr on deterministic gradients)
aw_opt = AdamW(lr=0.2 * lr, weight_decay=0.0, decoupled=True)
W_aw = W0.copy()
aw_losses: list[float] = []
aw_rms: list[float] = []
g_aw = np.zeros_like(W0)
for _ in range(n_steps):
_, g_aw = matrix_loss_grad(W_aw)
W_next = aw_opt.step(W_aw, g_aw)
aw_rms.append(_rms(W_next - W_aw))
W_aw = W_next
l_next, g_aw = matrix_loss_grad(W_aw)
aw_losses.append(l_next)
# 2. Muon with Moonlight 0.2 * sqrt(max(d_out, d_in)) RMS scaling
muon_opt = Muon(lr=lr, momentum=0.95, weight_decay=0.0, ns_steps=5, rms_match_adamw=True)
W_muon = W0.copy()
muon_losses: list[float] = []
muon_rms: list[float] = []
g_muon = np.zeros_like(W0)
for _ in range(n_steps):
_, g_muon = matrix_loss_grad(W_muon)
W_muon, step_rms = muon_opt.step(W_muon, g_muon)
muon_rms.append(step_rms)
l_next, g_muon = matrix_loss_grad(W_muon)
muon_losses.append(l_next)
return [
OptimizerTrajectoryResult(
optimizer_name="adamw",
n_steps=n_steps,
initial_loss=init_loss,
final_loss=aw_losses[-1] if aw_losses else init_loss,
final_grad_norm=float(np.linalg.norm(g_aw, ord="fro")),
loss_history=tuple(aw_losses),
update_rms_history=tuple(aw_rms),
),
OptimizerTrajectoryResult(
optimizer_name="muon_moonlight",
n_steps=n_steps,
initial_loss=init_loss,
final_loss=muon_losses[-1] if muon_losses else init_loss,
final_grad_norm=float(np.linalg.norm(g_muon, ord="fro")),
loss_history=tuple(muon_losses),
update_rms_history=tuple(muon_rms),
),
]
def _round_to_bfloat16(val: float) -> float:
f32 = np.array([val], dtype=np.float32)
u32 = f32.view(np.uint32)
abs_bits = int(u32[0]) & 0x7FFFFFFF
if abs_bits > 0x7F800000:
bf_u32 = (u32 | np.uint32(0x00400000)) & np.uint32(0xFFFF0000)
return float(bf_u32.view(np.float32)[0])
if abs_bits == 0x7F800000:
return float(f32[0])
rounding_bias = np.uint32(0x00007FFF) + ((u32 >> np.uint32(16)) & np.uint32(1))
bf_u32 = (u32 + rounding_bias) & np.uint32(0xFFFF0000)
return float(bf_u32.view(np.float32)[0])
def verify_bf16_stagnation_vs_fp32_master(
weight_mag: float = 1.0,
grad_mag: float = 1e-3,
lr: float = 1e-2,
n_steps: int = 200,
) -> dict[str, Any]:
"""Demonstrate IEEE-754 bfloat16 update stagnation vs. fp32 master weight accumulation."""
w_init_bf16 = _round_to_bfloat16(weight_mag)
w_bf16 = w_init_bf16
w_fp32 = np.float32(weight_mag)
step_delta = lr * grad_mag
for _ in range(n_steps):
w_bf16 = _round_to_bfloat16(w_bf16 - step_delta)
w_fp32 = np.float32(float(w_fp32) - step_delta)
total_change_bf16 = abs(float(w_bf16) - float(w_init_bf16))
total_change_fp32 = abs(float(w_fp32) - float(weight_mag))
bf16_half_ulp = 2.0 ** -8 * max(abs(float(w_init_bf16)), 1e-30)
return {
"initial_weight": float(w_init_bf16),
"final_bf16": float(w_bf16),
"final_fp32_master": float(w_fp32),
"total_change_bf16": float(total_change_bf16),
"total_change_fp32_master": float(total_change_fp32),
"expected_exact_change": float(n_steps * step_delta),
"step_delta": float(step_delta),
"bf16_half_ulp": float(bf16_half_ulp),
"stagnated_in_bf16": bool(total_change_bf16 == 0.0),
}
"""End-to-end CLI demonstration and workbench_panels JSON exporter for Lab 02 (linalg_lab)."""
from __future__ import annotations
import argparse
import json
import math
import sys
from dataclasses import asdict
from pathlib import Path
from typing import Any
import numpy as np
import pandas as pd
try:
import linalg_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 linalg_lab.calculus_and_autodiff import (
ReverseTensor,
benchmark_jvp_vs_vjp,
central_diff_grad_check,
compare_quadrature_vs_monte_carlo,
hvp_forward_over_reverse,
simulate_checkpointing_memory,
triangular_flow_log_prob,
)
from linalg_lab.optimizers import (
HybridMuonAdamW,
Muon,
project_onto_simplex,
run_convex_optimizer_arena,
run_matrix_optimizer_arena,
verify_bf16_stagnation_vs_fp32_master,
verify_simplex_kkt,
zeropower_via_newtonschulz5,
)
from linalg_lab.svd_and_lowrank import (
benchmark_lora_dora_pissa_adaptation,
circulant_matvec_direct,
circulant_matvec_fft,
compare_normal_eq_vs_qr_svd,
compute_matrix_norms,
eckart_young_approximation,
ledoit_wolf_shrinkage,
pissa_initialize,
randomized_svd,
safe_logdet_cholesky,
)
def _sanitize_json_value(value: Any) -> Any:
"""Convert NumPy arrays, scalars, and non-finite floats into JSON-safe values."""
if isinstance(value, np.ndarray):
return [_sanitize_json_value(v) for v in value.tolist()]
if isinstance(value, (np.floating, float)):
fval = float(value)
if math.isinf(fval):
return "inf" if fval > 0 else "-inf"
if math.isnan(fval):
return "nan"
return fval
if isinstance(value, (np.integer, int)):
return int(value)
if isinstance(value, (np.bool_, bool)):
return bool(value)
if isinstance(value, (tuple, list)):
return [_sanitize_json_value(v) for v in value]
if isinstance(value, dict):
return {str(k): _sanitize_json_value(v) for k, v in value.items()}
return value
def _finite_bar_value(val: float, fallback: float = 1.0) -> float:
return float(val) if math.isfinite(val) else float(fallback)
def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
"""Parse CLI arguments for the Linear Algebra & Optimizers Workbench demonstration."""
parser = argparse.ArgumentParser(
description="Run Lab 02: SVD/rSVD/PEFT/Conditioning, Autodiff JVP/VJP/HVP/Flows, and SOTA Optimizers."
)
parser.add_argument("--n-rows", type=int, default=120)
parser.add_argument("--n-cols", type=int, default=12)
parser.add_argument("--target-kappa", type=float, default=1e7)
parser.add_argument("--rsvd-dim", type=int, default=128)
parser.add_argument("--rsvd-rank", type=int, default=12)
parser.add_argument("--convex-kappa", type=float, default=100.0)
parser.add_argument("--n-steps", type=int, default=120)
parser.add_argument("--seed", type=int, default=42)
parser.add_argument("--json-out", type=str, default=None)
return parser.parse_args(argv)
def main(argv: list[str] | None = None) -> int:
"""Execute all 4 benchmark sections and optionally export structured JSON + workbench_panels."""
args = parse_args(argv)
rng = np.random.default_rng(args.seed)
# =========================================================================
# [1] Subspaces, Eckart-Young, rSVD, Low-Rank Adapters & Conditioning
# =========================================================================
print("=" * 84)
print("[1] Subspaces, Eckart-Young, rSVD, Low-Rank Adapters & Conditioning")
print("=" * 84)
a_3x2 = np.array([[3.0, 2.0], [2.0, 3.0], [2.0, -2.0]], dtype=np.float64)
norms_3x2 = compute_matrix_norms(a_3x2)
ey_3x2 = eckart_young_approximation(a_3x2, rank_k=1)
print(
f"3x2 worked SVD: singular_values={[round(s, 4) for s in norms_3x2.singular_values]} | "
f"||A||_2={norms_3x2.spectral_norm:.4f}, ||A||_F={norms_3x2.frobenius_norm:.4f}, "
f"||A||_*={norms_3x2.nuclear_norm:.4f}"
)
print(
f"3x2 rank-1 Eckart-Young: spectral_err={ey_3x2.spectral_error:.6f} "
f"(theory={ey_3x2.theoretical_spectral_error:.6f}), "
f"frob_err={ey_3x2.frobenius_error:.6f} (theory={ey_3x2.theoretical_frobenius_error:.6f})"
)
# Slow-decay synthetic matrix for rSVD power iteration benchmark
u_rsvd, _ = np.linalg.qr(rng.standard_normal((args.rsvd_dim, args.rsvd_dim)), mode="complete")
v_rsvd, _ = np.linalg.qr(rng.standard_normal((args.rsvd_dim, args.rsvd_dim)), mode="complete")
rank_k = min(args.rsvd_rank, args.rsvd_dim)
decay_spec = 1.0 / (1.0 + 0.15 * np.arange(args.rsvd_dim, dtype=np.float64))
a_rsvd = (u_rsvd * decay_spec) @ v_rsvd.T
ey_rsvd = eckart_young_approximation(a_rsvd, rank_k=rank_k)
rsvd_sweep = [
randomized_svd(a_rsvd, rank_k=rank_k, oversampling=10, n_power_iter=q, seed=args.seed)
for q in (0, 1, 2)
]
rsvd_df = pd.DataFrame(
[
{
"method": "exact_eckart_young",
"q": "-",
"spectral_err": ey_rsvd.spectral_error,
"frobenius_err": ey_rsvd.frobenius_error,
}
]
+ [
{
"method": f"rsvd_q{res.n_power_iter}",
"q": res.n_power_iter,
"spectral_err": res.spectral_error,
"frobenius_err": res.frobenius_error,
}
for res in rsvd_sweep
]
)
print("\nrSVD power-iteration decay vs. Exact Eckart-Young:")
print(rsvd_df.to_string(index=False))
circ_c = rng.standard_normal(64)
circ_x = rng.standard_normal(64)
circ_diff = float(np.max(np.abs(circulant_matvec_direct(circ_c, circ_x) - circulant_matvec_fft(circ_c, circ_x))))
print(f"\nCirculant FFT vs. direct matvec max abs diff (n=64): {circ_diff:.3e}")
pissa_check = pissa_initialize(rng.standard_normal((48, 32)), rank_r=4)
adapter_rows = benchmark_lora_dora_pissa_adaptation(
d_out=48, d_in=32, rank_r=4, n_steps=min(80, args.n_steps), lr=0.05, seed=args.seed
)
adapter_df = pd.DataFrame(
[
{
"method": row.method,
"rank_r": row.rank_r,
"n_steps": row.n_steps,
"initial_loss": row.initial_loss,
"final_loss": row.final_loss,
}
for row in adapter_rows
]
)
print(f"PiSSA lossless init reconstruction error: {pissa_check.reconstruction_error:.3e}")
print("Low-Rank Adapter Arena (LoRA vs. DoRA vs. PiSSA):")
print(adapter_df.to_string(index=False))
cond_res = compare_normal_eq_vs_qr_svd(
n_rows=args.n_rows,
n_cols=args.n_cols,
target_kappa=args.target_kappa,
seed=args.seed,
)
print(
f"\nConditioning Benchmark (kappa(X)={cond_res.kappa_design:.3e}, kappa(X^T X)={cond_res.kappa_gram:.3e}):\n"
f" Normal Eq rel_err = {cond_res.normal_eq_rel_error:.3e} | "
f"QR rel_err = {cond_res.qr_rel_error:.3e} | "
f"SVD lstsq rel_err = {cond_res.svd_lstsq_rel_error:.3e}"
)
# =========================================================================
# [2] Autodiff JVP/VJP, Pearlmutter HVP, Flows & Monte Carlo vs. Quadrature
# =========================================================================
print("\n" + "=" * 84)
print("[2] Autodiff JVP/VJP, Pearlmutter HVP, Flows & Monte Carlo vs. Quadrature")
print("=" * 84)
ad_bench = benchmark_jvp_vs_vjp(n_in=64, m_out=4, repeats=5, seed=args.seed)
ad_df = pd.DataFrame([asdict(r) for r in ad_bench])
print("Full Jacobian Assembly (R^64 -> R^4):")
print(ad_df.to_string(index=False))
# Non-quadratic logsumexp + quadratic objective for Pearlmutter HVP & central-diff check
h_dim = 8
W_hvp = rng.standard_normal((6, h_dim)) * 0.4
b_hvp = rng.standard_normal(6) * 0.2
M_hvp = rng.standard_normal((h_dim, h_dim)) * 0.3
Q_hvp = M_hvp.T @ M_hvp + 0.5 * np.eye(h_dim)
x_hvp = rng.standard_normal(h_dim) * 0.5
v_hvp = rng.standard_normal(h_dim)
def hvp_obj_ad(tx: ReverseTensor) -> ReverseTensor:
return (W_hvp @ tx + b_hvp).logsumexp() + 0.5 * (tx @ (Q_hvp @ tx))
def hvp_obj_np(x_vec: np.ndarray) -> float:
logits = W_hvp @ x_vec + b_hvp
m_val = float(np.max(logits))
lse = m_val + float(np.log(np.sum(np.exp(logits - m_val))))
return lse + 0.5 * float(x_vec @ (Q_hvp @ x_vec))
def hvp_grad_np(x_vec: np.ndarray) -> np.ndarray:
logits = W_hvp @ x_vec + b_hvp
shifted = logits - np.max(logits)
probs = np.exp(shifted) / np.sum(np.exp(shifted))
return W_hvp.T @ probs + Q_hvp @ x_vec
logits0 = W_hvp @ x_hvp + b_hvp
probs0 = np.exp(logits0 - np.max(logits0))
probs0 /= np.sum(probs0)
wv0 = W_hvp @ v_hvp
hvp_exact = W_hvp.T @ (probs0 * wv0 - probs0 * float(np.dot(probs0, wv0))) + Q_hvp @ v_hvp
ad_grad, ad_hvp = hvp_forward_over_reverse(hvp_obj_ad, x_hvp, v_hvp)
hvp_max_err = float(np.max(np.abs(ad_hvp - hvp_exact)))
gcheck_opt = central_diff_grad_check(hvp_obj_np, hvp_grad_np, x_hvp, eps=1e-6)
gcheck_coarse = central_diff_grad_check(hvp_obj_np, hvp_grad_np, x_hvp, eps=1e-2)
gcheck_tiny = central_diff_grad_check(hvp_obj_np, hvp_grad_np, x_hvp, eps=1e-13)
print(
f"\nPearlmutter FoR HVP max abs error vs exact H@v: {hvp_max_err:.3e} | "
f"grad max err: {float(np.max(np.abs(ad_grad - hvp_grad_np(x_hvp)))):.3e}"
)
print(
f"Central-diff grad check errors: eps=1e-6 -> {gcheck_opt.max_abs_error:.3e} (passed={gcheck_opt.passed}) | "
f"eps=1e-2 -> {gcheck_coarse.max_abs_error:.3e} | eps=1e-13 -> {gcheck_tiny.max_abs_error:.3e}"
)
flow_x, flow_log_px, flow_log_det = triangular_flow_log_prob(
z=np.array([0.5, -0.3, 1.1]),
scale_log=np.array([0.2, -0.4, 0.3]),
shift=np.array([0.1, -0.2, 0.4]),
)
print(
f"Triangular Flow sample: x={np.round(flow_x, 4).tolist()}, "
f"log p_X(x)={flow_log_px:.5f}, log|det J_T|={flow_log_det:.5f}"
)
quad_mc_rows = compare_quadrature_vs_monte_carlo(dims=(2, 6, 10), budget_evals=4096, seed=args.seed)
quad_df = pd.DataFrame([asdict(r) for r in quad_mc_rows])
print("\nQuadrature O(N^{-2/d}) vs. Monte Carlo O(N^{-1/2}) (budget=4096):")
print(quad_df.to_string(index=False))
ckpt_rows = simulate_checkpointing_memory(n_layers=64)
ckpt_df = pd.DataFrame([asdict(r) for r in ckpt_rows])
print("\n64-Layer Activation Checkpointing & SAC Memory Tradeoff:")
print(ckpt_df.to_string(index=False))
# =========================================================================
# [3] Convex & SOTA Optimizers (KKT Simplex, GD/NAG/L-BFGS, AdamW, Muon/Moonlight)
# =========================================================================
print("\n" + "=" * 84)
print("[3] Convex & SOTA Optimizers (KKT Simplex, GD/NAG/L-BFGS, AdamW, Muon/Moonlight)")
print("=" * 84)
simplex_y = np.array([1.8, 1.1, 0.2, -0.4], dtype=np.float64)
p_star, nu_star, k_star = project_onto_simplex(simplex_y)
kkt_rep = verify_simplex_kkt(simplex_y)
kkt_max_res = max(
kkt_rep.primal_residual,
kkt_rep.stationarity_residual,
kkt_rep.complementary_slackness_residual,
)
print(
f"Simplex Projection of [1.8, 1.1, 0.2, -0.4] -> p*={np.round(p_star, 4).tolist()}, "
f"nu*={nu_star:.4f}, k*={k_star}, KKT satisfied={kkt_rep.kkt_satisfied} (max_res={kkt_max_res:.2e})"
)
convex_rows = run_convex_optimizer_arena(
kappa=args.convex_kappa, dim=16, n_steps=args.n_steps, seed=args.seed
)
convex_df = pd.DataFrame(
[
{
"optimizer": r.optimizer_name,
"initial_loss": r.initial_loss,
"final_loss": r.final_loss,
"final_grad_norm": r.final_grad_norm,
}
for r in convex_rows
]
)
print(f"\nConvex Optimizer Arena (kappa={args.convex_kappa}, dim=16, steps={args.n_steps}):")
print(convex_df.to_string(index=False))
# NS5 singular value contraction check + Moonlight shape-invariance check
ns_test_mat = np.diag(np.geomspace(0.01, 0.99, 10))
ns_test_mat = ns_test_mat / np.linalg.norm(ns_test_mat, ord="fro")
ns_out = zeropower_via_newtonschulz5(ns_test_mat, steps=5)
ns_svals = np.linalg.svd(ns_out, compute_uv=False)
ns_nonzero = ns_svals[ns_svals > 1e-6]
ns_min, ns_max = float(np.min(ns_nonzero)), float(np.max(ns_nonzero))
muon_lr_probe = 0.02
muon_shape_audits: list[dict[str, Any]] = []
for shape in ((16, 128), (64, 64), (128, 16)):
m_opt = Muon(lr=muon_lr_probe, momentum=0.95, weight_decay=0.01, ns_steps=5, rms_match_adamw=True)
w_probe = rng.standard_normal(shape) * 0.02
g_probe = rng.standard_normal(shape)
_, upd_rms = m_opt.step(w_probe, g_probe)
muon_shape_audits.append(
{
"shape": f"{shape[0]}x{shape[1]}",
"update_rms": upd_rms,
"ratio_to_lr": upd_rms / muon_lr_probe,
"ns_min": ns_min,
"ns_max": ns_max,
}
)
matrix_rows = run_matrix_optimizer_arena(d_out=48, d_in=24, n_steps=100, lr=0.05, seed=args.seed)
print(
f"\nMuon NS5 Singular Value Band (from [0.01, 1.0]): [{ns_min:.4f}, {ns_max:.4f}] | "
f"Moonlight RMS/lr across shapes: "
+ ", ".join(f"{r['shape']}={r['ratio_to_lr']:.3f}" for r in muon_shape_audits)
)
for row in matrix_rows:
print(
f" Matrix Arena [{row.optimizer_name:14s}]: init={row.initial_loss:.4f} -> "
f"final={row.final_loss:.4f} | final_step_rms={row.update_rms_history[-1]:.5f}"
)
hybrid_demo = HybridMuonAdamW(
{
"embed_tokens": np.zeros((32, 16)),
"layer0.attn_proj": np.zeros((16, 16)),
"layer0.rms_norm": np.ones(16),
"lm_head": np.zeros((32, 16)),
}
)
print(f"HybridMuonAdamW routing: {hybrid_demo.routing}")
# =========================================================================
# [4] Numerical Guardrails Summary (slogdet, Ledoit-Wolf, bf16 Master Rescue)
# =========================================================================
print("\n" + "=" * 84)
print("[4] Numerical Guardrails Summary (slogdet, Ledoit-Wolf, bf16 Master Rescue)")
print("=" * 84)
q_spd, _ = np.linalg.qr(rng.standard_normal((500, 500)), mode="complete")
eigs_under = np.geomspace(0.05, 0.25, 500)
k_under = (q_spd * eigs_under) @ q_spd.T
naive_det_under = float(np.linalg.det(k_under))
chol_logdet_under = safe_logdet_cholesky(k_under)
_, slogdet_ref = np.linalg.slogdet(k_under)
k_perturbed = k_under.copy()
k_perturbed = (q_spd * np.concatenate([eigs_under[:-1], [-1e-9]])) @ q_spd.T
chol_logdet_jitter = safe_logdet_cholesky(k_perturbed)
# Ledoit-Wolf shrinkage at p_assets=45, n_bars=50
f_lat = rng.standard_normal((50, 2))
load = rng.standard_normal((45, 2)) * 0.6
ret_45x50 = f_lat @ load.T + 0.3 * rng.standard_normal((50, 45))
_, lw_delta, kappa_samp, kappa_lw = ledoit_wolf_shrinkage(ret_45x50)
bf16_audit = verify_bf16_stagnation_vs_fp32_master(
weight_mag=1.0, grad_mag=1e-3, lr=1e-2, n_steps=200
)
print(
f"d=500 logdet guard: naive det={naive_det_under:.3e} | "
f"safe_logdet_cholesky={chol_logdet_under:.4f} (slogdet={float(slogdet_ref):.4f}) | "
f"jittered (-1e-9 eig)={chol_logdet_jitter:.4f}"
)
print(
f"Ledoit-Wolf (n=50, p=45): delta={lw_delta:.4f} | "
f"kappa_sample={kappa_samp:.2f} -> kappa_lw={kappa_lw:.2f}"
)
print(
f"bf16 vs fp32 master (200 steps, step_delta=1e-5): "
f"bf16_delta={bf16_audit['total_change_bf16']:.6f} (stagnated={bf16_audit['stagnated_in_bf16']}) | "
f"fp32_master_delta={bf16_audit['total_change_fp32_master']:.6f}"
)
if args.json_out is not None:
out_path = Path(args.json_out)
out_path.parent.mkdir(parents=True, exist_ok=True)
rsvd_q2 = rsvd_sweep[-1]
quad_d10 = next(r for r in quad_mc_rows if r.dim == 10 and r.method == "trapezoidal_grid")
mc_d10 = next(r for r in quad_mc_rows if r.dim == 10 and r.method == "monte_carlo")
ne_ratio = (
cond_res.normal_eq_rel_error / max(cond_res.qr_rel_error, 1e-30)
if math.isfinite(cond_res.normal_eq_rel_error)
else math.inf
)
rsvd_gap = rsvd_q2.spectral_error - rsvd_q2.exact_spectral_error
workbench_panels = {
"kpis": [
{
"id": "kpi_normal_eq_vs_qr",
"label": "Normal Eq vs. QR Error Gap",
"value": f"{ne_ratio:.1e}x" if math.isfinite(ne_ratio) else "inf",
"unit": "rel_err ratio",
"status": "ok" if cond_res.qr_rel_error < 1e-3 * cond_res.normal_eq_rel_error else "warn",
"detail": (
f"kappa(X)={cond_res.kappa_design:.2e}; QR={cond_res.qr_rel_error:.2e} "
f"vs NormalEq={cond_res.normal_eq_rel_error:.2e}"
),
},
{
"id": "kpi_rsvd_q2_error",
"label": "rSVD (q=2) Spectral Gap",
"value": f"{rsvd_gap:.2e}",
"unit": "||A-Ak||_2 gap",
"status": "ok" if rsvd_gap < 0.05 else "warn",
"detail": (
f"rSVD(q=2)={rsvd_q2.spectral_error:.5f} vs "
f"Exact Eckart-Young={rsvd_q2.exact_spectral_error:.5f}"
),
},
{
"id": "kpi_hvp_precision",
"label": "FoR Pearlmutter HVP Error",
"value": f"{hvp_max_err:.2e}",
"unit": "max |Hvp - Hv|",
"status": "ok" if hvp_max_err < 1e-12 else "warn",
"detail": "Exact Dual-over-Wengert forward-over-reverse sweep without 2nd backward tape",
},
{
"id": "kpi_simplex_kkt",
"label": "Simplex KKT Max Residual",
"value": f"{kkt_max_res:.2e}",
"unit": "max residual",
"status": "ok" if kkt_rep.kkt_satisfied else "critical",
"detail": f"nu*={nu_star:.4f}, support k*={k_star}, exact Duchi O(n log n) water-fill",
},
{
"id": "kpi_muon_ns5_band",
"label": "Muon NS5 Singular Band",
"value": f"[{ns_min:.3f}, {ns_max:.3f}]",
"unit": "sigma_i(O_t)",
"status": "ok" if (0.68 <= ns_min and ns_max <= 1.14) else "warn",
"detail": (
f"Moonlight RMS/lr={muon_shape_audits[0]['ratio_to_lr']:.3f} across rectangular & square shapes"
),
},
{
"id": "kpi_bf16_rescue",
"label": "fp32 Master vs. bf16 Stall",
"value": f"{bf16_audit['total_change_fp32_master']:.4f}",
"unit": "fp32 delta (bf16=0)",
"status": "ok" if bf16_audit["stagnated_in_bf16"] else "warn",
"detail": (
f"200 steps @ delta=1e-5: pure bf16={bf16_audit['total_change_bf16']:.1f} vs "
f"fp32 master={bf16_audit['total_change_fp32_master']:.5f}"
),
},
],
"bars": [
{
"id": "bar_conditioning_rel_error",
"title": f"Least-Squares Relative Error at kappa={args.target_kappa:.1e}",
"metric_label": "Relative Error ||w_hat - w*|| / ||w*||",
"items": [
{
"label": "Normal Equations (X^T X)",
"value": _finite_bar_value(cond_res.normal_eq_rel_error, 1.0),
"display": f"{cond_res.normal_eq_rel_error:.2e}",
"css_class": "is-slow",
},
{
"label": "Householder QR",
"value": _finite_bar_value(cond_res.qr_rel_error),
"display": f"{cond_res.qr_rel_error:.2e}",
"css_class": "is-fast",
},
{
"label": "SVD lstsq",
"value": _finite_bar_value(cond_res.svd_lstsq_rel_error),
"display": f"{cond_res.svd_lstsq_rel_error:.2e}",
"css_class": "is-fast",
},
],
},
{
"id": "bar_jvp_vs_vjp_sweeps",
"title": "Full Jacobian Sweep Count (R^64 -> R^4)",
"metric_label": "AD Sweeps",
"items": [
{
"label": "Forward JVP (DualArray)",
"value": float(ad_bench[0].n_sweeps),
"display": f"{ad_bench[0].n_sweeps} sweeps",
"css_class": "is-slow",
},
{
"label": "Reverse VJP (Wengert)",
"value": float(ad_bench[1].n_sweeps),
"display": f"{ad_bench[1].n_sweeps} sweeps",
"css_class": "is-fast",
},
],
},
{
"id": "bar_quadrature_vs_mc_error",
"title": "10D Integration Absolute Error (4096 Budget)",
"metric_label": "|Estimate - 1.0|",
"items": [
{
"label": "Trapezoidal Grid (d=10)",
"value": float(quad_d10.abs_error),
"display": f"{quad_d10.abs_error:.4f}",
"css_class": "is-slow",
},
{
"label": "Monte Carlo (d=10)",
"value": float(mc_d10.abs_error),
"display": f"{mc_d10.abs_error:.4f}",
"css_class": "is-fast",
},
],
},
{
"id": "bar_optimizer_final_loss",
"title": f"Convex Arena Final Suboptimality (kappa={args.convex_kappa}, {args.n_steps} steps)",
"metric_label": "f(x_T) - f(x*)",
"items": [
{
"label": r.optimizer_name,
"value": float(r.final_loss),
"display": f"{r.final_loss:.2e}",
"css_class": (
"is-fast"
if r.final_loss < 1e-6
else ("is-mid" if r.final_loss < 1e-2 else "is-slow")
),
}
for r in convex_rows
],
},
],
"tables": [
{
"id": "table_eckart_young_rsvd",
"title": f"Eckart-Young Exact vs. Randomized SVD (dim={args.rsvd_dim}, rank={rank_k})",
"columns": ["method", "power_iters", "spectral_error", "frobenius_error"],
"rows": [
["exact_eckart_young", 0, round(ey_rsvd.spectral_error, 6), round(ey_rsvd.frobenius_error, 6)]
]
+ [
[f"rsvd_q{r.n_power_iter}", r.n_power_iter, round(r.spectral_error, 6), round(r.frobenius_error, 6)]
for r in rsvd_sweep
],
},
{
"id": "table_lora_dora_pissa",
"title": "Low-Rank Adaptation Arena (LoRA vs. DoRA vs. PiSSA)",
"columns": ["method", "rank_r", "n_steps", "initial_loss", "final_loss"],
"rows": [
[
row.method,
row.rank_r,
row.n_steps,
round(row.initial_loss, 6),
round(row.final_loss, 6),
]
for row in adapter_rows
],
},
{
"id": "table_convex_optimizers",
"title": f"Convex Optimizer Arena (kappa={args.convex_kappa}, dim=16)",
"columns": ["optimizer", "n_steps", "initial_loss", "final_loss", "final_grad_norm"],
"rows": [
[
row.optimizer_name,
row.n_steps,
round(row.initial_loss, 6),
float(f"{row.final_loss:.6e}"),
float(f"{row.final_grad_norm:.6e}"),
]
for row in convex_rows
],
},
{
"id": "table_muon_moonlight_spectrum",
"title": "Muon NS5 Spectrum & Moonlight RMS Shape Invariance",
"columns": ["shape", "update_rms", "rms_over_lr", "ns_sigma_min", "ns_sigma_max"],
"rows": [
[
item["shape"],
round(item["update_rms"], 6),
round(item["ratio_to_lr"], 4),
round(item["ns_min"], 4),
round(item["ns_max"], 4),
]
for item in muon_shape_audits
],
},
],
}
payload = {
"config": vars(args),
"workbench_panels": workbench_panels,
"svd_and_lowrank": {
"norms_3x2": asdict(norms_3x2),
"eckart_young_3x2": {
"rank_k": ey_3x2.rank_k,
"spectral_error": ey_3x2.spectral_error,
"theoretical_spectral_error": ey_3x2.theoretical_spectral_error,
"frobenius_error": ey_3x2.frobenius_error,
"theoretical_frobenius_error": ey_3x2.theoretical_frobenius_error,
"retained_energy_ratio": ey_3x2.retained_energy_ratio,
},
"rsvd_power_sweep": [
{
"n_power_iter": r.n_power_iter,
"spectral_error": r.spectral_error,
"frobenius_error": r.frobenius_error,
"exact_spectral_error": r.exact_spectral_error,
"exact_frobenius_error": r.exact_frobenius_error,
}
for r in rsvd_sweep
],
"circulant_fft_max_diff": circ_diff,
"pissa_reconstruction_error": pissa_check.reconstruction_error,
"lowrank_adapters": [asdict(r) for r in adapter_rows],
"conditioning": asdict(cond_res),
"logdet_d500": {
"naive_det": naive_det_under,
"cholesky_logdet": chol_logdet_under,
"slogdet_ref": float(slogdet_ref),
"jittered_logdet": chol_logdet_jitter,
},
"ledoit_wolf": {
"delta": lw_delta,
"kappa_sample": kappa_samp,
"kappa_lw": kappa_lw,
},
},
"calculus_and_autodiff": {
"jvp_vs_vjp": [asdict(r) for r in ad_bench],
"hvp_max_abs_error": hvp_max_err,
"grad_check": {
"eps_1e-6_err": gcheck_opt.max_abs_error,
"eps_1e-6_passed": gcheck_opt.passed,
"eps_1e-2_err": gcheck_coarse.max_abs_error,
"eps_1e-13_err": gcheck_tiny.max_abs_error,
},
"triangular_flow": {
"x": flow_x,
"log_px": flow_log_px,
"log_abs_det_J": flow_log_det,
},
"quadrature_vs_monte_carlo": [asdict(r) for r in quad_mc_rows],
"checkpointing_memory": [asdict(r) for r in ckpt_rows],
},
"optimizers": {
"simplex_kkt": asdict(kkt_rep),
"convex_arena": [asdict(r) for r in convex_rows],
"matrix_arena": [asdict(r) for r in matrix_rows],
"muon_ns5_band": {"min": ns_min, "max": ns_max},
"muon_moonlight_shapes": muon_shape_audits,
"hybrid_routing": hybrid_demo.routing,
"bf16_vs_fp32_master": bf16_audit,
},
}
out_path.write_text(
json.dumps(_sanitize_json_value(payload), indent=2),
encoding="utf-8",
)
print(f"\nSaved structured JSON report to: {out_path}")
return 0
if __name__ == "__main__":
raise SystemExit(main())
"""14-Test Verification Contract Suite for linalg_lab (Unit T1-P1-U02)."""
from __future__ import annotations
import ast
import json
import math
import subprocess
import sys
from pathlib import Path
import numpy as np
import pytest
from linalg_lab import (
AdamW,
DualArray,
HybridMuonAdamW,
Muon,
ReverseTensor,
benchmark_jvp_vs_vjp,
benchmark_lora_dora_pissa_adaptation,
central_diff_grad_check,
central_diff_jacobian,
circulant_matvec_direct,
circulant_matvec_fft,
compare_normal_eq_vs_qr_svd,
compare_quadrature_vs_monte_carlo,
compute_full_jacobian_jvp,
compute_full_jacobian_vjp,
compute_matrix_norms,
dora_effective_weight,
eckart_young_approximation,
hvp_forward_over_reverse,
ledoit_wolf_shrinkage,
pissa_initialize,
project_onto_simplex,
randomized_svd,
run_convex_optimizer_arena,
safe_logdet_cholesky,
simulate_checkpointing_memory,
triangular_flow_log_prob,
verify_bf16_stagnation_vs_fp32_master,
verify_simplex_kkt,
zeropower_via_newtonschulz5,
)
LAB_ROOT = Path(__file__).resolve().parents[1]
def test_four_subspaces_norms_and_spectral_nuclear_duality() -> None:
"""Verify Rank-Nullity, orthogonal subspaces, projector idempotency, norm bounds, and polar duality."""
rng = np.random.default_rng(42)
# Construct rank-deficient 5x4 matrix of exact rank 3
u_raw, _ = np.linalg.qr(rng.standard_normal((5, 3)), mode="reduced")
v_raw, _ = np.linalg.qr(rng.standard_normal((4, 3)), mode="reduced")
s_true = np.array([6.0, 2.5, 0.8])
A = (u_raw * s_true) @ v_raw.T
profile = compute_matrix_norms(A)
m, n = profile.shape
assert (m, n) == (5, 4)
assert profile.rank == 3
# Full SVD reveals orthonormal bases of all four fundamental subspaces
U, _s, Vt = np.linalg.svd(A, full_matrices=True)
r = profile.rank
row_basis = Vt[:r, :].T # C(A^T), shape (4, 3)
null_basis = Vt[r:, :].T # N(A), shape (4, 1)
col_basis = U[:, :r] # C(A), shape (5, 3)
left_null_basis = U[:, r:] # N(A^T), shape (5, 2)
assert row_basis.shape[1] + null_basis.shape[1] == n
assert col_basis.shape[1] + left_null_basis.shape[1] == m
assert np.allclose(row_basis.T @ null_basis, 0.0, atol=1e-12)
assert np.allclose(col_basis.T @ left_null_basis, 0.0, atol=1e-12)
assert np.allclose(A @ null_basis, 0.0, atol=1e-12)
assert np.allclose(A.T @ left_null_basis, 0.0, atol=1e-12)
# Orthogonal projection idempotency & symmetry on full-column-rank 3x2 matrix
A_full = np.array([[3.0, 2.0], [2.0, 3.0], [2.0, -2.0]], dtype=np.float64)
P = A_full @ np.linalg.solve(A_full.T @ A_full, A_full.T)
assert np.allclose(P @ P, P, atol=1e-12)
assert np.allclose(P.T, P, atol=1e-12)
# Exact Matrix Norm Equivalence Bounds (Theorem 2.2)
sqrt_r = math.sqrt(r)
assert profile.spectral_norm <= profile.frobenius_norm + 1e-12
assert profile.frobenius_norm <= sqrt_r * profile.spectral_norm + 1e-12
assert profile.frobenius_norm <= profile.nuclear_norm + 1e-12
assert profile.nuclear_norm <= sqrt_r * profile.frobenius_norm + 1e-12
# Exact Spectral-Nuclear Duality: tr(A^T (U_r V_r^T)) == ||A||_*
polar_factor = U[:, :r] @ Vt[:r, :]
dual_trace = float(np.trace(A.T @ polar_factor))
assert dual_trace == pytest.approx(profile.nuclear_norm, rel=1e-12, abs=1e-12)
def test_cholesky_logdet_and_progressive_jitter_stability() -> None:
"""Verify safe_logdet_cholesky matches slogdet at d=500 where det() overflows/underflows and survives -1e-9 eig."""
rng = np.random.default_rng(7)
d = 500
Q, _ = np.linalg.qr(rng.standard_normal((d, d)), mode="complete")
# Underflowing SPD matrix: det(K) == 0.0 -> log(det(K)) == -inf
eigs_under = np.geomspace(0.05, 0.25, d)
K_under = (Q * eigs_under) @ Q.T
assert float(np.linalg.det(K_under)) == 0.0
_, ref_under = np.linalg.slogdet(K_under)
assert safe_logdet_cholesky(K_under) == pytest.approx(float(ref_under), rel=1e-10, abs=1e-10)
# Overflowing SPD matrix: det(K) == inf -> log(det(K)) == inf
eigs_over = np.geomspace(5.0, 20.0, d)
K_over = (Q * eigs_over) @ Q.T
with np.errstate(over="ignore"):
assert math.isinf(float(np.linalg.det(K_over)))
_, ref_over = np.linalg.slogdet(K_over)
assert safe_logdet_cholesky(K_over) == pytest.approx(float(ref_over), rel=1e-10, abs=1e-10)
# Slight indefiniteness (-1e-9 negative eigenvalue): direct cholesky fails, progressive jitter recovers
eigs_bad = eigs_under.copy()
eigs_bad[-1] = -1e-9
K_bad = (Q * eigs_bad) @ Q.T
with pytest.raises(np.linalg.LinAlgError):
np.linalg.cholesky(0.5 * (K_bad + K_bad.T))
recovered = safe_logdet_cholesky(K_bad)
assert math.isfinite(recovered)
def test_circulant_fft_matches_direct_matvec() -> None:
"""Verify O(n log n) FFT circulant matvec matches O(n^2) direct matvec across sizes."""
rng = np.random.default_rng(123)
for n in (32, 64, 128):
first_col = rng.standard_normal(n)
x = rng.standard_normal(n)
y_direct = circulant_matvec_direct(first_col, x)
y_fft = circulant_matvec_fft(first_col, x)
assert np.allclose(y_fft, y_direct, atol=1e-11, rtol=1e-11)
def test_eckart_young_optimality_and_3x2_worked_example() -> None:
"""Verify exact 3x2 SVD worked example and Eckart-Young optimality against 20 random rank-k matrices."""
A_3x2 = np.array([[3.0, 2.0], [2.0, 3.0], [2.0, -2.0]], dtype=np.float64)
norms = compute_matrix_norms(A_3x2)
assert norms.singular_values == pytest.approx((5.0, 3.0), rel=1e-12, abs=1e-12)
ey_3x2 = eckart_young_approximation(A_3x2, rank_k=1)
assert ey_3x2.spectral_error == pytest.approx(3.0, rel=1e-12, abs=1e-12)
assert ey_3x2.theoretical_spectral_error == pytest.approx(3.0, rel=1e-12, abs=1e-12)
assert ey_3x2.frobenius_error == pytest.approx(3.0, rel=1e-12, abs=1e-12)
assert ey_3x2.theoretical_frobenius_error == pytest.approx(3.0, rel=1e-12, abs=1e-12)
rng = np.random.default_rng(99)
A = rng.standard_normal((12, 8))
rank_k = 3
ey = eckart_young_approximation(A, rank_k=rank_k)
assert ey.spectral_error == pytest.approx(ey.theoretical_spectral_error, rel=1e-12, abs=1e-12)
assert ey.frobenius_error == pytest.approx(ey.theoretical_frobenius_error, rel=1e-12, abs=1e-12)
for _ in range(20):
# Test both purely random rank-k matrices and local perturbations near A_k
if _ % 2 == 0:
B = rng.standard_normal((12, rank_k)) @ rng.standard_normal((rank_k, 8))
else:
u_b, _, vt_b = np.linalg.svd(ey.approx_matrix + 0.1 * rng.standard_normal((12, 8)), full_matrices=False)
B = (u_b[:, :rank_k] * rng.uniform(0.5, 2.0, size=rank_k)) @ vt_b[:rank_k, :]
spec_b = float(np.linalg.norm(A - B, ord=2))
frob_b = float(np.linalg.norm(A - B, ord="fro"))
assert spec_b >= ey.spectral_error - 1e-12
assert frob_b >= ey.frobenius_error - 1e-12
def test_randomized_svd_power_iter_and_pissa_dora_adapters() -> None:
"""Verify rSVD power iteration monotonicity, lossless PiSSA init, and DoRA/PiSSA vs. LoRA adaptation."""
rng = np.random.default_rng(42)
m, n, rank_k = 80, 60, 10
U, _ = np.linalg.qr(rng.standard_normal((m, m)), mode="complete")
V, _ = np.linalg.qr(rng.standard_normal((n, n)), mode="complete")
slow_spectrum = 1.0 / (1.0 + 0.12 * np.arange(min(m, n), dtype=np.float64))
A = (U[:, : min(m, n)] * slow_spectrum) @ V[: min(m, n), :]
r0 = randomized_svd(A, rank_k=rank_k, oversampling=8, n_power_iter=0, seed=42)
r1 = randomized_svd(A, rank_k=rank_k, oversampling=8, n_power_iter=1, seed=42)
r2 = randomized_svd(A, rank_k=rank_k, oversampling=8, n_power_iter=2, seed=42)
assert r0.spectral_error >= r1.spectral_error >= r2.spectral_error
assert r0.frobenius_error >= r1.frobenius_error >= r2.frobenius_error
assert r2.spectral_error <= 1.25 * r2.exact_spectral_error
W = rng.standard_normal((48, 32))
pissa = pissa_initialize(W, rank_r=4)
assert pissa.reconstruction_error < 1e-11
mag_ones = np.linalg.norm(W, axis=1)
w_dora_id = dora_effective_weight(W, np.zeros((48, 4)), np.zeros((4, 32)), mag_ones)
assert np.allclose(w_dora_id, W, atol=1e-10)
bench = {r.method: r for r in benchmark_lora_dora_pissa_adaptation(seed=42)}
assert bench["pissa"].final_loss < bench["lora"].final_loss
assert bench["dora"].final_loss < bench["lora"].final_loss
def test_condition_number_squaring_normal_eq_vs_qr_svd() -> None:
"""Verify kappa(X^T X) = kappa(X)^2 digit loss vs. QR/SVD and Ledoit-Wolf eigenvalue conditioning."""
cond_res = compare_normal_eq_vs_qr_svd(n_rows=120, n_cols=12, target_kappa=1e7, seed=42)
assert cond_res.kappa_gram == pytest.approx(cond_res.kappa_design ** 2, rel=5e-2)
assert cond_res.qr_rel_error < 1e-3 * cond_res.normal_eq_rel_error
assert cond_res.svd_lstsq_rel_error < 1e-3 * cond_res.normal_eq_rel_error
rng = np.random.default_rng(42)
n_bars, p_assets = 50, 45
factors = rng.standard_normal((n_bars, 2))
loadings = rng.standard_normal((p_assets, 2)) * 0.6
returns = factors @ loadings.T + 0.3 * rng.standard_normal((n_bars, p_assets))
sigma_lw, delta, kappa_sample, kappa_lw = ledoit_wolf_shrinkage(returns)
assert 0.0 < delta < 1.0
assert np.allclose(sigma_lw, sigma_lw.T, atol=1e-14)
assert kappa_lw < 0.2 * kappa_sample
def test_jvp_vjp_exact_jacobian_parity_and_direction_complexity() -> None:
"""Verify Numerator-Layout JVP/VJP Jacobian parity against analytical and finite-diff, plus sweep counts."""
rng = np.random.default_rng(42)
W1 = rng.standard_normal((6, 5)) * 0.5
b1 = rng.standard_normal(6) * 0.2
W2 = rng.standard_normal((3, 6)) * 0.5
b2 = rng.standard_normal(3) * 0.1
x = rng.standard_normal(5) * 0.7
def smooth_map_ad(z: DualArray | ReverseTensor) -> DualArray | ReverseTensor:
return W2 @ (W1 @ z + b1).tanh() + b2 + 0.2 * (W1[:3] @ z).square()
def smooth_map_np(z: np.ndarray) -> np.ndarray:
return W2 @ np.tanh(W1 @ z + b1) + b2 + 0.2 * np.square(W1[:3] @ z)
h = np.tanh(W1 @ x + b1)
j_tanh = (W2 * (1.0 - h * h)[None, :]) @ W1
u_sq = W1[:3] @ x
j_sq = 0.4 * (u_sq[:, None] * W1[:3])
j_exact = j_tanh + j_sq
j_jvp = compute_full_jacobian_jvp(smooth_map_ad, x) # type: ignore[arg-type]
j_vjp = compute_full_jacobian_vjp(smooth_map_ad, x) # type: ignore[arg-type]
j_num = central_diff_jacobian(smooth_map_np, x, eps=1e-6)
assert j_jvp.shape == (3, 5)
assert j_vjp.shape == (3, 5)
assert np.max(np.abs(j_jvp - j_exact)) < 1e-12
assert np.max(np.abs(j_vjp - j_exact)) < 1e-12
assert np.max(np.abs(j_jvp - j_num)) < 1e-8
assert np.max(np.abs(j_vjp - j_num)) < 1e-8
bench = {r.mode: r for r in benchmark_jvp_vs_vjp(n_in=64, m_out=4, repeats=3, seed=42)}
assert bench["jvp_forward"].n_sweeps == 64
assert bench["vjp_reverse"].n_sweeps == 4
assert bench["jvp_forward"].jacobian_max_error < 1e-10
assert bench["vjp_reverse"].jacobian_max_error < 1e-10
def test_pearlmutter_hvp_forward_over_reverse_and_grad_check() -> None:
"""Verify FoR HVP matches analytical H@v and central-diff gradient check step tradeoff (eps=1e-6 optimal)."""
rng = np.random.default_rng(17)
d = 8
W = rng.standard_normal((6, d)) * 0.4
b = rng.standard_normal(6) * 0.2
M = rng.standard_normal((d, d)) * 0.3
Q = M.T @ M + 0.5 * np.eye(d)
x = rng.standard_normal(d) * 0.5
v = rng.standard_normal(d)
def obj_ad(tx: ReverseTensor) -> ReverseTensor:
return (W @ tx + b).logsumexp() + 0.5 * (tx @ (Q @ tx))
def obj_np(z: np.ndarray) -> float:
logits = W @ z + b
m_val = float(np.max(logits))
lse = m_val + float(np.log(np.sum(np.exp(logits - m_val))))
return lse + 0.5 * float(z @ (Q @ z))
def grad_np(z: np.ndarray) -> np.ndarray:
logits = W @ z + b
shifted = logits - np.max(logits)
probs = np.exp(shifted) / np.sum(np.exp(shifted))
return W.T @ probs + Q @ z
logits0 = W @ x + b
probs0 = np.exp(logits0 - np.max(logits0))
probs0 /= np.sum(probs0)
wv = W @ v
hvp_exact = W.T @ (probs0 * wv - probs0 * float(np.dot(probs0, wv))) + Q @ v
grad_ad, hvp_ad = hvp_forward_over_reverse(obj_ad, x, v)
assert np.allclose(grad_ad, grad_np(x), atol=1e-12)
assert np.allclose(hvp_ad, hvp_exact, atol=1e-12)
eps_fd = 1e-6
hvp_fd = (grad_np(x + eps_fd * v) - grad_np(x - eps_fd * v)) / (2.0 * eps_fd)
assert np.allclose(hvp_ad, hvp_fd, atol=1e-8)
res_opt = central_diff_grad_check(obj_np, grad_np, x, eps=1e-6)
res_coarse = central_diff_grad_check(obj_np, grad_np, x, eps=1e-2)
res_tiny = central_diff_grad_check(obj_np, grad_np, x, eps=1e-13)
assert res_opt.passed is True
assert res_coarse.max_abs_error > res_opt.max_abs_error
assert res_tiny.max_abs_error > res_opt.max_abs_error
def test_dual_and_reverse_logsumexp_all_neginf_zero_grad() -> None:
"""Verify DualArray.logsumexp and ReverseTensor.logsumexp return -inf with zero grad when all inputs are -inf."""
d_all = DualArray(np.array([-np.inf, -np.inf, -np.inf]), np.array([1.0, -2.5, 3.0]))
lse_all = d_all.logsumexp()
assert float(lse_all.val) == -math.inf
assert float(lse_all.dot) == 0.0
# Mixed 2D rows: row 0 all -inf -> (-inf, 0.0); row 1 [-inf, 0.0] -> (0.0, dot[1,1])
d_mix = DualArray(
np.array([[-np.inf, -np.inf], [-np.inf, 0.0]]),
np.array([[1.5, -2.0], [3.0, 4.5]]),
)
lse_mix = d_mix.logsumexp(axis=1)
assert lse_mix.shape == (2,)
assert float(lse_mix.val[0]) == -math.inf
assert float(lse_mix.dot[0]) == 0.0
assert float(lse_mix.val[1]) == pytest.approx(0.0)
assert float(lse_mix.dot[1]) == pytest.approx(4.5)
r_all = ReverseTensor(np.array([-np.inf, -np.inf]))
r_out = r_all.logsumexp()
assert float(r_out.data) == -math.inf
r_out.backward()
assert r_all.grad is not None
assert np.all(r_all.grad == 0.0)
def test_change_of_variables_and_quadrature_vs_monte_carlo() -> None:
"""Verify triangular flow mass conservation, exact log|det J|, MC beating quadrature at d=10, and >=60% SAC cut."""
scale_log = np.array([0.2, -0.35, 0.25], dtype=np.float64)
shift = np.array([0.4, -0.2, 0.3], dtype=np.float64)
z_probe = np.array([0.5, -0.7, 0.9], dtype=np.float64)
_, _, log_det = triangular_flow_log_prob(z_probe, scale_log, shift)
j_num = central_diff_jacobian(
lambda z: triangular_flow_log_prob(z, scale_log, shift)[0],
z_probe,
eps=1e-6,
)
# Strictly lower-triangular Jacobian: upper triangle must vanish
assert np.allclose(np.triu(j_num, k=1), 0.0, atol=1e-8)
_, slog_num = np.linalg.slogdet(j_num)
assert log_det == pytest.approx(float(slog_num), abs=1e-8)
# Monte Carlo importance-sampling verification that integral of p_X(x) dx == 1.0
rng = np.random.default_rng(42)
d = 3
sigma_q = 2.0
n_mc = 20_000
x_samples = rng.normal(0.0, sigma_q, size=(n_mc, d))
weights = np.empty(n_mc, dtype=np.float64)
log_q_const = -0.5 * d * math.log(2.0 * math.pi * sigma_q * sigma_q)
for idx in range(n_mc):
x_pt = x_samples[idx]
z0 = (x_pt[0] - shift[0]) * math.exp(-scale_log[0])
z1 = (x_pt[1] - (shift[1] + 0.25 * math.sin(z0))) * math.exp(-scale_log[1] * math.tanh(z0))
z2 = (x_pt[2] - (shift[2] + 0.25 * math.sin(z1))) * math.exp(-scale_log[2] * math.tanh(z1))
z_inv = np.array([z0, z1, z2], dtype=np.float64)
x_rec, log_px, _ = triangular_flow_log_prob(z_inv, scale_log, shift)
assert np.allclose(x_rec, x_pt, atol=1e-12)
log_qx = log_q_const - 0.5 * float(np.sum(x_pt * x_pt)) / (sigma_q * sigma_q)
weights[idx] = math.exp(log_px - log_qx)
assert float(np.mean(weights)) == pytest.approx(1.0, abs=0.05)
comp_rows = compare_quadrature_vs_monte_carlo(dims=(2, 6, 10), budget_evals=4096, seed=42)
trap_d10 = next(r for r in comp_rows if r.dim == 10 and r.method == "trapezoidal_grid")
mc_d10 = next(r for r in comp_rows if r.dim == 10 and r.method == "monte_carlo")
assert mc_d10.abs_error < trap_d10.abs_error
ckpt = {c.strategy: c for c in simulate_checkpointing_memory(n_layers=64)}
full_bytes = ckpt["full_tape"].peak_activation_bytes
assert ckpt["uniform_sqrt"].peak_activation_bytes <= 0.40 * full_bytes
assert ckpt["selective_sac"].peak_activation_bytes <= 0.40 * full_bytes
assert ckpt["selective_sac"].extra_forward_flops_ratio < ckpt["uniform_sqrt"].extra_forward_flops_ratio
def test_simplex_projection_kkt_conditions_and_worked_example() -> None:
"""Verify exact Duchi simplex projection worked example and KKT satisfaction across 50 random vectors."""
y_worked = np.array([1.8, 1.1, 0.2, -0.4], dtype=np.float64)
p_star, nu_star, k_star = project_onto_simplex(y_worked)
assert np.allclose(p_star, np.array([0.85, 0.15, 0.0, 0.0]), atol=1e-12)
assert nu_star == pytest.approx(0.95, abs=1e-12)
assert k_star == 2
rng = np.random.default_rng(42)
for idx in range(50):
dim = int(rng.integers(2, 31))
vec = rng.standard_normal(dim) * (0.2 + 0.3 * (idx % 5)) + rng.uniform(-2.0, 2.0)
report = verify_simplex_kkt(vec)
assert report.kkt_satisfied is True
def test_convex_optimizers_rates_gd_nag_lbfgs_schedule_free() -> None:
"""Verify Nesterov beats GD, L-BFGS hits < 1e-10, and Schedule-Free hits < 1e-2 at step 120."""
arena = {
r.optimizer_name: r
for r in run_convex_optimizer_arena(kappa=100.0, dim=16, n_steps=120, seed=42)
}
assert arena["nesterov"].final_loss < arena["gd"].final_loss
assert arena["lbfgs"].final_loss < 1e-10
assert arena["schedule_free"].final_loss < 1e-2
def test_adamw_decoupled_decay_vs_coupled_l2() -> None:
"""Verify AdamW(decoupled=True) applies equal fractional weight decay across huge gradient anisotropy."""
w0 = np.array([1.0, 1.0], dtype=np.float64)
g_aniso = np.array([100.0, 0.01], dtype=np.float64)
# Single-step weight-decay isolation against zero-wd Adam
aw_dec_wd = AdamW(lr=0.1, weight_decay=0.5, decoupled=True).step(w0, g_aniso)
aw_dec_0 = AdamW(lr=0.1, weight_decay=0.0, decoupled=True).step(w0, g_aniso)
decay_delta_dec = aw_dec_0 - aw_dec_wd
assert np.allclose(decay_delta_dec, np.array([0.05, 0.05]), atol=1e-12)
aw_cpl_wd = AdamW(lr=0.1, weight_decay=0.5, decoupled=False).step(w0, g_aniso)
aw_cpl_0 = AdamW(lr=0.1, weight_decay=0.0, decoupled=False).step(w0, g_aniso)
decay_delta_cpl = aw_cpl_0 - aw_cpl_wd
# Coupled L2 gets attenuated by 1/sqrt(v_1) on the high-gradient coordinate
assert decay_delta_cpl[0] < 0.05 * decay_delta_cpl[1]
# Multi-step oscillating gradient confirming balanced vs. lopsided parameter shrinkage
opt_dec = AdamW(lr=0.1, weight_decay=0.5, decoupled=True)
opt_cpl = AdamW(lr=0.1, weight_decay=0.5, decoupled=False)
w_dec = w0.copy()
w_cpl = w0.copy()
for step_idx in range(20):
sign = 1.0 if step_idx % 2 == 0 else -1.0
w_dec = opt_dec.step(w_dec, sign * g_aniso)
w_cpl = opt_cpl.step(w_cpl, sign * g_aniso)
assert abs(float(w_dec[0]) - float(w_dec[1])) < 0.02
assert float(w_cpl[0]) > 2.0 * float(w_cpl[1])
def test_muon_newton_schulz5_bounds_and_moonlight_rms_invariance() -> None:
"""Verify NS5 singular contraction into [0.68, 1.14], Moonlight RMS invariance, Hybrid routing, and bf16 stall."""
# Unit-Frobenius test matrices whose normalized singular values span [0.01, 1.0]
for s_small in np.geomspace(0.01, 0.70, 12):
s_large = math.sqrt(max(0.0, 1.0 - float(s_small) ** 2))
mat = np.diag([s_large, float(s_small)])
out = zeropower_via_newtonschulz5(mat, steps=5)
s_out = np.linalg.svd(out, compute_uv=False)
assert np.all((s_out >= 0.68) & (s_out <= 1.14))
rng = np.random.default_rng(42)
u_m, _ = np.linalg.qr(rng.standard_normal((10, 6)), mode="reduced")
v_m, _ = np.linalg.qr(rng.standard_normal((6, 6)), mode="complete")
spec = np.array([0.99, 0.10, 0.06, 0.04, 0.025, 0.012], dtype=np.float64)
spec = spec / float(np.linalg.norm(spec))
g_rect = (u_m * spec) @ v_m.T
o_rect = zeropower_via_newtonschulz5(g_rect, steps=5)
s_rect = np.linalg.svd(o_rect, compute_uv=False)
assert np.all((s_rect >= 0.68) & (s_rect <= 1.14))
# Moonlight RMS invariance across aspect ratios
lr = 0.02
for shape in ((16, 128), (64, 64), (128, 16)):
muon = Muon(lr=lr, momentum=0.95, weight_decay=0.01, ns_steps=5, rms_match_adamw=True)
w = rng.standard_normal(shape) * 0.02
for _ in range(5):
g = rng.standard_normal(shape)
w, upd_rms = muon.step(w, g)
assert 0.12 * lr <= upd_rms <= 0.28 * lr
# Hybrid Muon + AdamW parameter routing
params = {
"embed_tokens": rng.standard_normal((32, 16)),
"lm_head": rng.standard_normal((32, 16)),
"layer0.attn_proj": rng.standard_normal((16, 16)),
"layer0.mlp_up": rng.standard_normal((32, 16)),
"layer0.rms_norm": np.ones(16, dtype=np.float64),
"layer0.bias": np.zeros(16, dtype=np.float64),
}
grads = {k: rng.standard_normal(v.shape) * 0.01 for k, v in params.items()}
hybrid = HybridMuonAdamW(params)
assert hybrid.routing["layer0.attn_proj"] == "muon"
assert hybrid.routing["layer0.mlp_up"] == "muon"
assert hybrid.routing["embed_tokens"] == "adamw"
assert hybrid.routing["lm_head"] == "adamw"
assert hybrid.routing["layer0.rms_norm"] == "adamw"
assert hybrid.routing["layer0.bias"] == "adamw"
updated = hybrid.step(params, grads)
assert all(np.all(np.isfinite(val)) for val in updated.values())
# bf16 stagnation vs fp32 master accumulation
bf16_report = verify_bf16_stagnation_vs_fp32_master(
weight_mag=1.0, grad_mag=1e-3, lr=1e-2, n_steps=200
)
assert bf16_report["stagnated_in_bf16"] is True
assert bf16_report["total_change_bf16"] == 0.0
assert bf16_report["total_change_fp32_master"] > 1e-3
def test_cli_demo_script_and_workbench_panels_json(tmp_path: Path) -> None:
"""Execute CLI demo, verify 4 stdout blocks & workbench_panels schema, and Security-Only AST Deserialization Ban."""
script_path = LAB_ROOT / "scripts" / "run_lab_demo.py"
json_path = tmp_path / "ch02_workbench_results.json"
proc = subprocess.run(
[sys.executable, str(script_path), "--json-out", str(json_path), "--seed", "42"],
cwd=str(LAB_ROOT),
capture_output=True,
text=True,
check=False,
)
assert proc.returncode == 0, f"CLI failed:\nSTDOUT:\n{proc.stdout}\nSTDERR:\n{proc.stderr}"
for header in (
"[1] Subspaces, Eckart-Young, rSVD, Low-Rank Adapters & Conditioning",
"[2] Autodiff JVP/VJP, Pearlmutter HVP, Flows & Monte Carlo vs. Quadrature",
"[3] Convex & SOTA Optimizers (KKT Simplex, GD/NAG/L-BFGS, AdamW, Muon/Moonlight)",
"[4] Numerical Guardrails Summary (slogdet, Ledoit-Wolf, bf16 Master Rescue)",
):
assert header in proc.stdout
assert json_path.exists()
payload = json.loads(json_path.read_text(encoding="utf-8"))
for key in ("config", "workbench_panels", "svd_and_lowrank", "calculus_and_autodiff", "optimizers"):
assert key in payload
panels = payload["workbench_panels"]
assert len(panels["kpis"]) == 6
assert {k["id"] for k in panels["kpis"]} == {
"kpi_normal_eq_vs_qr",
"kpi_rsvd_q2_error",
"kpi_hvp_precision",
"kpi_simplex_kkt",
"kpi_muon_ns5_band",
"kpi_bf16_rescue",
}
for kpi in panels["kpis"]:
assert kpi["status"] in {"ok", "warn", "critical"}
assert len(panels["bars"]) == 4
assert {b["id"] for b in panels["bars"]} == {
"bar_conditioning_rel_error",
"bar_jvp_vs_vjp_sweeps",
"bar_quadrature_vs_mc_error",
"bar_optimizer_final_loss",
}
for bar in panels["bars"]:
assert len(bar["items"]) >= 2
for item in bar["items"]:
assert isinstance(item["value"], (int, float))
assert math.isfinite(float(item["value"]))
assert item["css_class"] in {"is-fast", "is-mid", "is-slow"}
assert len(panels["tables"]) == 4
assert {t["id"] for t in panels["tables"]} == {
"table_eckart_young_rsvd",
"table_lora_dora_pissa",
"table_convex_optimizers",
"table_muon_moonlight_spectrum",
}
# Security-Only AST Deserialization Ban across src/, scripts/, and tests/
# (Reference Core zero-scipy/sklearn/torch parity is documented separately as informational.)
forbidden_unsafe_imports = {
"pickle",
"_pickle",
"cPickle",
"joblib",
"cloudpickle",
"dill",
"shelve",
"marshal",
}
for folder in ("src", "scripts", "tests"):
for py_file in (LAB_ROOT / folder).rglob("*.py"):
tree = ast.parse(py_file.read_text(encoding="utf-8"), filename=str(py_file))
for node in ast.walk(tree):
if isinstance(node, ast.Import):
for alias in node.names:
top_pkg = alias.name.split(".")[0]
assert top_pkg not in forbidden_unsafe_imports, (
f"Forbidden unsafe import {top_pkg} in {py_file}"
)
elif isinstance(node, ast.ImportFrom) and node.module:
top_pkg = node.module.split(".")[0]
assert top_pkg not in forbidden_unsafe_imports, (
f"Forbidden unsafe from-import {top_pkg} in {py_file}"
)
float64 (khoảng 16 chữ số thập phân chính xác), ma trận thiết kế \(\mathbf{X}\) có chỉ số điều kiện \(\kappa_2(\mathbf{X}) = 10^8\). Điều gì xảy ra khi giải hồi quy tuyến tính bằng phương trình chuẩn tắc inv(X.T @ X) @ X.T @ y thay vì Householder QR / SVD lstsq?float64 (solve có thể văng LinAlgError), trong khi QR/SVD trực giao tránh tạo \(\mathbf{X}^\top\mathbf{X}\).
VJP) thay vì Forward-Mode (JVP) để tính trọn vector gradient \(\nabla_{\boldsymbol{\theta}}\mathcal{L}\)?JVP (mỗi lượt tính một cột) và \(O(m)\) lượt VJP (mỗi lượt tính một hàng). Vì loss có \(m = 1\), VJP thu trọn toàn bộ gradient chỉ trong 1 lần truyền ngược.
NAG) tỷ lệ nghịch theo tham số nào?coupled L2) bị xem là anti-pattern so với AdamW?AdamW tách rời bước co trực tiếp \((1 - \eta\lambda)\mathbf{w}_t\) độc lập với phương sai gradient.
Moonlight (Muon + AdamW), nhận định nào sau đây ĐÚNG về lý thuyết và triển khai thực tế của Muon?[0.68, 1.14], nhưng bắt buộc nhân chuẩn hóa RMS 0.2*sqrt(max(d_out, d_in)) + weight decay tách rời và chỉ gán cho ma trận 2D ẩn (1D/embedding/head vẫn dùng AdamW).
p_i* > 0) không chạm biên âm nên nhân tử bất đẳng thức \(\lambda_i^* = 0\), cho \(p_i^* = y_i - \nu^*\). Biến bị khóa tại biên 0 thỏa \(\nu^* - y_i = \lambda_i^* \ge 0\), dẫn tới thuật toán mực nước \(O(n\log n)\).
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 Eckart–Young–Mirsky & Kiểm định SVD Ma trận 3x2 20%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Với chuẩn Phổ, dùng chiều của không gian hạch (null space) \(\mathcal{N}(\mathbf{B})\) (có số chiều \(\ge n - k\)) giao với không gian con trực giao \(\operatorname{span}\{\mathbf{v}_1,\dots,\mathbf{v}_{k+1}\}\) (chiều \(k+1\)) bằng Định lý Grassmann.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Với chuẩn Frobenius, áp dụng bất đẳng thức giá trị kỳ dị Weyl (hoặc Mirsky): \(\sigma_{i+j-1}(\mathbf{A}) \le \sigma_i(\mathbf{A}-\mathbf{B}) + \sigma_j(\mathbf{B})\) đặt \(j = k+1\) khi \(\operatorname{rank}(\mathbf{B}) \le k\) nên \(\sigma_{k+1}(\mathbf{B}) = 0\).
Tiêu chí Đáp án & Số đối chứng
Với \(\mathbf{A} = [[3,2],[2,3],[2,-2]]\), \(\mathbf{A}^\top\mathbf{A} = [[17, 8],[8, 17]]\) cho trị riêng 25 và 9, nên \(\sigma_1 = 5.0, \sigma_2 = 3.0\). Sai số tối ưu hạng-1 bằng đúng \(\sigma_2 = 3.0\) trên cả chuẩn Phổ và Frobenius.
Bài tập 2 — Chứng minh Đạo hàm Log-Det Jacobi & Đổi biến Normalizing Flow 20%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Vi phân định thức qua khai triển phần bù đại số (cofactor matrix): \(d(\det\mathbf{X}) = \operatorname{tr}(\operatorname{adj}(\mathbf{X})\,d\mathbf{X}) = \det(\mathbf{X})\operatorname{tr}(\mathbf{X}^{-1}\,d\mathbf{X})\).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chia cả hai vế cho \(\det\mathbf{X}\) (khi \(\det\mathbf{X} > 0\)) để thu \(d(\ln\det\mathbf{X}) = \operatorname{tr}(\mathbf{X}^{-1}\,d\mathbf{X})\), sau đó đồng nhất với dạng vi phân chính tắc \(df = \operatorname{tr}((\nabla_{\mathbf{X}}f)^\top d\mathbf{X})\).
Tiêu chí Đáp án & Số đối chứng
Thu được \(\nabla_{\mathbf{X}}\ln\det\mathbf{X} = (\mathbf{X}^{-1})^\top = \mathbf{X}^{-\top}\) (và với ma trận đối xứng SPD chỉ là \(\mathbf{X}^{-1}\)). Trong Planar/Triangular Flow, định thức Jacobian tam giác tính trong \(O(d)\) thay vì \(O(d^3)\).
Bài tập 3 — Suy diễn KKT Phép chiếu Đơn hình & Thuật toán Mực nước O(n log n) 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Viết hàm Lagrange: \(\mathcal{L}(\mathbf{p}, \nu, \boldsymbol{\lambda}) = \frac{1}{2}\|\mathbf{p} - \mathbf{y}\|_2^2 + \nu(\mathbf{1}^\top\mathbf{p} - 1) - \boldsymbol{\lambda}^\top\mathbf{p}\) với \(\boldsymbol{\lambda} \ge \mathbf{0}\).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Giải điều kiện dừng \(p_i - y_i + \nu - \lambda_i = 0\) kết hợp bổ đề bù trừ tĩnh \(\lambda_i p_i = 0\) và \(p_i \ge 0\) để suy ra \(p_i^* = \max(y_i - \nu^*, 0)\).
Tiêu chí Đáp án & Số đối chứng
Với \(\mathbf{y} = [1.8, 1.1, 0.2, -0.4]\), sắp giảm \(u = [1.8, 1.1, 0.2, -0.4]\): ở \(j=2\), \((1.8+1.1-1)/2 = 0.95 < 1.1\), còn ở \(j=3\), \((1.8+1.1+0.2-1)/3 = 0.7 > 0.2\). Suy ra \(k^* = 2\), \(\nu^* = 0.95\), \(\mathbf{p}^* = [0.85, 0.15, 0.0, 0.0]\).
Bài tập 4 — Gỡ lỗi 3 Lỗi Số học Kinh điển (Normal Eq, det() Tràn số & Bước Sai phân) 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Kiểm tra nguyên nhân mất chữ số khi tạo \(\mathbf{X}^\top\mathbf{X}\) ở \(\kappa=10^8\) (2*log10(kappa) = 16 chữ số trong FP64).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Tại \(d=400\) với giá trị riêng 0.15, \(\det = 0.15^{400} \approx 10^{-330}\) dưới chuẩn tối thiểu của float64 (4.94e-324). Trong sai phân hữu hạn, sai số tổng là \(O(\epsilon^2) + O(\varepsilon_{\text{mach}}/\epsilon)\).
Tiêu chí Đáp án & Số đối chứng
Dùng np.linalg.lstsq(X, y, rcond=None) (SVD/QR); dùng safe_logdet_cholesky (2*sum(log(diag(L)))) hoặc np.linalg.slogdet; chọn bước sai phân trung tâm tối ưu \(\epsilon^* \approx \varepsilon_{\text{mach}}^{1/3} \approx 6\times 10^{-6}\) (1e-6).
Bài tập 5 — Thiết kế Cấu trúc Phục vụ & Tinh chỉnh Tối ưu cho Mô hình 16B MoE + MLA + Multi-LoRA 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Kết hợp MLA (nén KV latent + tách RoPE + hấp thụ ma trận W^{UK} vào W^{UQ}) cho suy luận, Muon+AdamW (với hệ số RMS 0.2*sqrt(max(d_out, d_in)) và phân loại tensor) cho tiền huấn luyện, và S-LoRA/BGMV cho đa khách hàng.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chú ý bẫy tích lũy FP8 14-bit trên NVIDIA Hopper TensorCore khiến tích vô hướng dài K>128 bị nhiễu nếu không nâng thanh ghi về fp32 định kỳ.
Tiêu chí Đáp án & Số đối chứng
Bản thiết kế hoàn chỉnh chứng minh: MLA giảm >90% KV cache nhờ tính kết hợp ma trận; PiSSA/DoRA khai thác top-r SVD & tách hướng–độ lớn; Muon giữ ổn định phổ ở 2D hidden weights còn embeddings/head/1D giữ AdamW; DeepGEMM FP8 promote về FP32 mỗi N_C=128.
Bài tập 6 — Chẩn đoán Sụp đổ Đòn bẩy Danh mục & Sai số Whitening Phổ 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Dùng phân bố Marchenko–Pastur: với \(c = p_{\text{assets}}/n_{\text{bars}} = 450/500 = 0.9\), cận dưới \(\lambda_- = \sigma^2(1 - \sqrt{0.9})^2 \approx 0.0026\sigma^2\) dù mọi tài sản hoàn toàn độc lập.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Phép trắng hoàn toàn (full whitening) chia trục theo \(1/\sqrt{\lambda_i}\), khuếch đại các chiều nhiễu đuôi lên hàng trăm lần.
Tiêu chí Đáp án & Số đối chứng
Dùng Ledoit–Wolf shrinkage kéo sàn trị riêng lên để kiểm soát \(\kappa(\hat{\boldsymbol{\Sigma}}_{\text{LW}})\) và hạ đòn bẩy danh mục GMV; trong truy xuất embedding, chuyển sang Truncated Whitening (chỉ giữ k=256 chiều đầu) hoặc cộng chính quy hóa \(\boldsymbol{\Lambda} + \epsilon\mathbf{I}\).