Chương 14 — Mạng Nơ-ron Sâu, Tự động Vi phân, Động lực Học tập & Nội tại PyTorch 2.x
Từ UAT vs Telgarsky (32 đoạn), L=20 Kaiming/Pre-Norm (1.59x) & SwiGLU (d_ff=11,008) vs BatchNorm B=2 (+-1) đến TapeTensor (9.71e-17), Adam lỗi L2 (2.97x) vs AdamW/Muon NS_5, Early Stopping rollback, fp16/bf16 16*Psi (112 GB) & TorchDynamo/Roofline (71.4% HBM cut).
Đơn vị học phần (
Unit ID):T1-P3-U01(Phần 3: Nền tảng Học sâu, Thị giác Máy tính Hiện đại & Nhận thức Đa phương thức — Mục lục Phần 3)
Phòng thí nghiệm Thực hành (Workbench): WB-Ch14 — Mạng Nơ-ron, Tự động Vi phân, Tối ưu hóa & Nội tạiPyTorch 2.x(nn_pytorch_lab)
Truy xuất nguồn & kế thừa: Chương 02 (Giải tích Ma trận Bố cục Tử số,JVP/VJP,SAC,AdamW&Muon), Chương 03 (Cross-Entropy & Hiệu chuẩn), Chương 13, và Chương trình gốc DSAI (R41). Chương tiếp theo trong lộ trình làChương 15.
Bốn Ca Thất bại Thực chiến Mở màn: Vì sao Mạng Nơ-ron Sụp đổ Âm thầm Trong Sản xuất?#
Phần lớn sự cố sụp đổ của hệ thống Học sâu (Deep Learning — DL) ngoài thực tế không phát sinh từ lỗi cú pháp Python, mà từ việc vi phạm những bất biến toán học về truyền phương sai, độ chính xác dấu chấm động hữu hạn, quản trị bộ nhớ tensor và trình biên dịch đồ thị. Bốn thảm họa điển hình dưới đây được kiểm chứng trực tiếp bằng thực nghiệm lặp lại trong WB-Ch14 (nn_pytorch_lab):
-
Tắt dần \((1/2)^L\) do Khởi tạo Sai & Lượng tử hóa Nhị phân \(\pm 1\) của
BatchNormtạiB=2(WB-Ch14,Tests 04, 06):Khi huấn luyện một mạng truyền thẳng
ReLUsâu \(L = 20\) tầng bằng khởi tạoXavier(vốn thiết kế cho hàm tuyến tính/tanhchứ không bù hệ số cắt âm1/2củaReLU), phương sai kích hoạt tại tầng cuối sụp xuống1.02e-06(naive_smalltụt còn1.49e-38, còn nhánh thặng dư không chia tỷ lệ nổ7.86e+11); ngược lại,Kaiming / Hegiữ nguyên1.07xvàPre-Normchia tỷ lệ \(1/\sqrt{2L}\) ổn định ở1.59xvới chuẩn gradient tầng đầu1.25. Nguy hiểm tương đương, trong huấn luyện đa GPU lô nhỏ \(B = 2\) hoặc API suy luận quên gọimodel.eval():BatchNorm1dnémValueErrortạiB = 1, ép mọi kênh đầu ra tạiB = 2thành hai giá trị nhị phân \(\pm 1\) (độ lệch khỏi \(\pm 1\) chỉ2.38e-07, thiên lệch phương sai mẫu0.509) và làm trôirunning_mean1.213khi quêneval(), trong khiLayerNormvàRMSNormgiữ sai khácB = 1so vớiB = 32bằng0.0. -
Thảm họa Dữ liệu Tràn Số
fp16(OPT-175B), Đóng băng ULPbf16& Bức tường Bộ nhớ \(16\Psi\) (WB-Ch14,Tests 12, 13, 14):Định dạng
fp16(E5M10) chỉ có đỉnh biểu diễn65,504và ngưỡng chuẩn dưới6.10e-5: trong kiểm toánWB-Ch14, giá trị1e-8bị xóa sạch về0.0và70000.0tràn ngay thànhinf(nguyên nhân khiến nhật ký huấn luyệnOPT-175Bcủa Meta phải khởi động lại thủ công hơn35lần). Chuyển sangbf16(E8M7) bảo toàn dải sốfp32nhưng chỉ có7bit phần trị (\(\varepsilon_{\text{mach}} = 2^{-7}\)): cập nhật trực tiếp-1e-4qua100bước trên trọng sốbf16thuần cho tổng biến thiên0.0(đóng băng hoàn toàn) nếu thiếu bản sao trọng số chủfp32(-0.0100). Ở quy mô7Btham số, bộ nhớ tĩnhAdamWchiếm đúng \(16\Psi = 112.0\text{ GB}\) (14w16 +14g16 +28master32 +28m +28v) trước cả khi cấp phát tensor kích hoạt; dùng Gradient Checkpointing \(\sqrt{L}\) tạiL = 64cắt75.0%bộ nhớ kích hoạt với đúng+33.33%FLOP (SACchọn lọc chỉ tốn+4.0%FLOP). -
Lỗi \(L_2\) Ghép cặp của
Adam(2.97xLệch Co ngót) & Triển khai Sai Trọng số Dừng sớm (WB-Ch14,Tests 07, 09, 11):Truyền
weight_decayvàotorch.optim.Adamkhiến \(\lambda \mathbf{w}\) bị chia cho \(\sqrt{\hat{\mathbf{v}}_t}\): trong bài kiểm thử hai tọa độ có gradient \((100, 0.01)\),Adamlàm lệch tỷ số trọng số tới2.97x(1.962vs0.660) và trên mạngPre-Norm SwiGLUthật làm trôi chuẩnRMSNorm0.988, kéo độ chính xác tụt xuống44.7%(val_loss = 1.194). Tách nhóm tham số (weight_decay = 0.0cho 1D norm/bias) vớiAdamWđưa sai lệch hai tọa độ về3.02e-08(val_acc = 91.2%) vàHybridMuonAdamW(NS_5nén phổ[0.01, 1.0]vào[0.682, 1.134]) đạt88.3%. Đồng thời, dừng sớm vớipatience=0kết thúc non tại epoch2(1.694), còn bỏ quên khôi phụcbest_state_dictsaupatience=5(dừng tại epoch12với1.659) làm mất mốc cực tiểu epoch7(1.624) và đẩytest_lossxấu đi từ1.616lên1.707. -
Bẫy Copy Ngầm
.reshape(), Đột biến_version& Điểm Ngắt Đồ thịTorchDynamo(WB-Ch14,Tests 14, 15):Trong
PyTorch 2.x,x.t()chỉ đảostridethành[1, 64](\(O(1)\), không sao chép): gọix.t().view(-1)văngRuntimeError, nên lập trình viên thay bằng.reshape(-1)mà không biết nó âm thầm cấp phát vùng nhớ mới (đứt liên kếtuntyped_storage().data_ptr()). Ghi tại chỗ lên lát cắth[:, :2] = 0làm tăng_version(0 -> 1) khiến.backward()đổ vỡ. Tệ hơn, chèn.item()hay nhánhifphụ thuộc dữ liệu trongforward()kích hoạt1graph break trênTorchDynamo(so với0break ở mô hình sạch vớicompile_max_abs_diff = 0.0), phá hủy dung hợpTorchInductorvốn giúp cắt57.14%băng thông HBM choBias+GELU+Res(0.86 -> 2.00 FLOP/B) và71.43%choRMSNorm(0.36 -> 1.25 FLOP/B) dưới trần RooflineH100\(I^* = 295.2\text{ FLOP/B}\).
Mục tiêu Học tập (Learning Objectives)#
Sau khi hoàn tất Chương 14 và vượt qua trọn vẹn 16/16 kiểm thử của WB-Ch14 (nn_pytorch_lab), học viên đạt chuẩn năng lực thạc sĩ chuyên sâu (UCL MSc Distinction) về các trụ cột sau:
- Chứng minh Biểu diễn Sâu & Hình học Kích hoạt (
UATvsTelgarsky&SwiGLU): Trình bày khung chứng minhCybenko/Hornik/Leshno, tự tay quy nạp Định lý Tách sâu hàm mũ củaTelgarsky (2016)(\(2^k\) đoạn affine bằng \(\mathcal{O}(k)\) lớp rộng3vs cận dưới \(\Omega(2^k)\) bề rộng ở độ sâu2), và dẫn xuất hệ số cân bằng tham số/FLOP \(d_{\text{ff}} = \frac{8}{3}d\) choSwiGLU. - Làm chủ Lý thuyết Khởi tạo, Tỷ lệ Thặng dư & Chuẩn hóa: Chứng minh hệ số phương sai
1/2củaReLUđể phân táchXavier(\(\frac{2}{n_{\text{in}}+n_{\text{out}}}\)) vớiKaiming(\(\frac{2}{n_{\text{in}}}\)), chứng minh bất biến \(\mathbb{E}[\lVert \mathbf{J}_{\mathbf{x}_{2L}}\mathbf{v}_0 \rVert_2^2] \le e^{\nu^2}\) dưới tỷ lệ \(1/\sqrt{2L}\) ở \(L \ge 20+\), và chứng minh sụp đổ lượng tử hóa \(\pm 1\) củaBatchNormtại \(B=2\) đối lập với bất biến tỷ lệ củaLayerNorm/RMSNorm. - Xây dựng Động cơ Autodiff Ngược & Quản trị Bộ nhớ Checkpointing \(O(\sqrt{L})\): Phân biệt
JVPvsVJPtheo Bố cục Tử số (ch-02), cài đặt đồ thị tính toánTapeTensor(MatMul,RMSNorm,SwiGLU,LSE CrossEntropy) kiểm định bằng sai phân trung tâmfloat64(< 1e-6), và giải bài toán cực tiểu hóa bộ nhớ kích hoạt \(M(k) = m_{\text{act}}(k + L/k)\) để suy ra \(k^* = \sqrt{L}\) cùng chi phí+33.33%FLOP và bảng ngân sách16\Psibytes củaAdamW. - Giải phẫu Nội tại
PyTorch 2.x, Biên dịchtorch.compile, Độ chính xác Hỗn hợp & Mô hình Roofline: Phân tích cấu trúcuntyped_storage/stride/view/reshape, cơ chế_versionvàtorch.inference_mode(); nắm vững chuỗiTorchDynamo (PEP 523) -> AOTAutograd Min-Cut -> TorchInductor; phân biệtfp16(E5M10),bf16(E8M7+fp32master) vàfp8(E4M3/E5M2+ tỷ lệ khối1x128/128x128); và tính cường độ số học \(I\) so với điểm gãy \(I^*\) cùng lượng byte HBM tiết kiệm nhờ dung hợp nhân. - Làm chủ Tối ưu hóa (
AdamW,Muon NS_5), Điều chuẩn & Dừng sớm Chống Lỗi: Chứng minh lỗi ghép \(L_2\) củaAdam(\(1/\sqrt{\hat{v}_t}\)), tách nhóm tham số2D/1D, vận dụngMuon(NS_5+Moonlight\(0.2\sqrt{\max(d_{\text{out}}, d_{\text{in}})}\)) đúng phạm vi ma trận2Dẩn, kết hợpWarmup + Cosine,Inverted Dropout,Label Smoothing,MixUp/CutMixvà khôi phụcbest_state_dicttrongEarly Stopping.
Truy xuất Nguồn & Bảng Ký hiệu Phi Mơ hồ (R41 Traceability & Notation)#
Thành phần Giáo trình Gốc (R41) |
Nâng cấp Chuẩn SOTA 2026 (ch-14) |
Mục trong Chương 14 | Sơ đồ / Widget | Mô-đun & Kiểm thử (nn_pytorch_lab) |
|---|---|---|---|---|
| 1. Intro to DL & Applications | Lời nguyền chiều \(\Omega(\epsilon^{-d/s})\) vs đa tạp hợp thành; UAT (Cybenko/Hornik/Leshno) vs Tách sâu Telgarsky (2016) (\(\phi_k\) \(2^k\) đoạn vs độ sâu 2) |
Trụ cột 1 (§1.1–§1.2) | Widget 1 (Chế độ B) |
autograd_core.py: telgarsky_triangle_wave, benchmark_telgarsky_depth_separation (Test 05) |
| 2. FFNN | Khối tuyến tính & đa diện lồi; lan truyền phương sai xuôi/ngược; Xavier vs Kaiming; Pre-Norm \(1/\sqrt{2L}\); BatchNorm (\(B=2\), eval()) vs LayerNorm vs RMSNorm |
Trụ cột 1 (§1.3–§1.5) + Trụ cột 2 (§2.5) | Mermaid 1 + Widget 1 (Chế độ A & B) |
autograd_core.py: benchmark_deep_init_propagation; pytorch_training_lab.py: audit_batchnorm_collapse_and_eval_mode (Tests 04, 06) |
| 3. Activation Functions | Sigmoid, Tanh, ReLU (dying ReLU, \(\frac{1}{2}\sigma_z^2\)), GELU, SiLU, SwiGLU (cân bằng chính xác \(d_{\text{ff}} = \frac{8}{3}d\), căn 256 11,008) & GeGLU |
Trụ cột 1 (§1.4) + Trụ cột 2 (§2.4) | Mermaid 1 + Widget 1 |
autograd_core.py: TapeTensor, audit_swiglu_param_flop_parity (Tests 02, 03, 05) |
| 4. Backpropagation | VJP vs JVP, Baur–Strassen (\(\le 3\times\)), Checkpointing \(O(\sqrt{L})\) (+33.3%), PyTorch 2.x (stride/view/_version/inference_mode()), torch.compile (Dynamo/AOT/Inductor) & Roofline |
Trụ cột 1 (§1.6) + Trụ cột 2 (§2.1–§2.4) | Mermaid 2 + Widget 3 |
autograd_core.py: TapeTensor, central_diff_grad_check, simulate_checkpointing_tradeoff, compute_roofline_and_fusion_savings; pytorch_training_lab.py (Tests 02, 03, 13, 14, 15) |
| 5. Loss & Optimizers | LSE CrossEntropy; 16*Psi, fp16 vs bf16 ULP vs fp8; SGD+Momentum; Adam lỗi \(L_2\) vs AdamW; Warmup+Cosine; Muon (NS_5 + Moonlight) & QK-Norm |
Trụ cột 1 (§1.7) + Trụ cột 2 (§2.3, §2.5) | Mermaid 3 + Widget 2 + Widget 3 |
autograd_core.py: log_sum_exp_cross_entropy, audit_adam_coupled_vs_adamw_decoupled, zeropower_via_newtonschulz5; pytorch_training_lab.py (Tests 07, 08, 09, 12) |
| 6. Regularization Techniques | Inverted Dropout (\(1/(1-p)\)), Decoupled Weight Decay (chỉ 2D), Label Smoothing (biên logit hữu hạn), MixUp & CutMix |
Trụ cột 1 (§1.8) + Trụ cột 2 (§2.5) | Mermaid 3 + Widget 2 (Chế độ B) |
pytorch_training_lab.py: audit_regularization_techniques (Tests 09, 10) |
| 7. When Training Should Stop | Tương đương phổ \(\lambda_{\text{eff}} \propto 1/t\); Máy trạng thái Prechelt (patience, min_delta, khôi phục best_state_dict); 6 Cổng Canary CI/CD |
Trụ cột 1 (§1.9) + Trụ cột 2 (§2.5) | Mermaid 3 + Widget 2 (Chế độ B) |
autograd_core.py: EarlyStoppingConfig; pytorch_training_lab.py: run_early_stopping_restoration_bench (Tests 11, 16) |
Bảng Ký hiệu Toán học Phi Mơ hồ (ch-02, ch-03 & ch-14)#
| Ký hiệu LaTeX | Miền / Hình dạng | Định nghĩa Chuẩn trong Chương 14 | Quy tắc Phân tách Liên chương | Định danh nn_pytorch_lab |
|---|---|---|---|---|
| \(\mathbf{h}^{(l)}, \mathbf{z}^{(l)} \in \mathbb{R}^{d_l}\) | Vector cột | Trạng thái sau & trước kích hoạt tầng \(l\) (\(\mathbf{h}^{(0)} = \mathbf{x}\)) | Dữ liệu lô PyTorch hàng viết \(\mathbf{X}, \mathbf{H}^{(l)} \in \mathbb{R}^{B \times d_l}\) | h, z, x_batch |
| \(\mathbf{W}^{(l)} \in \mathbb{R}^{d_l \times d_{l-1}}\) | Ma trận trọng số | Ánh xạ cột \(\mathbf{z}^{(l)} = \mathbf{W}^{(l)}\mathbf{h}^{(l-1)} + \mathbf{b}^{(l)}\) | PyTorch nn.Linear tính \(\mathbf{X}\mathbf{W}^\top + \mathbf{1}\mathbf{b}^\top\) (\(\mathbf{W} \in \mathbb{R}^{d_{\text{out}} \times d_{\text{in}}}\)) |
W, weight |
| \(L, d, B, S\) | \(\mathbb{N}_{>0}\) | Độ sâu \(L\) (\(2L\) nhánh con Transformer), bề rộng \(d\), lô \(B\), độ dài chuỗi \(S\) | Tách biệt Lipschitz \(L\) (ch-02), lead time \(L\) (ch-13) và bước tensor \(\mathbf{s}_{\text{stride}}\) |
depth, width, batch_size, seq_len |
| \(n_{\text{in}}, n_{\text{out}}, d_{\text{ff}}\) | \(\mathbb{N}_{>0}\) | Fan-in (\(d_{l-1}\)), fan-out (\(d_l\)), bề rộng ẩn FFN (SwiGLU: \(\frac{8}{3}d\)) |
Khớp fan_in / fan_out của PyTorch init |
fan_in, fan_out, d_ff |
| \(\Psi\) | \(\mathbb{N}_{>0}\) | Tổng số tham số huấn luyện (\(\boldsymbol{\theta} \in \mathbb{R}^\Psi\)) | Quyết định bộ nhớ tĩnh \(16\Psi\); tách biệt xác suất Dropout \(p\) | num_params |
| \(\mathbf{J}_{\mathbf{f}}(\mathbf{x}) \in \mathbb{R}^{m \times n}\) | Jacobian | Bố cục Tử số (ch-02): \([\mathbf{J}_{\mathbf{f}}]_{ij} = \partial f_i / \partial x_j\) |
Gradient ma trận bảo toàn hình dạng \(\nabla_{\mathbf{W}}\mathcal{L} \in \mathbb{R}^{d_{\text{out}} \times d_{\text{in}}}\) | jacobian, grad |
| \(\phi(\cdot), \sigma(\cdot), \Phi(\cdot)\) | \(\mathbb{R} \to \mathbb{R}\) | Hàm kích hoạt \(\phi\), logistic \(\sigma(z)=(1+e^{-z})^{-1}\), CDF chuẩn \(\Phi(z)\) | Giá trị kỳ dị viết \(\sigma_i(\cdot)\); phương sai viết \(\sigma_w^2, \sigma_B^2, \sigma_b^2\) | activation, sigmoid, norm_cdf |
| \(\phi_\triangle, \phi_k, \phi_{\text{NS}}\) | Ánh xạ 1D | Sóng tam giác Telgarsky, hợp \(k\) lần (\(2^k\) đoạn), đa thức NS_5 bậc 5 |
Không dùng chung ký hiệu \(\phi\) trơn cho ba hàm này | telgarsky_triangle_wave |
| \(\varepsilon, \epsilon_{\text{ls}}, \varepsilon_{\text{mach}}\) | \(\mathbb{R}_{>0}, [0,1)\) | Hằng ổn định mẫu số, làm mượt nhãn (Label Smoothing), sai số làm tròn máy | bf16 \(\varepsilon_{\text{mach}}=2^{-7}\); fp16 \(2^{-10}\); fp32 \(2^{-23}\) |
eps, label_smoothing, ulp |
| \(\lambda, \lambda_{\text{mix}}, \lambda_{\text{eff}}\) | \(\mathbb{R}_{\ge 0}, [0,1]\) | Hệ số Weight Decay, hệ số nội suy MixUp/CutMix, ridge dừng sớm \(\propto 1/t\) |
Không dùng \(\lambda\) trần cho cả hai khái niệm cùng lúc | weight_decay, lam_mix |
| \(\eta_t, \mu_{\text{mom}}, \beta_1, \beta_2, m_{\text{bn}}\) | \(\mathbb{R}_{>0}, [0,1)\) | Tốc độ học bước \(t\), động lượng SGD/Muon, phân rã Adam, động lượng EMA BN |
Dự trữ \(\gamma\) cho hệ số co giãn của LayerNorm/RMSNorm |
lr, momentum, beta1, beta2, bn_momentum |
| \(I, I^*\) | \(\mathbb{R}_{>0}\) | Cường độ số học \(\frac{\text{FLOPs}}{\text{Bytes}}\) & điểm gãy phần cứng \(\frac{P_{\text{peak}}}{B_{\text{mem}}}\) | Thống nhất với ch-02 (\(\text{AI}, I^*\)); tách biệt MI \(I(X;Y)\) (ch-03) |
arithmetic_intensity, ridge_point |
| \(\operatorname{NS}_5, \text{scale}_{\text{RMS}}\) | Hệ số Muon |
\((3.4445, -4.7750, 2.0315)\); hệ số khớp Moonlight \(0.2\sqrt{\max(d_{\text{out}}, d_{\text{in}})}\) |
Khớp ch-02 & torch.optim.Muon(adjust_lr_fn="match_rms_adamw") |
NS5_COEFFS, moonlight_rms_scale |
Trụ cột 1 — Nền tảng Lý thuyết, Hình học Khởi tạo, Chuẩn hóa & Động lực Tối ưu hóa#
1.1 Phạm vi Ứng dụng Học sâu & Tính Hợp thành Đa tạp#
Các bộ ước lượng phi tham số cổ điển (hạt nhân, k-NN, spline địa phương) vấp phải lời nguyền số chiều (curse of dimensionality): để xấp xỉ một hàm trơn bậc \(s\) tùy ý \(f \in W^{s,\infty}([0,1]^d)\) tới sai số cực đại \(\epsilon\), độ phức tạp mẫu và tham số tăng theo \(\Omega(\epsilon^{-d/s})\). Mạng nơ-ron sâu vượt qua giới hạn xấu nhất này trên dữ liệu thực tế không phải bằng phép màu, mà vì tín hiệu tự nhiên mang cấu trúc phân cấp hợp thành \(f(\mathbf{x}) = h_L \circ \dots \circ h_1(\mathbf{x})\) trên các đa tạp số chiều thấp (Poggio et al., 2017):
- Thị giác Máy tính (
Computer Vision): Các đặc trưng phân cấp bất biến dịch chuyển từ biên cạnh cục bộ \(\to\) bộ phận \(\to\) vật thể toàn cục (Chương 16–Chương 17). - Xử lý Ngôn ngữ & Mô hình Ngôn ngữ Lớn (
LLMs): Phân rã mật độ tự hồi quy \(P(x_1,\dots,x_S) = \prod_{t=1}^S P(x_t \mid x_{<t})\) thông qua các tầngPre-Norm+RMSNorm+SwiGLU+ Self-Attention (Chương 18–Chương 20). - Dữ liệu Chuỗi & Cảm biến IoT / Khoa học (
Scientific ML): Trích xuất biểu diễn đa tỷ lệ cho bảo trì dự đoán (RUL,Chương 15) và mô phỏng nghiệm phương trình đạo hàm riêng (PDE).
1.2 Xấp xỉ Phổ quát (UAT) vs. Định lý Tách sâu Hàm mũ (Telgarsky 2016)#
Mạng Truyền thẳng (FFNN) & Gấp Đa diện Lồi#
Một mạng FFNN \(L\) tầng biến đổi đầu vào \(\mathbf{h}^{(0)} = \mathbf{x} \in \mathbb{R}^{d_0}\) thành đầu ra \(\mathbf{h}^{(L)} \in \mathbb{R}^{d_L}\) qua:
và tầng đọc tuyến tính \(\mathbf{h}^{(L)} = \mathbf{W}^{(L)}\mathbf{h}^{(L-1)} + \mathbf{b}^{(L)}\). Trong PyTorch theo bố cục hàng (row-major), phép biến đổi tuyến tính của lô dữ liệu \(\mathbf{H}^{(l-1)} \in \mathbb{R}^{B \times d_{l-1}}\) thực thi dưới dạng nhân ma trận BLAS-3 GEMM: \(\mathbf{Z}^{(l)} = \mathbf{H}^{(l-1)}(\mathbf{W}^{(l)})^\top + \mathbf{1}_B(\mathbf{b}^{(l)})^\top\). Khi \(\phi = \operatorname{ReLU}\), một tầng ẩn đơn có bề rộng \(d_1\) cắt \(\mathbb{R}^{d_0}\) bằng \(d_1\) siêu phẳng thành tối đa \(\mathcal{O}(d_1^{d_0})\) vùng tuyến tính (Định lý Zaslavsky), trong khi việc hợp thành \(L\) tầng bề rộng \(d\) gấp đệ quy các miền đã chia, tạo tới \(\Omega\!\big((d/d_0)^{(L-1)d_0} d^{d_0}\big)\) vùng đa diện lồi (Montúfar et al., 2014) — tăng theo hàm mũ của độ sâu \(L\) thay vì đa thức của bề rộng \(d\).
Định lý Xấp xỉ Phổ quát (Cybenko 1989; Hornik 1991; Leshno et al. 1993)#
Trên tập compact \(K \subset \mathbb{R}^d\), lớp hàm một tầng ẩn \(\mathcal{F}_1(\phi) := \{ g(\mathbf{x}) = \sum_{j=1}^m c_j\,\phi(\mathbf{w}_j^\top \mathbf{x} + b_j) \}\) trù mật trong \(C(K)\) theo chuẩn \(\lVert f - g \rVert_\infty < \epsilon\) khi và chỉ khi \(\phi\) không phải là một đa thức đại số hầu khắp nơi.
Phác thảo chứng minh (Cybenko, Hahn–Banach + Riesz): Giả sử bao đóng \(\overline{\mathcal{F}_1(\sigma)} \subsetneq C(K)\) là không gian con thực sự. Theo định lý Hahn–Banach và biểu diễn Riesz–Markov–Kakutani, tồn tại độ đo Borel có dấu khác không \(\mu \not\equiv 0\) trên \(K\) sao cho \(\int_K \sigma(\gamma(\mathbf{w}^\top \mathbf{x} + b) + \theta)\,d\mu(\mathbf{x}) = 0\) với mọi \(\gamma, \theta \in \mathbb{R}\). Cho \(\gamma \to +\infty\) rồi áp dụng định lý hội tụ bị chặn Lebesgue, \(\sigma(\gamma(\mathbf{w}^\top \mathbf{x}+b)+\theta)\) hội tụ về hàm chỉ thị nửa không gian mở cộng \(\sigma(\theta)\) trên siêu phẳng; thay đổi \(\theta\) suy ra \(\mu\) triệt tiêu trên mọi nửa không gian, kéo theo \(\mu \equiv 0\) (mâu thuẫn!). Chiều ngược lại (Leshno et al.): nếu \(\phi\) là đa thức bậc \(p\), mọi tổ hợp hữu hạn vẫn có bậc \(\le p\), không thể xấp xỉ \(\cos(x)\) trên \([0,1]\).
Định lý Tách sâu Hàm mũ (Telgarsky, COLT 2016)#
UAT chỉ khẳng định sự tồn tại khi bề rộng \(m \to \infty\) mà không chặn \(m\) ở mức đa thức. Định nghĩa ánh xạ sóng tam giác (triangle-wave) \(\phi_\triangle: \mathbb{R} \to [0, 1]\) dùng đúng 3 đơn vị ReLU:
Gọi \(\phi_k := \underbrace{\phi_\triangle \circ \dots \circ \phi_\triangle}_{k\text{ lần}}\) là phép hợp \(k\) tầng (\(\mathcal{O}(k)\) tham số, bề rộng không đổi 3).
- Bổ đề Quy nạp (
2^kĐoạn Tuyến tính): Tại \(k=1\), \(\phi_1\) có \(2^1\) đoạn đơn điệu ánh xạ song ánh \([0, 1/2]\) và \([1/2, 1]\) lên \([0, 1]\) với \(2^0 = 1\) đỉnh. Giả sử \(\phi_{k-1}\) chia \([0, 1]\) thành \(2^{k-1}\) đoạn bằng nhau ánh xạ song ánh lên \([0, 1]\). Hợp thêm \(\phi_\triangle\) gập đôi mỗi đoạn thành hai đoạn con ngược chiều nhau, tạo chính xác \(2^k\) đoạn tuyến tính và \(2^{k-1}\) đỉnh. - Cận dưới Cho Mạng Nông 2 Tầng (
WB-Ch14,Test 05): Bất kỳ mạng nông \(g(x)\) 1 tầng ẩn có \(m\) nútReLUchỉ có tối đa \(m\) điểm gãy nên không quá \(m+1\) đoạn tuyến tính, và hàm \(\operatorname{sgn}(g(x) - 1/2)\) đổi dấu tối đa \(m+1\) lần. Trong khi đó \(\operatorname{sgn}(\phi_k(x) - 1/2)\) luân phiên dấu đều đặn qua \(2^k\) khoảng độ dài \(2^{-k}\) trên \([0, 1]\). Do đó xác suất bất đồng phân loại trên \(x \sim \mathcal{U}[0,1]\) bị chặn dưới bởi:
Muốn đạt sai số nhỏ hơn \(1/4\), mạng nông 2 tầng bắt buộc phải có bề rộng \(m = \Omega(2^k)\)! Tổng quát hơn, Telgarsky (2016) chứng minh một hàm từ mạng \(\Theta(k^3)\) tầng bề rộng \(\mathcal{O}(1)\) tạo \(2^{\Theta(k^3)}\) dao động không thể được xấp xỉ bởi mạng sâu \(\mathcal{O}(k)\) tầng nếu bề rộng nhỏ hơn \(2^{\Omega(k^2)}\). Trong WB-Ch14 (Test 05), tại \(k=5\), \(\phi_5\) sinh đúng 32 đoạn và 16 đỉnh; mạng nông \(m=8\) chịu cận dưới 0.34375 > 0.25 (bất đồng thực nghiệm 0.491).
1.3 Ma trận Jacobian Sâu & Xa lộ Thặng dư Pre-Norm Tỷ lệ \(1/\sqrt{2L}\)#
Ở một FFNN thuần \(L\) tầng, quy tắc dây chuyền Bố cục Tử số cho Jacobian từ đầu vào tới tầng \(L\):
Tích của \(L\) ma trận ngẫu nhiên có tích số giá trị kỳ dị co hoặc nở theo hàm mũ \(c^{L/2}\) khi phương sai từng tầng lệch khỏi 1.0. Ngược lại, xét \(L\) khối Pre-Norm (mỗi khối có \(2\) nhánh con Attention + FFN \(\implies 2L\) bước thặng dư \(m = 0, \dots, 2L-1\)) với hệ số tỷ lệ đầu ra nhánh \(1/\sqrt{2L}\):
Gọi \(\mathbf{A}_m := \mathbf{J}_{\mathbf{F}_m \circ \operatorname{Norm}}(\mathbf{x}_m)\). Khi đó Jacobian toàn mạng mang cấu trúc xa lộ đồng nhất:
Ở lúc khởi tạo, các trọng số trong \(\mathbf{F}_m\) độc lập và đối xứng tâm nên \(\mathbb{E}[\mathbf{A}_m] = \mathbf{0}\) và \(\mathbb{E}[\mathbf{A}_m^\top \mathbf{A}_m] = \nu^2 \mathbf{I}_d\) (\(\nu = \mathcal{O}(1)\)). Điều kiện hóa trên \(\mathbf{v}_m = \mathbf{J}_{\mathbf{x}_m}(\mathbf{x}_0)\mathbf{v}_0\) với \(\lVert \mathbf{v}_0 \rVert_2 = 1\):
Lặp qua tất cả \(2L\) bước, bất kể \(L = 20, 80\) hay \(128\) tầng:
1.4 Hàm Kích hoạt (Sigmoid \(\to\) ReLU \(\to\) GELU/SiLU) & Cân bằng Tham số SwiGLU#
| Hàm Kích hoạt | Công thức \(\phi(z)\) | Đạo hàm \(\phi'(z)\) & Cận | Mô-men bậc 2 \(\mathbb{E}_{z\sim\mathcal{N}(0,1)}[\phi(z)^2]\) | Bệnh lý & Ghi chú Hệ thống |
|---|---|---|---|---|
| Sigmoid | \(\sigma(z) = \frac{1}{1+e^{-z}}\) | \(\sigma(z)(1-\sigma(z)) \in (0, \frac{1}{4}]\) | \(\approx 0.2934\) | Bão hòa mũ \(e^{-\lvert z\rvert}\); lệch tâm dương (\(\sigma(z)>0\)) gây bước zig-zag cho trọng số; suy giảm \(\le 4^{-L}\) qua \(L\) tầng |
| Tanh | \(\frac{e^z-e^{-z}}{e^z+e^{-z}}\) | \(1-\tanh^2(z) \in (0, 1]\) | \(\approx 0.3943\) | Đối xứng tâm \(0\) (khắc phục zig-zag), nhưng vẫn bão hòa mũ khi \(\lvert z\rvert \gg 1\) |
| ReLU | \(\max(0, z)\) | \(\mathbb{I}\{z > 0\}\) | \(\frac{1}{2}\) (đúng \(\frac{1}{2}\sigma_z^2\) với mọi \(z\) đối xứng) | Chết nơ-ron (Dying ReLU): nếu \(\mathbf{w}_j^\top \mathbf{x}+b_j \le 0\) trên mọi mẫu thì gradient triệt tiêu vĩnh viễn; cần hệ số He 2 |
| GELU | \(z\Phi(z) = \frac{z}{2}[1+\operatorname{erf}(\frac{z}{\sqrt{2}})]\) | \(\Phi(z) + \frac{z}{\sqrt{2\pi}}e^{-z^2/2}\) (\(\max \approx 1.129\)) | \(\approx 0.4252\) | Khả vi \(C^\infty\); vùng âm nhỏ (\(\min \approx -0.170\)) cứu gradient âm khỏi chết cứng |
| SiLU / Swish | \(z\sigma(z)\) | \(\sigma(z)[1 + z(1-\sigma(z))]\) (\(\max \approx 1.100\)) | \(\approx 0.3558\) | Tự cổng trơn (\(\min \approx -0.2785\)); hạt nhân của khối SwiGLU |
Chứng minh Hệ số Phương sai 1/2 của ReLU: Với tiền kích hoạt \(z\) phân bố đối xứng qua \(0\) (\(p_Z(z) = p_Z(-z)\)) và mô-men \(\mathbb{E}[z^2] = \sigma_z^2\), do \(\operatorname{ReLU}(z) = 0\) trên \((-\infty, 0]\) nên:
Cổng Song tuyến SwiGLU (Shazeer 2020) & Cân bằng \(d_{\text{ff}} = \frac{8}{3}d\)#
Thay vì dùng \(2\) ma trận trong FFN chuẩn (\(\operatorname{FFN}(\mathbf{x}) = \phi(\mathbf{x}\mathbf{W}_{\text{in}})\mathbf{W}_{\text{out}}\) với \(d_{\text{ff\_std}} = 4d \implies P_{\text{std}} = 2 \cdot d \cdot 4d = 8d^2\) tham số và \(16 B S d^2\) FLOPs), SwiGLU nhân phần tử giữa một nhánh chiếu tuyến tính và một nhánh cổng SiLU:
(Trong PyTorch nn.Linear, các ma trận lưu chuyển vị là \(\mathbf{W}_{\text{gate}}, \mathbf{W}_{\text{up}} \in \mathbb{R}^{d_{\text{ff}} \times d}\) và \(\mathbf{W}_{\text{down}} \in \mathbb{R}^{d \times d_{\text{ff}}}\).) Do có 3 ma trận chiếu, tổng số tham số là \(P_{\text{SwiGLU}} = 3 d d_{\text{ff}}\) và tổng phép tính GEMM là \(6 B S d d_{\text{ff}}\). Để giữ nguyên ngân sách tham số và FLOP ngang bằng FFN \(4d\):
Trong WB-Ch14 (audit_swiglu_param_flop_parity), tại \(d = 4096\), giá trị chính xác là \(d_{\text{ff}} = 10{,}922.67\) (134,217,728 tham số, 1.000x); làm tròn lên bội số 256 để khớp gạch Tensor Core WGMMA cho d_ff = 11,008 (135,266,304 tham số, chỉ dư +0.78125%). Họ Gemma 2/3 dùng biến thể GeGLU (thay SiLU bằng GELU).
1.5 Khởi tạo Trọng số (Xavier/Kaiming/\(1/\sqrt{2L}\)) & Chuẩn hóa (BatchNorm vs LayerNorm vs RMSNorm)#
Xét tầng tuyến tính \(y_i = \sum_{j=1}^{n_{\text{in}}} W_{ij} x_j\) với trọng số \(W_{ij}\) độc lập trung bình 0, phương sai \(\operatorname{Var}(W)\) và độc lập với đầu vào \(x_j\). Do các tích chéo \(j \neq k\) triệt tiêu:
-
Khởi tạo
Xavier / Glorot(Glorot & Bengio, 2010): Dành cho hàm đối xứng quanh \(0\) nhưtanh(\(\mathbb{E}[x^2] = \operatorname{Var}(x)\)). Dung hòa điều kiện xuôi \(n_{\text{in}}\operatorname{Var}(W) = 1\) và điều kiện ngược \(n_{\text{out}}\operatorname{Var}(W) = 1\) bằng trung bình điều hòa:\[\operatorname{Var}(W) = \frac{2}{n_{\text{in}} + n_{\text{out}}} \qquad \Big(\text{phân phối đều } \mathcal{U}\!\Big[-\sqrt{\tfrac{6}{n_{\text{in}}+n_{\text{out}}}}, \sqrt{\tfrac{6}{n_{\text{in}}+n_{\text{out}}}}\Big]\Big).\]Bẫy chết người khi dùng
XaviertrênReLU: Vì \(\mathbb{E}[x^2] = \frac{1}{2}\operatorname{Var}(y^{(l-1)})\), mỗi tầngReLUbị nhân hệ số \(\frac{1}{2}\): ở \(L=20\), phương sai sụp xuống \((1/2)^{20} \approx 9.54 \times 10^{-7}\) (1.02e-06trongWB-Ch14). -
Khởi tạo
Kaiming / He(He et al., 2015): Giải trực tiếp \(\frac{1}{2}n_{\text{in}}\operatorname{Var}(W) = 1\):\[\operatorname{Var}(W) = \frac{2}{n_{\text{in}}} \quad (\text{chế độ fan\_in}), \qquad \text{hoặc } \operatorname{Var}(W) = \frac{2}{n_{\text{out}}} \quad (\text{chế độ fan\_out}).\] -
Bùng nổ \(2^L\) khi thiếu Tỷ lệ Dư & Chuẩn hóa: Trong mạng dư \(\mathbf{x}_{l+1} = \mathbf{x}_l + \mathbf{F}_l(\mathbf{x}_l)\) không có
Normhay hệ số \(1/\sqrt{2L}\), phương sai cộng dồn gấp đôi mỗi khối thành \(\operatorname{Var}(\mathbf{x}_L) = 2^L\operatorname{Var}(\mathbf{x}_0)\) (\(2^{20} \approx 1.05\times 10^6\)). Kết hợpPre-Normvà nhân đầu ra nhánh dư với \(1/\sqrt{2L}\) (GPT-2) cố định phương sai ở \(\operatorname{Var}(\mathbf{x}_{2L}) = 1 + 2L \cdot \frac{1}{2L} = 2 = \Theta(1)\) (1.59xtrongWB-Ch14).
So sánh Toàn diện: BatchNorm vs. LayerNorm vs. RMSNorm#
-
BatchNorm(Ioffe & Szegedy, 2015) & Chứng minh Sụp đổB=2:Ở chế độ
train(),BatchNormtính trung bình \(\mu_{B,j} = \frac{1}{B}\sum_{b=1}^B x_{b,j}\) và phương sai \(\sigma_{B,j}^2 = \frac{1}{B}\sum_{b=1}^B (x_{b,j} - \mu_{B,j})^2\) dọc trục lô \(B\), rồi cập nhật bộ đệmrunning_mean/running_var(hệ số hiệu chỉnh Bessel \(\frac{B}{B-1}\)) theo EMA với \(m_{\text{bn}} = 0.1\) để dùng cố định lúceval(). Điều này gây ra hai thảm họa:- Bẫy quên
model.eval(): Khi phục vụ lưu lượng thực tế mà quên gọimodel.eval(),BatchNorm1dtạiB=1văng lỗiValueError, cònBatchNormtrên ảnh/lô nhỏ làm nhiễu dự đoán theo các mẫu cùng batch và đầu độcrunning_mean(trôi 1.213trongWB-Ch14). -
Chứng minh Sụp đổ
B=2: Với \(x_1, x_2 \stackrel{\text{i.i.d.}}{\sim} \mathcal{N}(\mu, \sigma^2)\), ta có \(\mu_B = \frac{x_1+x_2}{2}\) và \(\sigma_B^2 = \frac{(x_1-x_2)^2}{4}\), dẫn đến \(\mathbb{E}[\sigma_B^2] = \frac{1}{2}\sigma^2\) (thiên lệch âm-50%, khớp0.509trongWB-Ch14) và hệ số biến thiên \(\text{CV}(\sigma_B^2) = \sqrt{2} \approx 141.4\%\). Tệ hơn, khi \(\varepsilon \to 0\):\[\hat{x}_{1,j} = \frac{(x_1 - x_2)/2}{\sqrt{(x_1 - x_2)^2/4}} = \operatorname{sgn}(x_1 - x_2) \in \{-1, +1\}, \qquad \hat{x}_{2,j} = -\operatorname{sgn}(x_1 - x_2).\]Tại
B=2,BatchNormxóa sạch 100% độ lớn liên tục của mọi kênh về hai mức lượng tử \(\pm 1\) (lệch 2.38e-07trongWB-Ch14)! (Giải phápGroupNormchia \(C\) kênh thành \(G\) nhóm trên từng mẫu, cònSyncBatchNormép đồng bộNCCL all-reduce2 chiều ở mọi lớp gây nghẽn đa node.)
- Bẫy quên
-
LayerNorm(Ba et al., 2016): Chuẩn hóa độc lập trên trục đặc trưng \(d\) của từng mẫu (\(\mu_b, \sigma_b^2\)), hoàn toàn giống nhau ởtrain()vàeval(), chạy an toàn tại \(B=1\). Jacobian của \(\hat{\mathbf{x}} = (\mathbf{x}-\mu\mathbf{1})/\sigma\) chiếu vuông góc cả \(\mathbf{1}\) lẫn \(\hat{\mathbf{x}}\):\[\mathbf{J}_{\hat{\mathbf{x}}}(\mathbf{x}) = \frac{1}{\sigma}\left(\mathbf{I}_d - \frac{1}{d}\mathbf{1}\mathbf{1}^\top - \frac{1}{d}\hat{\mathbf{x}}\hat{\mathbf{x}}^\top\right),\]nên
LayerNormbất biến với cả phép dịch hằng số (\(\mathbf{x} + c\mathbf{1}\)) lẫn co giãn tỷ lệ dương (\(\alpha\mathbf{x}\)). -
RMSNorm(Zhang & Sennrich, NeurIPS 2019): Chứng minh rằng sức mạnh ổn định củaLayerNormđến từ bất biến co giãn tỷ lệ (re-scaling invariance) chứ không phải dịch trung bình \(\mu_b\).RMSNormbỏ phép trừ \(\mu_b\) và vector dịch \(\boldsymbol{\beta}\), giảm xuống còn 1 phép giảm chiều duy nhất:\[\operatorname{RMS}(\mathbf{a}) = \sqrt{\frac{1}{d}\sum_{i=1}^d a_i^2 + \varepsilon}, \qquad \bar{a}_i = \frac{a_i}{\operatorname{RMS}(\mathbf{a})} \cdot \gamma_i, \qquad \mathbf{J}_{\tilde{\mathbf{a}}}(\mathbf{a}) = \frac{1}{\operatorname{RMS}(\mathbf{a})}\left(\mathbf{I}_d - \frac{\mathbf{a}\mathbf{a}^\top}{d\,\operatorname{RMS}(\mathbf{a})^2}\right).\]Khi nhân ma trận trọng số \(\mathbf{W}' = \alpha \mathbf{W}\) (\(\alpha > 0 \implies \mathbf{a}' = \alpha\mathbf{a}\)), \(\operatorname{RMS}(\alpha\mathbf{a}) = \alpha\operatorname{RMS}(\mathbf{a})\) triệt tiêu chính xác \(\alpha\) (
WB-Ch14đo sai khác4.77e-07), nhưng lưu ýRMSNormkhông bất biến với phép cộng hằng số \(\mathbf{a} + c\mathbf{1}\).
Hãy thử thay đổi chiến lược khởi tạo, độ sâu \(L \in [2, 40]\), kích thước lô \(B = 2\) của BatchNorm và bậc hợp \(k\) của hàm răng cưa Telgarsky trong trình mô phỏng tương tác đầu tiên:
1.6 Lan truyền Ngược, VJP vs JVP, Checkpointing \(O(\sqrt{L})\) & Ngân sách Bộ nhớ \(16\Psi\)#
Kế thừa khung Giải tích Ma trận Bố cục Tử số từ Chương 02:
-
Chế độ Xuôi (
JVP) vs. Chế độ Ngược (VJP):JVPđẩy vector tiếp tuyến \(\dot{v}_k = \sum_{u \in \operatorname{pa}(v_k)} \mathbf{J}_{\phi_k, u} \dot{u}\) dọc theo đồ thịWengert DAGchỉ tốn bộ nhớ kích hoạt \(O(1)\), nhưng để tính đủ \(\Psi\) thành phần của \(\nabla_{\boldsymbol{\theta}} \mathcal{L}\) (với hàm mất mát vô hướng \(\mathcal{L} \in \mathbb{R}\)) đòi hỏi \(\Psi\) lần chạy xuôi — bất khả thi khi \(\Psi \sim 10^9\). Ngược lại,VJP(Backpropagation) gieo \(\bar{\mathcal{L}} = 1\) rồi đi ngược thứ tự topo qua một lượt duyệt duy nhất \(O(1)\):\[\bar{u} := \nabla_u \mathcal{L} = \sum_{k \in \operatorname{ch}(u)} \left(\frac{\partial \phi_k}{\partial u^\top}\right)^\top \bar{v}_k.\]Với tầng tuyến tính hàng \(\mathbf{Y} = \mathbf{X}\mathbf{W}^\top\) (\(\mathbf{X} \in \mathbb{R}^{B \times d_{\text{in}}}, \mathbf{W} \in \mathbb{R}^{d_{\text{out}} \times d_{\text{in}}}\)) nhận đạo hàm ngược \(\bar{\mathbf{Y}}\), đồng nhất thức vết cho \(\nabla_{\mathbf{X}}\mathcal{L} = \bar{\mathbf{Y}}\mathbf{W}\) (
dgrad, \(2 B d_{\text{in}} d_{\text{out}}\) FLOPs) và \(\nabla_{\mathbf{W}}\mathcal{L} = \bar{\mathbf{Y}}^\top \mathbf{X}\) (wgrad, \(2 B d_{\text{in}} d_{\text{out}}\) FLOPs). Theo Định lý Baur–Strassen (1983), một lượt xuôi + một lượt ngược không vượt quá \(3\times\) chi phí phép tính xuôi (\(2 + 4 = 6 B d_{\text{in}} d_{\text{out}}\) FLOPs).
Chứng minh Tối ưu Gradient Checkpointing (\(O(L \cdot B \cdot d) \to O(\sqrt{L})\), \(+33.3\%\) Compute)#
Vì wgrad (\(\bar{\mathbf{Y}}^\top \mathbf{X}\)) đòi hỏi giữ nguyên đầu vào \(\mathbf{X}\) của mọi tầng trong pha xuôi, bộ nhớ kích hoạt chuẩn tăng tuyến tính \(M_{\text{act}}^{\text{std}} = L \cdot m_{\text{act}} = \Theta(L \cdot B \cdot d)\) (42.95 GB tại L=32, 85.90 GB tại L=64 trong mô hình 7B của WB-Ch14). Khi chia \(L\) tầng thành \(k\) đoạn có chiều dài \(L/k\), chỉ lưu lại \(k\) điểm kiểm tra ranh giới đoạn trong pha xuôi rồi chạy lại pha xuôi cục bộ từng đoạn khi đi ngược, tổng đỉnh bộ nhớ là \(M(k) = m_{\text{act}}(k + \frac{L}{k})\). Giải phương trình đạo hàm bằng 0:
Về phép tính: huấn luyện chuẩn thực hiện \(1\) xuôi (\(L F_1\)) + \(1\) ngược (\(2 L F_1\)) \(= 3 L F_1\); Checkpointing thêm đúng \(1\) lượt tính lại xuôi (\(L F_1\)) thành \(4 L F_1\), tạo ra mức tăng chi phí tính toán chính xác là \(\frac{4 L F_1 - 3 L F_1}{3 L F_1} = \frac{1}{3} = \mathbf{+33.33\%}\). Trong thực tiễn hiện đại, tính lại chọn lọc (Selective Activation Checkpointing — SAC, Korthikanti et al. 2023) chỉ bỏ qua các tensor lớn ít FLOP như softmax/norm/activation mà giữ lại đầu ra GEMM, đạt mức tiết kiệm bộ nhớ tương đương (-72.0% trong WB-Ch14) với chỉ +4.0% FLOPs.
Kiểm toán Chính xác Bức tường Bộ nhớ \(16\Psi\) của AdamW Hỗn hợp#
Vùng đệm Tĩnh (Static Buffers) |
Kiểu Dữ liệu & Byte/Tham số | Tổng Dung lượng (\(\Psi\) tham số) | Quy mô 7B (\(\Psi = 7\times 10^9\)) |
Vai trò Hệ thống Bắt buộc |
|---|---|---|---|---|
| 1. Trọng số Mô hình (\(\boldsymbol{\theta}_{16}\)) | bf16 / fp16 (2 B) |
\(2\Psi\) | 14.0 GB |
Chạy GEMM tốc độ cao trên Tensor Cores |
| 2. Gradient (\(\mathbf{g}_{16}\)) | bf16 / fp16 (2 B) |
\(2\Psi\) | 14.0 GB |
Lưu wgrad (tăng lên \(4\Psi \implies 18\Psi\) nếu tích lũy fp32) |
3. Trọng số Chủ (Master \(\boldsymbol{\theta}_{32}\)) |
fp32 (4 B) |
\(4\Psi\) | 28.0 GB |
Chống đóng băng làm tròn ULP của bf16 (\(2^{-7}\)) |
4. Mô-men bậc 1 (AdamW \(\mathbf{m}_t\)) |
fp32 (4 B) |
\(4\Psi\) | 28.0 GB |
Trung bình trượt hàm mũ của gradient (exp_avg) |
5. Mô-men bậc 2 (AdamW \(\mathbf{v}_t\)) |
fp32 (4 B) |
\(4\Psi\) | 28.0 GB |
Trung bình trượt bình phương gradient (exp_avg_sq) |
Tổng Bộ nhớ Tĩnh (Static Total) |
— | \(16\Psi\text{ bytes}\) | 112.0 GB |
Chưa gồm bộ nhớ kích hoạt \(O(L \cdot B \cdot S \cdot d)\)! |
1.7 Hàm Mất mát LSE, Adam Ghép \(L_2\) vs AdamW, Lịch trình & Muon (NS_5)#
-
Hàm Mất mát
CrossEntropyLossỔn định bằngLog-Sum-Exp(LSE):Với vector logit \(\mathbf{z} \in \mathbb{R}^K\) và nhãn đúng \(c\), tính trực tiếp \(\log\sum_j e^{z_j}\) tràn ngay lên
infkhi \(z_j > 88.72\) (fp32) hoặc \(z_j > 11.09\) (fp16), và sụp về \(-\infty\) khi mọi \(z_j < -104\). Đưa đại lượng lớn nhất \(m := \max_j z_j\) ra ngoài bảo đảm mọi số mũ thỏa mãn \(e^{z_j - m} \in (0, 1]\) với ít nhất một phần tử bằng1:\[\mathcal{L}_{\text{CE}}(\mathbf{z}, c) = m - z_c + \log\sum_{j=1}^K e^{z_j - m}, \qquad \frac{\partial \mathcal{L}_{\text{CE}}}{\partial z_j} = \frac{e^{z_j - m}}{\sum_{k=1}^K e^{z_k - m}} - \mathbb{I}\{j = c\}.\] -
Chứng minh Lỗi \(L_2\) Ghép cặp của
Adamvs.AdamW(Loshchilov & Hutter, ICLR 2019):Với
SGD + Momentum, thêm \(\frac{\lambda}{2}\lVert \boldsymbol{\theta} \rVert_2^2\) vào hàm mất mát cho \(\tilde{\mathbf{g}}_t = \mathbf{g}_t + \lambda \boldsymbol{\theta}_t\), tương đương suy giảm trọng số đồng đều \(\boldsymbol{\theta}_{t+1} = (1 - \eta_t\lambda)\boldsymbol{\theta}_t - \eta_t \mathbf{g}_t\). Nhưng khi đưa \(\tilde{\mathbf{g}}_t\) vàoAdam, cả \(\mathbf{m}_t\) và \(\mathbf{v}_t\) đều hấp thụ \(\lambda\boldsymbol{\theta}_t\), biến bước co ngót thành:\[\boldsymbol{\theta}_{t+1} = \boldsymbol{\theta}_t - \eta_t \frac{\operatorname{EMA}_{\beta_1}(\mathbf{g}_t)}{\sqrt{\hat{\mathbf{v}}_t} + \varepsilon} - \underbrace{\frac{\eta_t \lambda}{\sqrt{\hat{\mathbf{v}}_t} + \varepsilon}}_{\text{co ngót méo theo } \hat{\mathbf{v}}_t!}\operatorname{EMA}_{\beta_1}(\boldsymbol{\theta}_t).\]Các trọng số có gradient lịch sử lớn (\(\sqrt{\hat{v}_{t,j}} \gg 1\)) bị chia nhỏ lực co ngót (hầu như không được điều chuẩn), còn các trọng số gradient nhỏ bị ép co quá mức (
2.972xlệch tỷ số trongWB-Ch14!).AdamWsửa triệt để bằng cách tính \(\mathbf{m}_t, \mathbf{v}_t\) thuần trên \(\mathbf{g}_t\) và tách bước suy giảm ra ngoài:\[\boldsymbol{\theta}_{t+1} = (1 - \eta_t\lambda)\boldsymbol{\theta}_t - \eta_t \frac{\hat{\mathbf{m}}_t}{\sqrt{\hat{\mathbf{v}}_t} + \varepsilon}.\]Quy tắc Tách nhóm Tham số: Tuyệt đối không áp
weight_decay > 0lên các vector 1D (LayerNorm/RMSNorm\(\gamma\) khởi tạo tại1.0,bias) — tách riêng2D+(weight_decay\(= \lambda\)) và1D(weight_decay = 0.0). -
Lịch trình Khởi động Tuyến tính + Suy giảm Cosine (
Linear Warmup + Cosine Decay):\[\eta(t) = \begin{cases} \eta_{\max} \cdot \frac{t}{T_w}, & 1 \le t \le T_w, \\[6pt] \eta_{\min} + \frac{1}{2}(\eta_{\max} - \eta_{\min})\left(1 + \cos\!\left(\pi\,\frac{t - T_w}{T - T_w}\right)\right), & T_w < t \le T. \end{cases}\]Theo phân tích phương sai
RAdam(Liu et al., ICLR 2020), ở các bước đầu \(t \le 5\) khi \(\beta_2 = 0.999\), bộ ước lượng \(\frac{1}{\sqrt{\hat{\mathbf{v}}_t}}\) có phương sai vô hạn, dễ kích hoạt bước nhảy phá hỏng cấu trúc đặc trưng nếu không có khởi động tuyến tính \(T_w\). -
Bộ tối ưu
Muon(Jordan et al. 2024–2025;Moonlight,Liu et al. 2025):Kế thừa lý thuyết đối ngẫu phổ–hạt nhân từ
Chương 02,Muonthực hiện dốc nhất theo chuẩn phổ trên các ma trận trọng số ẩn 2D bằng cách xấp xỉ nhân tử cực \(\operatorname{polar}(\mathbf{M}_t) = \mathbf{U}\mathbf{V}^\top\) của động lượng Nesterov \(\mathbf{M}_t = \mathbf{G}_t + \mu_{\text{mom}}\mathbf{B}_t\) (\(\mu_{\text{mom}} = 0.95\)) mà không cầnSVD: chuẩn hóa \(\mathbf{X}_0 = \mathbf{M}_t / (\lVert \mathbf{M}_t \rVert_F + \varepsilon)\) (bảo đảm mọi giá trị kỳ dị nằm trong \([0, 1]\)) rồi lặp 5 lần đa thức lẻ bậc 5 \(\phi_{\text{NS}}(s) = 3.4445s - 4.7750s^3 + 2.0315s^5\):\[\mathbf{A}_k = \mathbf{X}_k \mathbf{X}_k^\top, \qquad \mathbf{X}_{k+1} = 3.4445\,\mathbf{X}_k + (-4.7750)\,\mathbf{A}_k\mathbf{X}_k + 2.0315\,\mathbf{A}_k^2\mathbf{X}_k \qquad (k = 0,\dots,4).\]Phép lặp
NS_5ánh xạ toàn bộ dải kỳ dị[0.01, 1.0]vào[0.6819, 1.1344](WB-Ch14). Để ổn định ở quy mô lớn (Moonlight-16Btiết kiệm ~50% FLOPs huấn luyện so vớiAdamW), bắt buộc tuân thủ hai luật: (i) chỉ áp dụngMuoncho ma trận trọng số ẩn 2D, giữ toàn bộ tham số 1D (RMSNorm,bias), bảng nhúngembed_tokens(gradient thưa Zipfian) và đầu ralm_head(cần bảo toàn độ lớn logit theo tần suất) trênAdamW; (ii) nhân bước trực giao \(\mathbf{O}_t\) với hệ số khớpAdamWRMS0.2 * sqrt(max(d_out, d_in))kèm suy giảm trọng số tách rời.
1.8 Kỹ thuật Điều chuẩn (Inverted Dropout, Label Smoothing, MixUp, CutMix)#
Inverted Dropout(Srivastava et al., 2014): Ởtrain(), nhân mặt nạ \(r_i \sim \operatorname{Bernoulli}(1 - p)\) với hệ số phóng đại \(\frac{1}{1 - p}\) để giữ nguyên kỳ vọng \(\mathbb{E}[\tilde{h}_i \mid h_i] = h_i\) (phương sai nhiễu \(\frac{p}{1-p}h_i^2\), tương đương hiệu chỉnh Tikhonov thích nghi theo đường chéo ma trận Fisher); ởeval(), biến đổi trở thành ánh xạ đồng nhất chính xác (diff = 0.0).Label Smoothing(Szegedy et al., 2016;Müller et al., 2019): Thay nhãn cứng \(\mathbf{e}_c\) bằng \(y_j^{\text{LS}} = (1 - \epsilon_{\text{ls}})\mathbb{I}\{j=c\} + \frac{\epsilon_{\text{ls}}}{K}\), buộc điểm cực tiểu toàn cục dừng tại khoảng cách logit hữu hạn \(z_c^* - z_{j\neq c}^* = \log\!\big(\frac{(1-\epsilon_{\text{ls}})K+\epsilon_{\text{ls}}}{\epsilon_{\text{ls}}}\big)\) thay vì phân kỳ ra \(+\infty\) (margin 2.163vs7.747trongWB-Ch14), cải thiện mạnh hiệu chuẩn xác suất (ECE).MixUp(Zhang et al., 2018) &CutMix(Yun et al., 2019): Rút \(\lambda_{\text{mix}} \sim \operatorname{Beta}(\alpha_{\text{mix}}, \alpha_{\text{mix}})\):MixUpnội suy tuyến tính \((\tilde{\mathbf{x}}, \tilde{\mathbf{y}}) = \lambda_{\text{mix}}(\mathbf{x}_i, \mathbf{y}_i) + (1-\lambda_{\text{mix}})(\mathbf{x}_j, \mathbf{y}_j)\) tương đương phạt chuẩn gradient đầu vào \(\lVert \nabla_{\mathbf{x}} f \rVert_2^2\); cònCutMixvá một khung chữ nhật nhị phân \(\mathbf{M} \in \{0,1\}^{H\times W}\) giữ nguyên thống kê điểm ảnh cục bộ và cập nhật nhãn đúng theo tỷ lệ diện tích không che \(\lambda_{\text{mix}} = 1 - \frac{r_w r_h}{WH}\) (0.8125khớp tuyệt đối trongWB-Ch14).
1.9 Tiêu chí Dừng Huấn luyện (Early Stopping) & Máy Trạng thái Khôi phục#
Dưới dòng chảy gradient liên tục \(\dot{\boldsymbol{\theta}}(t) = -\nabla \frac{1}{2}\lVert \mathbf{X}\boldsymbol{\theta}-\mathbf{y}\rVert_2^2\), Yao, Rosasco & Caponnetto (2007) chứng minh dừng tại thời điểm \(t\) co ngót thành phần kỳ dị \(\sigma_i\) bởi \((1 - e^{-t\sigma_i^2})\), tương đương điều chuẩn Ridge với \(\lambda_{\text{eff}} \propto 1/t\): dừng đúng lúc lọc bỏ hướng nhiễu kỳ dị nhỏ trước khi quá khớp. Trên thực hành ngẫu nhiên, thuật toán Prechelt (1998) theo dõi mất mát kiểm định sạch dưới model.eval() qua bộ đếm patience \(P\) và ngưỡng min_delta \(\delta_{\min}\):
- Nếu \(M_k < M^* - \delta_{\min}\): lưu \(M^* \leftarrow M_k\), sao chép sâu
best_state_dict\(\leftarrow \operatorname{deepcopy}(\boldsymbol{\theta}_k)\), đặt lại bộ đếmstale = 0. - Ngược lại tăng
stale += 1; khistale >= patience, dừng vòng lặp và bắt buộc gọimodel.load_state_dict(best_state_dict)để loại bỏ hoàn toàn độ trôi quá khớp tích tụ trongPepoch cuối (deploy_gap = +0.035trênval_lossvà1.707 -> 1.616trêntest_losstrongWB-Ch14).
Khám phá trực tiếp lỗi co ngót của Adam ghép \(L_2\), đường cong trực giao hóa Muon NS_5, lịch trình Warmup + Cosine và điểm khôi phục best_state_dict trong trình mô phỏng thứ hai:
Trụ cột 2 — Kiến trúc Hệ thống Sản xuất, Nội tại PyTorch 2.x, Độ chính xác Hỗn hợp & Mô hình Roofline#
2.1 Giải phẫu Bộ nhớ Tensor (Storage, Stride, view vs reshape) & Cơ chế autograd#
Một torch.Tensor tách rời hoàn toàn siêu dữ liệu khung nhìn (TensorImpl) gồm shape, stride(), storage_offset(), dtype, device khỏi vùng đệm byte vật lý 1D (untyped_storage()). Với tensor kích thước \(\mathbf{N} = (N_0, \dots, N_{d-1})\), bước nhảy \(\mathbf{s}_{\text{stride}} = (s_0, \dots, s_{d-1})\), độ lệch \(o\) và kích thước phần tử \(b\) byte, địa chỉ của phần tử \(\mathbf{i}\) là:
Tensor thỏa mãn tính liên tục hàng C-contiguous khi và chỉ khi \(s_k = \prod_{j=k+1}^{d-1} N_j\) với mọi \(N_k > 1\).
- Bẫy
.view()vs.reshape()& Giá băng thông Bộ nhớ Đệm: Các phép cắt lát hayx.t()hoàn thành trong \(O(1)\) chỉ bằng cách hoán đổistride(từ[64, 1]thành[1, 64]trongWB-Ch14). Vì bước nhảy không còn tương thích hợp trục,x.t().view(-1)némRuntimeError, trong khix.t().reshape(-1)âm thầm cấp phát vùng đệm mới và sao chép toàn bộ tensor (đứt liên kếtuntyped_storage().data_ptr()). Ở ma trận lớn (\(4096 \times 4096\)fp32), đọc theo hàng trên tensor chuyển vị khiến CPU (64 Bcache line \(= 16\) float) chỉ sử dụng \(1/16\) phần tử mỗi dòng bộ nhớ đệm (lãng phí93.75%băng thông DRAM) và warp GPU (32luồng) phải phát \(32\) giao dịch HBM rời rạc thay vì gộp mạch128 B! - Bộ đếm Phiên bản
_version&no_grad()vsinference_mode(): MọiTensorImplgiữ bộ đếm nguyên tử_version(dùng chung cho mọi view con). Ghi tại chỗ nhưh[:, :2] = 0haynn.ReLU(inplace=True)trước nhánh cộng thặng dư tăng_version(0 -> 1) khiến kiểm traSavedVariabletrong.backward()sập vớiRuntimeError; sửa.datacòn nguy hiểm hơn vì bỏ qua_versiongây sai gradient âm thầm. Khi suy luận,torch.no_grad()tắtAutogradnhưng vẫn duy trì_versionvà theo dõi view (ADInplaceOrView), còntorch.inference_mode()tắt đồng thời cả hai (đọc._versionbáo lỗi) để đạt tốc độ suy luận tối đa.
2.2 Ngăn xếp Trình biên dịch torch.compile (Ansel et al., ASPLOS 2024)#
Báo cáo của đội ngũ PyTorch tại ASPLOS 2024 trên 180+ mô hình thực tế cho thấy torch.compile mang lại tăng tốc trung bình nhân \(2.27\times\) cho suy luận và \(1.41\times\) cho huấn luyện nhờ ba tầng biên dịch tự động:
TorchDynamo(Can thiệp Bytecode CPythonPEP 523\(\to\) Đồ thịFX+Guards): Móc thẳng vào hàm thực thi frame của CPython (_PyInterpreterState_SetEvalFrameFunc) để vết các phép toán tensor thành đồ thịFXthuần túy kèm các chốt kiểm tra điều kiện (Guardschodtype,shape,stride). Mọi lệnh ép đồng bộ về CPU (.item(),.numpy(),print(tensor)) hay nhánh rẽifphụ thuộc giá trị tensor đều tạo điểm ngắt đồ thị (graph break): Dynamo buộc phải cắt rời đồ thị, đẩy tensor trung gian ra ngoài HBM và rơi về Python tuần tự — triệt tiêu hoàn toàn sức mạnh dung hợp của các tầng sau (WB-Ch14đo được1break khi có.item()so với0break trên mô hình sạch dùngbackend="aot_eager", fullgraph=True).AOTAutograd(Thuần hóa Đồ thị & Phân hoạchMin-Cut SAC): Biến mọi đột biến tại chỗ và view thành dạng gán tĩnh đơn (SSAtrên ~250 toán tử Core ATen), tạo trước đồ thị hợp nhất Xuôi + Ngược và giải bài toán cắt cực tiểu (Min-Cut / Max-Flow): đẩy các phép toán rẻ nhẹ về băng thông (SiLU,GELU, chuẩnRMSNorm) sang phía pha ngược để tính lại tại chỗ thay vì lưu vào HBM.TorchInductor(Loop-Level IR \(\to\) NhânTritonGPU /C++ AVX-512 AMXCPU): Hạ bậc đồ thị thành các vòng lặp lồng nhau và thực hiện dung hợp dọc (producer-consumer) cùng dung hợp ngang (parallel loops), sinh trực tiếp nhân OpenAI Triton trên GPU (kèmCUDA Graphs) hoặc mã C++OpenMP/SIMDtrên CPU. (Lưu ý biên dịch vùngRegional Compilation: với mô hình có \(L\) khối lặp giống nhau, bọc từng khối bằnglayer.compile(fullgraph=True)hoặc@torch.compiler.nested_compile_regiongiúp biên dịch đúng 1 lần thay vì lặp \(L\) lần.)
2.3 Vật lý Bit Độ chính xác Hỗn hợp (fp32, fp16, bf16, fp8) & CPU autocast#
Định dạng (dtype) |
Bố cục (S-E-M) |
Giá trị Lớn nhất | Chuẩn dưới Nhỏ nhất | Sai số Máy \(\varepsilon_{\text{mach}}\) tại 1.0 |
Khuyến nghị Sử dụng & Bẫy Số học |
|---|---|---|---|---|---|
fp32 (float32) |
1-8-23 |
\(\approx 3.40 \times 10^{38}\) | \(1.40 \times 10^{-45}\) | \(2^{-23} \approx 1.19 \times 10^{-7}\) | Trọng số chủ, trạng thái AdamW, các phép giảm chiều Softmax/RMSNorm/CrossEntropy |
fp16 (float16) |
1-5-10 |
65,504 |
\(5.96 \times 10^{-8}\) (subnormal) |
\(2^{-10} \approx 9.77 \times 10^{-4}\) | Chỉ dùng cho GPU cũ (V100/T4); bắt buộc GradScaler vì tràn \(>65{,}504\) và xóa \(10^{-8} \to 0\) |
bf16 (bfloat16) |
1-8-7 |
\(\approx 3.39 \times 10^{38}\) | \(9.18 \times 10^{-41}\) | \(2^{-7} \approx 7.81 \times 10^{-3}\) | Chuẩn huấn luyện 2026 (khớp dải mũ fp32, bỏ GradScaler), nhưng bắt buộc có fp32 master chống đóng băng \(\lvert\Delta w\rvert < 2^{-8}\lvert w\rvert\) |
fp8 E4M3 |
1-4-3 |
448 (không Inf) |
\(1.95 \times 10^{-3}\) | \(2^{-3} = 0.125\) | Kích hoạt & trọng số pha xuôi; cần tỷ lệ khối 1x128/128x128 (DeepSeek-V3) + cộng dồn fp32 ngoài bộ tích lũy 14-bit Hopper WGMMA |
fp8 E5M2 |
1-5-2 |
57,344 |
\(1.53 \times 10^{-5}\) | \(2^{-2} = 0.25\) | Gradient pha ngược nhờ có 5 bit mũ rộng; Blackwell thêm hệ số vi tỷ lệ E8M0 (MXFP8) |
Trên máy chủ không GPU, torch.autocast("cpu", dtype=torch.bfloat16) tận dụng tập lệnh AVX512_BF16/AMX-BF16 và tự động nâng các phép nhạy cảm (Softmax, RMSNorm, CrossEntropy) lên fp32 (đạt loss hữu hạn 1.325 và gradient sạch trong WB-Ch14).
2.4 Mô hình Hardware Roofline, Cường độ Số học & Tiết kiệm Băng thông Dung hợp Nhân#
Theo mô hình Roofline (Williams et al., 2009), hiệu năng đạt được bị kẹp bởi cả trần tính toán \(P_{\text{peak}}\) và trần băng thông bộ nhớ \(B_{\text{mem}}\) qua Cường độ Số học \(I = \frac{\text{FLOPs}}{\text{Bytes di chuyển}}\) và Điểm gãy phần cứng \(I^* := \frac{P_{\text{peak}}}{B_{\text{mem}}}\):
- NVIDIA H100 SXM5 (
bf16): \(989\text{ TFLOPS} / 3.35\text{ TB/s} \implies I^* = \mathbf{295.2\text{ FLOP/B}}\) (590.7ởfp8). - NVIDIA A100 SXM4 (
bf16): \(312\text{ TFLOPS} / 2.04\text{ TB/s} \implies I^* = \mathbf{153.0\text{ FLOP/B}}\). - Server CPU (
AMX-BF16,DDR5): \(\sim 60\text{ TFLOPS} / 350\text{ GB/s} \implies I^* \approx \mathbf{171.4\text{ FLOP/B}}\) (bắt buộc chia khối cache L2/L3).
Phép phân tích trực tiếp lý giải vì sao gần như mọi phép toán ngoài GEMM lô lớn đều bị trói bởi băng thông bộ nhớ (memory-bound) và giá trị khổng lồ của TorchInductor (b = 2 bytes bf16, \(T = B \cdot S\) token):
Bias + GELU + Residual: Chạy rời rạc3nhân đọc/ghi HBM tổng cộng7 T d bbytes (I = 0.86 FLOP/B); dung hợp dọcTorchInductorgiữ trung gian trong thanh ghi/SRAM chỉ còn3 T d bbytes (I = 2.00 FLOP/B) — cắt57.14%lưu lượng HBM (2.33xtrần băng thông).RMSNorm: Chạy rời rạc tốn7 T d bbytes (I = 0.36 FLOP/B); dung hợp một lượt chỉ đọc vào và ghi ra đúng2 T d bbytes (I = 1.25 FLOP/B) — cắt71.43%HBM.SwiGLU: Chạy rời rạc tốn8 T d_ff bbytes (I = 0.31 FLOP/B); dung hợp chỉ còn3 T d_ff bbytes (I = 0.83 FLOP/B) — cắt62.50%HBM.- Bước
AdamW(0.43 FLOP/B) &GEMMlô đơnB=1(1.00 FLOP/B): Đều nằm sâu dưới \(I^* = 295.2\), chỉ đạt< 1%công suất Tensor Core; ngược lạiGEMMhuấn luyện lô lớn (\(M=N=K=4096\)) đạt682.67–1,365.3 FLOP/B\(> I^*\), bão hòa toàn bộ cụm tính toán (989.0 TFLOPS).
Hãy thử điều chỉnh số tham số \(\Psi\), định dạng độ chính xác, chính sách Checkpointing và điểm gãy Roofline trong trình mô phỏng tương tác thứ ba:
2.5 Kiến trúc Phòng thủ Sản xuất, Bảng Ngân sách & Cẩm nang Quyết định#
| Lựa chọn Kỹ thuật | Phương án Khuyến nghị (Go) |
Bẫy Phải Tránh (No-Go) |
Ngưỡng Quy tắc Định lượng Ngoài Sản xuất |
|---|---|---|---|
| Độ chính xác Hỗn hợp | bf16 + fp32 Master (hoặc fp8 chia khối trên Hopper/Blackwell) |
fp16 + GradScaler trên GPU hiện đại; bf16 thuần không master |
Mặc định bf16 trên sm_80+ và CPU AMX; ép fp32 trong Softmax/CrossEntropy/RMSNorm |
| Lớp Chuẩn hóa | RMSNorm (MLP/LLM) hoặc GroupNorm (CNN lô nhỏ) |
BatchNorm khi B < 16 hoặc SyncBatchNorm qua mạng chậm |
Dừng dùng BatchNorm khi \(B_{\text{per-GPU}} < 16\); luôn kiểm tra B=1 vs B=32 bằng nhau dưới eval() |
| Khởi tạo & Sâu | Kaiming + tỷ lệ \(1/\sqrt{2L}\) cho nhánh thặng dư |
Xavier trên mạng ReLU sâu; nhánh dư không tỷ lệ |
Áp \(1/\sqrt{2L}\) lên W_down / W_O ngay khi độ sâu \(L \ge 6\) |
| Tối ưu hóa & Decay | AdamW tách nhóm (2D decay, 1D 0.0) hoặc Muon+AdamW |
torch.optim.Adam(..., weight_decay>0) hoặc áp decay/Muon lên 1D |
Kiểm tra param_groups khẳng định 1D có weight_decay == 0.0; Muon chỉ chạm ma trận 2D ẩn |
| Bộ nhớ vs Tốc độ | Selective SAC + FlashAttention |
Tràn HBM OOM hoặc checkpointing toàn phần mù quáng |
Bật SAC khi bộ nhớ kích hoạt vượt 60% HBM (< 5% FLOPs); dùng \(\sqrt{L}\) nếu vẫn thiếu RAM |
| Biên dịch & Phục vụ | torch.compile(fullgraph=True) + model.eval() + inference_mode() |
.item() / nhánh if trong forward(); quên khôi phục best_state_dict |
Chạy torch._dynamo.explain trong CI yêu cầu 0 graph break và khẳng định nạp best_state_dict |
2.6 Mẹo Công nghiệp SOTA 2025–2026: Biên dịch PyTorch 2.x (mark_dynamic), FlexAttention, NVFP4/MXFP4 & An toàn weights_only=True (Principal Industrial Tip #1)#
torch.compile,mark_dynamic& BẫyGraph Break+ Bộ nhớCUDA Graphs: Chế độmode="reduce-overhead"tự động ghi nhận đồ thị thực thi bằngCUDA Graphsđể cắt chi phí CPU kernel launch từ~200 usxuống< 10 uscho suy luận lô nhỏ. Tuy nhiên nó có hai chế độ lỗi chết người: (a) chỉ một lệnh.item(),.cpu(), hay nhánhif x.max() > 0:trongforward()sẽ gây graph break, phá vỡCUDA Graph capturevà chèn đồng bộ CPU–GPU khiến độ trễp99còn tệ hơn cảeagermode; (b) với chuỗi độ dài biến thiên hoặc batch động, trình biên dịch mặc định chuyên biệt hóa kích thước ở lần chạy đầu tiên (static shape specialization), nên mỗi kích thước mới lại kích hoạt biên dịch lại (vượtrecompile_limit = 8và cấp phát pool CUDA Graph mới gây tràn VRAM OOM âm thầm). Quy chuẩn sản xuất: khai báo tường minh chiều động ngay trước biên dịch bằngtorch._dynamo.mark_dynamic(tensor, dim, min=..., max=...)(hoặctorch.export.Dim) để đồ thị theo dõi hình dạng ký hiệu (SymInt) mà không tái biên dịch, kiểm định CI bằngfullgraph=True(TORCH_LOGS="graph_breaks,recompiles"), kết hợp đệm theo nhóm kích thước (bucket padding) hoặcmode="max-autotune-no-cudagraphs"khi hình dạng biến thiên tùy ý.SDPA/FlexAttention& Rơi âm thầm vềMath Fallback: Giao diện chuẩnF.scaled_dot_product_attention(SDPA) tự động chọn nhân dung hợp FlashAttention-2/3 (\(\mathcal{O}(N)\) bộ nhớ HBM) hoặcMemory-Efficient Attention, nhưng nếu vô tình truyềnattn_maskkiểufloattùy biến hoặc sai quy cáchstride/head_dim, PyTorch sẽ âm thầm rơi vềMathbackend (vật liệu hóa ma trận \(N \times N\) trên HBM \(\implies\) sập thông lượng3–6xvà tràn bộ nhớ!). Khi cần mặt nạ chú ý đặc thù (Sliding Window, Document Packing, ALiBi, Soft-Capping), dùngFlexAttention(torch.nn.attention.flex_attentionkết hợpscore_modvàcreate_block_mask): dướitorch.compile,FlexAttentiontự hạ thấp thành nhân Triton/FlashAttention dung hợp theo khối bỏ qua các khối bị che mà không phải cấp phát ma trận mặt nạ dày \(N \times N\), đồng thời vẫn cầnmark_dynamicnếu độ dài chuỗi thay đổi và kiểm soát bằngsdpa_kernel(SDPBackend.FLASH_ATTENTION)trong CI để chặn fallback thầm lặng.- Từ
BF16/FP8đến Lượng tử hóa Vi tỷ lệNVFP4&MXFP4(Blackwell): Trên GPU Hopper/Blackwell,FP8(E4M3xuôi,E5M2ngược) tăng gấp đôi thông lượng Tensor Core so vớiBF16, nhưngDelayed Scaling(dùngamaxbước trước) dễ sụp đổ khi gặp gai kích hoạt (activation spikes) ở lớpSwiGLU. Chuẩn 2025–2026 chuyển sang lượng tử hóa vi tỷ lệ theo khối (Blockwise FP8 1×128 / 128×128,MXFP8) và bước tiến 4-bit thế hệ mớiMXFP4(chuẩn mở OCP Microscaling dùngE2M1với thang mũ chungE8M0cho mỗi khối32phần tử) cùngNVFP4(định dạngE2M1gốc Blackwell dùng khối siêu mịn16phần tử kết hợp thang tỷ lệFP8 E4M3và thang cấp haiFP32để giữ độ chính xác cao hơn khi giảm2×băng thông so vớiFP8). Giới hạn thực chiến:NVFP4/MXFP4đòi hỏi biến đổi Hadamard làm phẳng ngoại lai trước khi lượng tử hóa, tích lũy thanh ghifp32, và bắt buộc giữ cứngBF16/FP32choRMSNorm,Softmax,Router Gating, vàCrossEntropy. - An toàn Nạp Checkpoint với
weights_only=Truevs.safetensors: Hàmtorch.load()truyền thống dựa trênpickletiềm ẩn lỗ hổng thực thi mã tùy ý (RCE/CWE-502) ngay khi nạp tệp trọng số từ nguồn ngoài. Mặc định chuẩn sản xuất 2025–2026 là lưu/nạp định dạngsafetensors(mmapzero-copy,0mã thực thi); nếu bắt buộc đọc tệp.pt/.pthkế thừa, luôn khóa cứngtorch.load(path, map_location="cpu", weights_only=True)(mặc định an toàn từ PyTorch 2.6+) để chỉ giải mã tensor nguyên thủy và từ chối tuyệt đốiweights_only=Falsetrên dữ liệu không tin cậy.
Trụ cột 3 — Ngăn xếp Công nghệ 2026 & Mã Python Thực thi Đầu-Cuối#
3.1 Ngăn xếp Kỹ thuật Học sâu Chuẩn 2026#
- Lõi Huấn luyện & Biên dịch:
PyTorch 2.x(torch.compilevớiTorchDynamo/AOTAutograd/TorchInductortrênTritonGPU hoặcaot_eager/C++ CPU),torch.nn.RMSNorm,torch.utils.checkpoint(use_reentrant=False),torch.amp.autocast("cpu"|"cuda", dtype=torch.bfloat16)vàtorch.optim.Muon(adjust_lr_fn="match_rms_adamw"). - Kỹ nghệ Phần mềm & Hợp đồng Dữ liệu:
Python 3.12+quản lý quauv+pyproject.toml(pytorch-cpuindex tách sạch trên máy phát triển không GPU) +uv.lock; kiểm soát cấu hình bằngPydantic v2(extra="forbid"); kiểm tra chất lượng tĩnh bằngruffvàmypy; không dùng giải tuần tự hóa rủi ro cao (pickle/joblib).
3.2 Ma trận 8 Chống Mẫu Sản xuất & Cổng Kiểm soát Tự động CI/CD#
| # | Chống mẫu (Anti-Pattern) |
Triệu chứng Thất bại Âm thầm | Cổng Kiểm soát Tự động (CI Canary Gate) |
|---|---|---|---|
| 1 | Dùng Xavier cho mạng ReLU sâu hay bỏ qua \(1/\sqrt{2L}\) |
Phương sai sụp 1e-06 hoặc bùng nổ 7.86e+11 ở \(L=20\) |
Kiểm tra dải phương sai \([0.2, 5.0]\) qua các tầng tại epoch 0 |
| 2 | Quên model.eval() hoặc giữ BatchNorm khi B <= 2 |
BatchNorm sập \(\pm 1\) (B=2), ValueError (B=1), trôi running_mean |
Khẳng định bất biến B=1 vs B=32 (< 1e-5) và running_mean không đổi |
| 3 | Dùng torch.optim.Adam(..., weight_decay>0) hay decay cho 1D |
Lệch co ngót 2.97x, trôi RMSNorm, tụt độ chính xác 44.7% |
Quét optimizer.param_groups cấm Adam ghép \(L_2\) và buộc 1D decay == 0.0 |
| 4 | Bỏ Warmup hoặc quên load_state_dict(best_state_dict) |
Bùng nổ v_hat bước đầu hoặc triển khai trọng số sau patience (1.707 vs 1.616) |
Cổng kiểm tra tỷ lệ T_w > 0 và khẳng định restored_val == min(val_trace) |
| 5 | Dùng fp16 không scaler hoặc bf16 không có trọng số chủ fp32 |
1e-8 -> 0.0, 70000 -> inf hoặc cập nhật nhỏ đóng băng ở 0.0 |
Kiểm định fp32 master copy và khẳng định isfinite(loss) & isfinite(grad) |
| 6 | Thay .view() bằng .reshape() trên tensor transpose() |
Âm thầm cấp phát bản sao HBM gấp đôi bộ nhớ và rớt hiệu năng bộ nhớ đệm | Kiểm tra untyped_storage().data_ptr() và gọi .contiguous() có chủ đích |
| 7 | Ghi tại chỗ h[:, :2] = 0 hay sửa .data trong luồng autograd |
Đụng bộ đếm _version nổ .backward() hoặc sai lệch đạo hàm im lặng |
Chạy central_diff_grad_check (fp64 < 1e-6) và cấm chỉnh sửa .data |
| 8 | Đặt .item() hoặc if tensor.sum() > 0 bên trong forward() |
Sinh TorchDynamo graph break, đồng bộ CPU–GPU, phá dung hợp HBM |
Chạy torch._dynamo.explain & torch.compile(..., fullgraph=True) buộc 0 break |
3.3 Mã Python Thực thi Đầu-Cuối (PyTorch 2.15.0+cpu, Đã Chạy Kiểm chứng)#
Đoạn mã hoàn chỉnh dưới đây tự chạy độc lập trên môi trường .venv (seed=42, ruff 0 lỗi, mypy 0 lỗi), tích hợp cùng lúc: mạng Pre-Norm (RMSNorm giảm chiều fp32 + SwiGLU \(d_{\text{ff}}=\frac{8}{3}d\) + tỷ lệ thặng dư \(1/\sqrt{2L}\)), bộ tối ưu lai HybridMuonAdamW (torch.optim.Muon cho ma trận 2D khối ẩn + torch.optim.AdamW tách nhóm cho 1D/đầu vào/head), torch.autocast("cpu", dtype=torch.bfloat16), Warmup + Cosine, Early Stopping khôi phục best_state_dict, và 4 kiểm toán Canary (BatchNorm B=2, fp16 vs bf16, .reshape() copy pointer, và torch._dynamo.explain + aot_eager):
from __future__ import annotations
import copy
import math
from typing import Any
import torch
import torch.nn.functional as F
from torch import nn
class SwiGLUFFN(nn.Module):
"""Parameter-matched SwiGLU block: d_ff = 2/3 * 4d -> 3*d*d_ff = 8*d^2."""
def __init__(self, d_model: int, d_ff: int) -> None:
super().__init__()
self.w_gate = nn.Linear(d_model, d_ff, bias=False)
self.w_up = nn.Linear(d_model, d_ff, bias=False)
self.w_down = nn.Linear(d_ff, d_model, bias=False)
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.w_down(F.silu(self.w_gate(x)) * self.w_up(x))
class PreNormBlock(nn.Module):
"""Single Pre-Norm RMSNorm + SwiGLU block with 1/sqrt(2L) residual scaling."""
def __init__(self, d_model: int, d_ff: int, res_scale: float) -> None:
super().__init__()
self.norm = nn.RMSNorm(d_model)
self.ffn = SwiGLUFFN(d_model, d_ff)
nn.init.kaiming_normal_(self.ffn.w_gate.weight, nonlinearity="relu")
nn.init.kaiming_normal_(self.ffn.w_up.weight, nonlinearity="relu")
nn.init.kaiming_normal_(self.ffn.w_down.weight, nonlinearity="relu")
with torch.no_grad():
self.ffn.w_down.weight.mul_(res_scale)
def forward(self, x: torch.Tensor) -> torch.Tensor:
normed = self.norm(x.float()).to(x.dtype)
return x + self.ffn(normed)
class PreNormMLP(nn.Module):
"""Pre-Norm RMSNorm + SwiGLU network with 1/sqrt(2L) residual output scaling."""
def __init__(self, d_in: int, d_model: int, n_blocks: int, n_classes: int) -> None:
super().__init__()
self.proj_in = nn.Linear(d_in, d_model)
d_ff = max(8, (2 * 4 * d_model) // 3)
res_scale = 1.0 / math.sqrt(2.0 * n_blocks)
self.blocks = nn.ModuleList(
[PreNormBlock(d_model, d_ff, res_scale) for _ in range(n_blocks)]
)
self.norm_out = nn.RMSNorm(d_model)
self.head = nn.Linear(d_model, n_classes)
def forward(self, x: torch.Tensor) -> torch.Tensor:
h = self.proj_in(x)
for blk in self.blocks:
h = blk(h)
return self.head(self.norm_out(h.float()).to(h.dtype))
def build_hybrid_muon_adamw(
model: PreNormMLP,
lr: float = 0.02,
weight_decay: float = 0.02,
) -> tuple[torch.optim.Muon, torch.optim.AdamW]:
"""Route 2D hidden block matrices to Muon; 1D norms, biases & input/head to AdamW."""
muon_params: list[torch.nn.Parameter] = []
adamw_decay: list[torch.nn.Parameter] = []
adamw_nodecay: list[torch.nn.Parameter] = []
for name, p in model.named_parameters():
if not p.requires_grad:
continue
if p.ndim == 2 and "blocks." in name:
muon_params.append(p)
elif p.ndim >= 2:
adamw_decay.append(p)
else:
adamw_nodecay.append(p)
opt_muon = torch.optim.Muon(
muon_params,
lr=lr,
weight_decay=weight_decay,
momentum=0.95,
nesterov=True,
adjust_lr_fn="match_rms_adamw",
)
opt_adamw = torch.optim.AdamW(
[
{"params": adamw_decay, "weight_decay": weight_decay},
{"params": adamw_nodecay, "weight_decay": 0.0},
],
lr=lr * 0.5,
)
return opt_muon, opt_adamw
def run_pillar3_specimen(seed: int = 42) -> dict[str, Any]:
torch.manual_seed(seed)
n_samples, d_in, n_classes = 640, 8, 4
x = torch.randn(n_samples, d_in)
scores = torch.stack(
[
2.2 * torch.sin(x[:, 0]) + 1.5 * (x[:, 1] * x[:, 2]),
2.2 * torch.cos(x[:, 3]) - 1.4 * (x[:, 4] ** 2),
2.0 * torch.tanh(x[:, 5] + x[:, 6]) + 1.2 * x[:, 0],
-1.8 * x[:, 7] + 2.0 * torch.relu(x[:, 2] - x[:, 4]),
],
dim=1,
)
y = scores.argmax(dim=1)
x_tr, y_tr = x[:448], y[:448]
x_va, y_va = x[448:], y[448:]
model = PreNormMLP(d_in=d_in, d_model=32, n_blocks=2, n_classes=n_classes)
opt_muon, opt_adamw = build_hybrid_muon_adamw(model, lr=0.02, weight_decay=0.02)
total_epochs, warmup_epochs, patience = 70, 6, 8
best_val_loss = float("inf")
best_state = copy.deepcopy(model.state_dict())
stale_epochs = 0
final_val_loss = float("inf")
for epoch in range(1, total_epochs + 1):
if epoch <= warmup_epochs:
lr_mult = epoch / warmup_epochs
else:
progress = (epoch - warmup_epochs) / max(1, total_epochs - warmup_epochs)
lr_mult = 0.1 + 0.9 * 0.5 * (1.0 + math.cos(math.pi * progress))
for pg in opt_muon.param_groups:
pg["lr"] = 0.02 * lr_mult
for pg in opt_adamw.param_groups:
pg["lr"] = 0.01 * lr_mult
model.train()
opt_muon.zero_grad(set_to_none=True)
opt_adamw.zero_grad(set_to_none=True)
with torch.autocast(device_type="cpu", dtype=torch.bfloat16):
logits_tr = model(x_tr)
loss_tr = F.cross_entropy(logits_tr.float(), y_tr, label_smoothing=0.05)
loss_tr.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
opt_muon.step()
opt_adamw.step()
model.eval()
with torch.inference_mode():
logits_va = model(x_va)
val_loss = float(F.cross_entropy(logits_va, y_va).item())
final_val_loss = val_loss
if val_loss < best_val_loss - 1e-4:
best_val_loss = val_loss
best_state = copy.deepcopy(model.state_dict())
stale_epochs = 0
else:
stale_epochs += 1
if stale_epochs >= patience:
break
model.load_state_dict(best_state)
model.eval()
with torch.inference_mode():
logits_restored = model(x_va)
restored_val_loss = float(F.cross_entropy(logits_restored, y_va).item())
restored_val_acc = float((logits_restored.argmax(dim=1) == y_va).float().mean().item())
b1_out = model(x_va[:1])
b32_out = model(x_va[:1].repeat(32, 1))
eval_b1_b32_diff = float((b1_out - b32_out[:1]).abs().max().item())
bn2 = nn.BatchNorm1d(8, eps=1e-8)
bn2.train()
bn_out = bn2(torch.randn(2, 8) * 3.0 + 1.5)
bn_b2_abs_dev = float((bn_out.abs() - 1.0).abs().max().item())
fp16_tiny = float(torch.tensor([1e-8], dtype=torch.float16).item())
bf16_tiny = float(torch.tensor([1e-8], dtype=torch.bfloat16).item())
fp16_big_inf = bool(torch.isinf(torch.tensor([70000.0], dtype=torch.float16)).item())
t_mat = torch.randn(16, 32)
reshape_ptr_changed = (
t_mat.t().reshape(-1).untyped_storage().data_ptr()
!= t_mat.untyped_storage().data_ptr()
)
clean_exp = torch._dynamo.explain(model)(x_va[:4])
class BrokenControlFlow(nn.Module):
def forward(self, z: torch.Tensor) -> torch.Tensor:
if z.sum().item() > 0.0:
return z * 2.0
return z * 0.5
broken_exp = torch._dynamo.explain(BrokenControlFlow())(x_va[:4])
compiled_model = torch.compile(model, backend="aot_eager", fullgraph=True)
with torch.inference_mode():
compile_diff = float((compiled_model(x_va[:4]) - model(x_va[:4])).abs().max().item())
return {
"best_val_loss": best_val_loss,
"final_val_loss": final_val_loss,
"restored_val_loss": restored_val_loss,
"restored_val_acc": restored_val_acc,
"eval_b1_b32_diff": eval_b1_b32_diff,
"bn_b2_abs_dev": bn_b2_abs_dev,
"fp16_tiny": fp16_tiny,
"bf16_tiny": bf16_tiny,
"fp16_big_inf": fp16_big_inf,
"reshape_ptr_changed": reshape_ptr_changed,
"clean_graph_breaks": int(clean_exp.graph_break_count),
"broken_graph_breaks": int(broken_exp.graph_break_count),
"compile_diff": compile_diff,
}
if __name__ == "__main__":
out = run_pillar3_specimen(seed=42)
print(
f"ValLoss(final={out['final_val_loss']:.4f}->restored={out['restored_val_loss']:.4f}, "
f"acc={out['restored_val_acc']:.1%}) | Eval_B1_vs_B32_diff={out['eval_b1_b32_diff']:.2e} | "
f"BN_B2_dev_from_1={out['bn_b2_abs_dev']:.2e} | fp16(1e-8)={out['fp16_tiny']:.1e} "
f"bf16(1e-8)={out['bf16_tiny']:.2e} fp16_70k_inf={out['fp16_big_inf']} | "
f"ReshapeCopy={out['reshape_ptr_changed']} | DynamoBreaks(clean={out['clean_graph_breaks']},"
f"broken={out['broken_graph_breaks']}) | CompileDiff={out['compile_diff']:.2e}"
)
Khi thực thi trực tiếp trên Python 3.12.16 + torch 2.15.0+cpu (seed=42, exit 0), kết quả xác thực ghi nhận:
ValLoss(final=0.5669->restored=0.5012, acc=80.7%) | Eval_B1_vs_B32_diff=7.15e-07 | BN_B2_dev_from_1=1.19e-07 | fp16(1e-8)=0.0e+00 bf16(1e-8)=1.00e-08 fp16_70k_inf=True | ReshapeCopy=True | DynamoBreaks(clean=0,broken=1) | CompileDiff=0.00e+00
Trụ cột 4 — Phòng thí nghiệm Thực chiến Hai Tầng WB-Ch14 (nn_pytorch_lab)#
Bàn thực hành WB-Ch14 (nn_pytorch_lab) tại hướng dẫn Workbench Ch 14 triển khai trọn vẹn kiến trúc Hai Tầng trên môi trường PyTorch 2.15.0+cpu:
- Tầng 1 Thuần Python/NumPy (
src/nn_pytorch_lab/autograd_core.py): Hoàn toàn không nhậptorch, cài đặt 6 cấu hìnhPydantic v2(extra="forbid"), bộ máyTapeTensorchế độ ngượcfloat64(MatMul,Add,Sub,Mul,Sum,Mean,ReLU,GELU,SiLU,SwiGLU,RMSNorm,LayerNorm,LSE CrossEntropy), kiểm tra sai phân trung tâmcentral_diff_grad_check, sóng tam giác Telgarsky, lan truyền phương sai 20 tầng (benchmark_deep_init_propagation), cân bằngSwiGLU, chứng minh lỗiAdamghép \(L_2\) so vớiAdamW, trực giao hóazeropower_via_newtonschulz5(NS_5) + tỷ lệMoonlight, mô phỏng Checkpointing \(O(\sqrt{L})\) và Roofline HBM Fusion. - Tầng 2 Thực thi
PyTorch 2.15.0+cpu(src/nn_pytorch_lab/pytorch_training_lab.py): Cài đặtSwiGLUFFN+PreNormResidualBlock, đối chiếu khớp số họcfloat64với Tầng 1, kiểm toán sụp đổBatchNormtạiB=1, 2và quêneval(), đấu trường 4 bộ tối ưu (SGD+Momentum,Adamghép \(L_2\),AdamWtách nhómWarmup+Cosine,HybridMuonAdamW), kiểm chứngDropout/Label Smoothing/MixUp/CutMix, khôi phụcbest_state_dict, bẫyfp16/bf16ULP +torch.autocast("cpu", dtype=torch.bfloat16), giải phẫustride/_version/inference_mode(), cùngtorch._dynamo.explainvàtorch.compile(..., backend="aot_eager", fullgraph=True).
4.1 Lệnh Thực thi & Xác minh Chuẩn trong WB-Ch14#
cd 02-track-1-data-science-and-ai/part-03-deep-learning-and-modern-cv/labs/ch14-neural-networks-and-pytorch-workbench
D:\FSDS-SOTA-Curriculum\.venv\Scripts\python.exe scripts/run_lab_demo.py --seed 42 --output artifacts/ch14_wb14_results.json
D:\FSDS-SOTA-Curriculum\.venv\Scripts\ruff.exe check src scripts tests
D:\FSDS-SOTA-Curriculum\.venv\Scripts\mypy.exe src
D:\FSDS-SOTA-Curriculum\.venv\Scripts\pytest.exe -p no:cacheprovider -v
4.2 Kết quả Thực nghiệm Cốt lõi (artifacts/ch14_wb14_results.json, --seed 42)#
Bảng A — 6 KPI Cổng Nghiệm thu Toàn hệ thống (workbench_panels)#
| Chỉ số Cổng Nghiệm thu | Giá trị Đối chuẩn (Baseline / Lỗi) |
Giá trị Chuẩn hóa (WB-Ch14 SOTA) |
Ngưỡng Nghiệm thu | Trạng thái |
|---|---|---|---|---|
Khớp Autograd Tầng 1 vs PyTorch |
Sai phân trung tâm 2.12e-10 |
9.71e-17 (loss_diff = 2.22e-16) |
< 1e-5 |
Đạt |
Truyền Tín hiệu L=20 & 1/sqrt(2L) |
Xavier = 1.02e-06 (naive = 1.49e-38 / 7.86e+11) |
1.59x (PreNorm), 1.07x (Kaiming) |
Trong dải [0.2, 5.0] |
Đạt |
Sụp đổ BatchNorm B=2 vs RMSNorm |
BN B=2 ép \(\pm 1\) (2.38e-07, var = 0.509) |
0.0 sai khác B=1 vs B=32 (RMS scale 4.77e-07) |
Bất biến B=1 |
Đạt |
AdamW Tách nhóm & Muon NS_5 |
Adam ghép \(L_2\): 2.97x, 44.7% (1.194) |
AdamW: 3.02e-08 (91.2%); Muon: 88.3% ([0.682, 1.134]) |
val_acc >= 85% |
Đạt |
Vật lý fp16/bf16 & Bộ nhớ 16*Psi |
fp16: 1e-8 -> 0.0, 7e4 -> inf; bf16 thuần: 0.0 |
112.0 GB tĩnh @ 7B; fp32 master -0.0100 |
Không đóng băng/tràn | Đạt |
TorchDynamo & Roofline HBM Fusion |
.item() tạo 1 break; gemm_b1 = 1.0 FLOP/B |
0 graph break (aot_eager 0.0); HBM cắt 57.1% / 71.4% |
== 0 break |
Đạt |
Bảng B — Chi tiết Cắt bỏ Thành phần Thành phần Chuyên sâu (seed=42)#
| Thí nghiệm Thành phần | Cấu hình / Phương pháp | Số đo Ghi nhận Chính xác (artifacts/ch14_wb14_results.json) |
Kết luận Kỹ thuật |
|---|---|---|---|
Tách sâu Telgarsky & SwiGLU |
\(\phi_k\) (\(k=5\)) vs Depth-2 / SwiGLU (\(d=4096\)) |
32 đoạn tuyến tính (16 đỉnh); \(m=8\) LB 0.344 > 0.25 (thực 0.491); d_ff chuẩn 10,922.67 (1.0x), căn 256 11,008 (+0.78%) |
Độ sâu tăng khả năng biểu diễn theo hàm mũ; SwiGLU cân bằng tham số tại \(\frac{8}{3}d\) |
| Đấu trường Tối ưu & Điều chuẩn | SGD+M / Adam L2 / AdamW / HybridMuonAdamW + Reg |
SGD+M: 0.365 (87.3%); Adam L2: 1.194 (44.7%, norm drift 0.988); AdamW: 0.441 (91.2%); Muon: 0.580 (88.3%, RMS ~0.172); Label Smooth margin 2.16 vs 7.75; CutMix = 0.8125 |
Tách nhóm 1D decay=0.0 và giới hạn Muon trên 2D ẩn là điều kiện tiên quyết |
Dừng sớm (Early Stopping) |
patience=0 / final vs best_state_dict |
patience=0 @epoch 2 (1.694); best_epoch=7 (1.624); stop=12 (1.659); khôi phục 0.0 sai lệch, test_loss 1.707 -> 1.616 |
Bắt buộc sao lưu và gọi load_state_dict(best_state_dict) trước triển khai |
Checkpointing, Roofline & PyTorch 2.x |
L=32/L=64, H100 I*=295.2, xt stride, Dynamo |
L=64: -75.0% RAM (+33.33% FLOP), SAC: -72.0% (+4.0%); RMSNorm 0.36 -> 1.25 (-71.4%), SwiGLU 0.31 -> 0.83 (-62.5%), gemm_large = 682.7; _version 0 -> 1; ckpt grad diff = 0.0 |
Checkpointing chọn lọc + torch.compile giải quyết đồng thời hai rào cản VRAM và HBM |
4.3 Hợp đồng 16 Bài kiểm thử Tự động (tests/test_nn_pytorch_lab.py)#
| STT | Tên hàm kiểm thử Pytest |
Bất biến & Ngưỡng Nghiệm thu Bắt buộc (CPU-Only, 0 Skips) |
|---|---|---|
1 |
test_01_pydantic_configs_strict_forbid |
Từ chối trường lạ (extra="forbid") và chặn miền sai trên cả 6 cấu hình Pydantic v2 |
2 |
test_02_numpy_autograd_microengine_central_diff_gradcheck |
Khẳng định TapeTensor (RMSNorm + SwiGLU + GELU + LSE) khớp sai phân trung tâm < 1e-6 |
3 |
test_03_tier1_numpy_vs_torch_autograd_exact_parity |
Khớp float64 giữa Tầng 1 và torch.autograd (loss_diff < 1e-8, grad_diff < 1e-5) |
4 |
test_04_deep_l20_init_variance_and_prenorm_residual_scaling |
xavier/naive_small < 1e-4, naive_large > 1e3, kaiming & Pre-Norm 1/sqrt(2L) trong [0.2, 5.0] |
5 |
test_05_telgarsky_triangle_wave_exponential_pieces_and_swiglu_parity |
Xác minh \(2^k\) đoạn của \(\phi_k\), cận dưới > 0.25 tại \(m=8\) và cân bằng SwiGLU \(\frac{8}{3}d\) |
6 |
test_06_batchnorm_b2_collapse_and_eval_trap_vs_layernorm_rmsnorm |
BN B=1 báo ValueError, B=2 ép \(\pm 1\) (< 1e-4), quên eval() trôi buffer; LN/RMSNorm bất biến B=1 |
7 |
test_07_lse_crossentropy_stability_and_optimizer_adam_coupled_bug |
LSE hữu hạn tại [-1e4, +1e4]; Adam ghép \(L_2\) lệch > 1.5x vs AdamW < 1e-5 |
8 |
test_08_muon_newton_schulz5_and_moonlight_rms_invariance |
NS_5 nén [0.01, 1.0] vào [0.68, 1.14] và Moonlight giữ Update RMS đồng nhất [0.12, 0.28]*lr |
9 |
test_09_pytorch_training_arena_adamw_hybrid_muon_warmup_cosine |
Khẳng định 1D decay == 0.0, AdamW và HybridMuonAdamW hội tụ đạt val_acc >= 0.85 |
10 |
test_10_regularization_dropout_label_smoothing_mixup_cutmix |
Khẳng định Dropout không chệch/eval() định danh, Label Smoothing chặn margin, CutMix khớp \(\lambda_{\text{mix}}\) |
11 |
test_11_early_stopping_patience_and_best_state_dict_restoration |
Khẳng định patience=0 dừng sớm sai, final > best, và rollback khôi phục khớp < 1e-12 |
12 |
test_12_mixed_precision_fp16_underflow_bf16_stagnation_and_cpu_autocast |
Tái hiện xóa/tràn fp16, đóng băng bf16 không master vs fp32, và chạy torch.autocast("cpu", torch.bfloat16) |
13 |
test_13_gradient_checkpointing_memory_and_torch_checkpoint_parity |
Khẳng định sqrt_uniform cắt >= 70% bộ nhớ tại L=64 (+33.33% FLOPs) và khớp torch.utils.checkpoint |
14 |
test_14_roofline_intensity_and_fusion_byte_savings |
Khẳng định 16*Psi = 112 GB, vị trí dưới/trên điểm gãy H100/A100, và mức cắt HBM 57.14%/71.43% |
15 |
test_15_tensor_strides_view_reshape_version_trap_and_dynamo_explain |
Khẳng định view/reshape pointer, bẫy _version, inference_mode(), 0 break vs .item() và aot_eager |
16 |
test_16_cli_demo_workbench_json_schema_and_ast_deserialization_guard |
Chạy run_lab_demo.py --quick, xác thực 6 KPI, 4 bar, 4 bảng và AST cấm giải tuần tự hóa rủi ro |
Trụ cột 5 — Văn liệu Nền tảng & SOTA (2015–2026), Ôn tập & Thang chấm Rubric#
5.1 Sáu Công trình Học thuật Nền tảng & SOTA (2015–2026)#
- He, K., Zhang, X., Ren, S., & Sun, J. (2015). Delving Deep into Rectifiers: Surpassing Human-Level Performance on ImageNet Classification. ICCV 2015. (Chứng minh hệ số phương sai
2/n_inbù sự cắt nửa âm củaReLU.) - Telgarsky, M. (2016). Benefits of depth in neural networks. COLT 2016 (
PMLR 49:1517–1539). (Chứng minh định lý tách sâu hàm mũ qua sóng tam giác \(\phi_k\) có \(2^k\) đoạn tuyến tính.) - Loshchilov, I., & Hutter, F. (2019). Decoupled Weight Decay Regularization. ICLR 2019 (
arXiv:1711.05101). (Phát hiện lỗi ghép \(L_2\) trongAdamvà đề xuấtAdamWtách rời.) - Zhang, B., & Sennrich, R. (2019). Root Mean Square Layer Normalization. NeurIPS 2019 (
arXiv:1910.07467). (Đề xuấtRMSNormloại bỏ dịch trung bình, giảm giảm chiều HBM và giữ bất biến co giãn.) - Shazeer, N. (2020). GLU Variants Improve Transformer.
arXiv:2002.05202. (Đề xuấtSwiGLU/GeGLUkèm quy tắc \(d_{\text{ff}} = \frac{2}{3} \cdot 4d\) cân bằng tham số.) - Ansel, J., Yang, E., He, H., et al. (2024) & Jordan, K. (2024) / Liu, J., et al. (2025). PyTorch 2: Faster Machine Learning Through Dynamic Python Bytecode Transformation and Graph Compilation (ASPLOS 2024) & Muon / Moonlight: Muon is Scalable for LLM Training (
arXiv:2502.16982). (Kiến trúcTorchDynamo -> AOTAutograd -> TorchInductorđạt tăng tốc2.27xvà phép lặpNS_5+ tỷ lệMoonlighttiết kiệm ~50% FLOPs huấn luyện.)
5.2 Tám Câu hỏi Trắc nghiệm Kiểm tra Nhanh (Q1..Q8 — Khớp quiz_and_hints.json)#
Q1(UATvsTelgarsky):UATbảo đảm trù mật khi \(\phi\) không là đa thức, còn sóng tam giác \(\phi_k\) (\(\mathcal{O}(k)\) tham số) tạo \(2^k\) đoạn (k=5 -> 32đoạn) buộc mạng sâu 2 tầng cần bề rộng \(\Omega(2^k)\) (m=8chịu cận dưới0.344).Q2(XaviervsKaiming& \(1/\sqrt{2L}\)):ReLUcắt nửa âm (\(\mathbb{E}[\operatorname{ReLU}(z)^2]=\frac{1}{2}\sigma_z^2\)) nênXaviersụp xuống1.02e-06ở \(L=20\), trong khiKaiming(1.07x) vàPre-Norm\(1/\sqrt{2L}\) (1.59x,L1 grad = 1.25) giữ ổn định \(\mathcal{O}(1)\).Q3(SwiGLU&BatchNorm B=2vsRMSNorm):SwiGLUkhớp8d^2tham số tại \(d_{\text{ff}} = \frac{8}{3}d\) (11,008cho \(d=4096\));BatchNormtạiB=2lượng tử hóa về \(\pm 1\) (lệch 2.4e-07,var=0.51) và hỏng nếu thiếueval(), cònRMSNormgiữ sai khácB=1vsB=32bằng0.0.Q4(PyTorch 2.xStride,_version,inference_mode):x.t().view(-1)văngRuntimeError,x.t().reshape(-1)cấp phát bản sao mới mất liên kếtdata_ptr(), ghi tại chỗh[:, :2] = 0tăng_version(0 -> 1) gây sập.backward(), còninference_mode()tắt luôn theo dõi_version.Q5(TorchDynamo& Roofline Fusion):.item()sinh1graph break phá dung hợpTorchInductor; dung hợp nhân đưaRMSNorm(0.36 -> 1.25,-71.4%HBM) vàBias+GELU+Res(-57.1%HBM) tiến gần điểm gãy H100 \(I^*=295.2\), trong khigemm_large_batch(682.7) vượt hẳn vào vùngcompute-bound.Q6(Mixed Precision16*Psi& Checkpointing):fp16xóa1e-8 -> 0.0và tràn70000 -> inf;bf16thuần đóng băng cập nhật nhỏ trừ phi có trọng số chủfp32trong16*Psi = 112 GB @ 7B; Checkpointing \(\sqrt{L}\) cắt75.0%RAM kích hoạt tạiL=64với+33.33%FLOPs (SACchỉ+4.0%).Q7(Adamghép \(L_2\) vsAdamW&Muon):Adamghép \(L_2\) lệch tỷ số2.97x(tụt xuống44.7%), cònAdamWtách nhóm giữ lệch3.0e-08(91.2%);MuondùngNS_5([0.682, 1.134]) +Moonlightchỉ cho ma trận2Dẩn (88.3%), chừa1D/embedding/headchoAdamW.Q8(Điều chuẩn &Early Stopping):patience=0dừng non ở epoch2, triển khai trọng số cuối ở epoch12(1.659) làm xấutest_loss(1.616 -> 1.707), buộc phải gọiload_state_dict(best_state_dict)khôi phục epoch7(1.624) dướimodel.eval().
5.3 Sáu Bài tập Lập trình & Chứng minh Trọng số (Bài tập 1..6)#
-
Bài tập 1 (
15%) — Chứng minh Tách sâu Lũy thừa Telgarsky (Telgarsky 2016) & Cân bằng Tham sốSwiGLU:Chứng minh quy nạp \(\phi_k\) có \(2^k\) đoạn tuyến tính và cận dưới bất đồng phân loại \(\frac{1}{2}(1 - \frac{m+2}{2^k})\) cho mạng 2 lớp rộng \(m\); suy ra \(d_{\text{ff}} = \frac{8}{3}d\) cho
SwiGLUvà đối chứng quatelgarsky_triangle_wave,benchmark_telgarsky_depth_separationvàaudit_swiglu_param_flop_parity. -
Bài tập 2 (
15%) — Dẫn xuất Phương sai Khởi tạo (Xavier/Kaiming), Tỷ lệ \(1/\sqrt{2L}\) & Sụp đổBatchNorm B=2:Chứng minh \(\mathbb{E}[\operatorname{ReLU}(z)^2]=\frac{1}{2}\sigma_z^2\), công thức
XaviervsKaiming, cận \(e^{\nu^2}\) củaPre-Norm\(1/\sqrt{2L}\) và sụp đổ lượng tử \(\pm 1\) củaBatchNormtạiB=2; đối chứng bằngbenchmark_deep_init_propagationvàaudit_batchnorm_collapse_and_eval_mode. -
Bài tập 3 (
20%) — Xây dựng Động cơ Autodiff Ngược (TapeTensor), Sai phân Trung tâm & Kiểm toánAdamvsMuon NS_5:Cài đặt và chứng minh
TapeTensor(MatMul,SwiGLU,RMSNorm,LSE CrossEntropy) khớp sai phân trung tâm (< 1e-6) vàtorch.autograd(< 1e-5), chứng minh sai lệch \(1/\sqrt{\hat{v}_t}\) củaAdamghép \(L_2\), và chạyaudit_muon_ns5_spectrum+benchmark_optimizers_arena. -
Bài tập 4 (
20%) — Chứng minh Checkpointing \(O(\sqrt{L})\) (+33.3%FLOPs), Bẫyfp16/bf16ULP & Roofline Fusion:Cực tiểu hóa \(M(k) = m_{\text{act}}(k + L/k)\) thu \(k^*=\sqrt{L}\) và
+33.33%FLOPs, kiểm toán16*Psi = 112 GB, tính mức cắt giảm HBM củaBias+GELU+Res(-57.14%) &RMSNorm(-71.43%), tái hiện lỗifp16/bf16và đối chiếutorch.utils.checkpoint. -
Bài tập 5 (
15%) — Gỡ lỗi Nội tạiPyTorch 2.x:Stride/view/reshape,_version&TorchDynamoGraph Breaks:Chẩn đoán lỗi sao chép ngầm
xt.reshape(-1), bẫy đột biếnh[:, :2] = 0vàinference_mode(), truy vết graph break bằngtorch._dynamo.explain, tái cấu trúc về0break và xác nhậntorch.compile(..., backend="aot_eager", fullgraph=True). -
Bài tập 6 (
15%) — Điều chuẩn (Dropout,Label Smoothing,CutMix), Dừng sớmbest_state_dict&16/16 Pytest:Chứng minh khoảng cách logit tối ưu của
Label Smoothing, tỷ lệ \(\lambda_{\text{mix}}\) củaCutMix, thiết kếEarlyStoppingkhôi phụcbest_state_dict(1.624,restore_diff = 0.0) và xác nhận đạt trọn bộruff,mypy,pytest(16/16) cùngscripts/run_lab_demo.py.
5.4 Thang chấm Rubric (UCL MSc Grading Rubric)#
| Cấp độ Đạt chuẩn | Tiêu chí Chứng minh & Lý thuyết (Trụ cột 1 & 2) | Tiêu chí Hệ thống & Thực nghiệm WB-Ch14 (nn_pytorch_lab) |
|---|---|---|
Principal / MSc Distinction (>= 85%) |
Chứng minh trọn vẹn quy nạp \(\phi_k\), hệ số 1/2 Kaiming và ổn định \(e^{\nu^2}\) với \(1/\sqrt{2L}\), sụp đổ BN B=2, tối ưu Checkpoint \(k^*=\sqrt{L}\) (+33.3%), lỗi ghép \(L_2\) Adam, NS_5 + Moonlight và tính đúng Roofline \(I\) vs \(I^*\); giữ nhất quán ký hiệu ch-02/ch-03/ch-14 |
Đạt trọn vẹn 16/16 pytest (0 skips, 0 lỗi ruff/mypy), TapeTensor khớp torch.autograd (< 1e-5), tái hiện BN B=2, cứu bf16 ULP, khôi phục best_state_dict, dẹp 0 graph break qua torch._dynamo.explain & xuất chuẩn ch14_wb14_results.json |
Senior / Đạt chuẩn (70% – 84%) |
Nắm vững quy tắc Xavier/Kaiming, SwiGLU \(\frac{8}{3}d\), RMSNorm vs BatchNorm, AdamW vs Adam, 16*Psi và torch.compile/bf16, nhưng thiếu bước giải cực trị \(k^*=\sqrt{L}\), gap logit Label Smoothing hoặc tính byte HBM sau dung hợp |
Chạy thông suốt run_lab_demo.py và qua phần lớn kiểm thử, nhưng thiếu đối chiếu float64 gradcheck hoặc bỏ sót kiểm tra 1D weight_decay=0.0 / khôi phục best_state_dict |
Cần khắc phục (< 70%) |
Dùng Xavier cho ReLU sâu hoặc quên \(1/\sqrt{2L}\); giữ BatchNorm khi B=2 hoặc quên model.eval(); đánh đồng Adam ghép \(L_2\) với AdamW; hoặc để .item() / if gây graph break trong forward() |
Không khớp đạo hàm Tầng 1 vs torch.autograd, để rò đột biến _version, triển khai trọng số sau patience thay vì best_state_dict, hoặc thất bại bộ pytest WB-Ch14 |
L=20 Signal Variance Drift |log10(Var_L / Var_0)| (Lower is Better)
Pre-Norm SwiGLU Optimizer Arena Validation Loss (Lower is Better)
Activation Memory vs Recompute Overhead at L=32 (% of Full Tape / Step)
Roofline Arithmetic Intensity I (FLOP/B) Before vs After TorchInductor Fusion
Signal Propagation (L=20), Normalization Collapse & Telgarsky Depth Separation
| Regime / Norm | Layer-20 Fwd Var | Grad / B=2 Behavior | Status |
|---|---|---|---|
| Xavier on ReLU (L=20) | 1.02e-06 | L1 grad 8.03e-04 | VANISH (0.5^20) |
| Kaiming + PreNorm 1/sqrt(2L) | 1.07x | 1.59x | L1 grad 1.25 | O(1) STABLE |
| BatchNorm1d (B=2 / No eval) | Var bias 0.51 | +-1 dev 2.4e-07 | COLLAPSE |
| Telgarsky k=5 vs Depth-2 | 32 pieces | m=8 LB 0.344 > 0.25 | EXP DEPTH GAP |
Optimizer Preconditioning, Regularization & Early Stopping Rollback
| Optimizer / Stopping | Val Loss | Param Group / Decay Rule | Verdict |
|---|---|---|---|
| Coupled L2 Adam | 1.194 | Skew ratio 2.97x | norm drift 0.99 | NON-UNIFORM BUG |
| Split AdamW + WarmupCosine | 0.441 | 1D decay=0.0 | diff 3.0e-08 | PASS (91.2%) |
| HybridMuonAdamW (NS5+Moonlight) | 0.580 | NS5 [0.682,1.134] | PASS (88.3%) |
| EarlyStop Restore (t*=7) | 1.624 (final 1.659) | p=0 stop @2 (1.694) | RESTORE diff 0.0e+00 |
Mixed-Precision Bit Physics, 16*Psi VRAM & Checkpointing Budget
| Format / Strategy | 7B Static + Act | Extra FLOPs / ULP | Numerical Safety |
|---|---|---|---|
| fp16 (1-5-10, max 65504) | 112 GB static (with master) | 1e-8 -> 0.0 | 70000 -> inf | NEEDS GradScaler |
| Pure bf16 (No fp32 master) | 14 GB weights only | 100x(-1e-4) -> 0.0 | ULP STAGNATION |
| bf16 Compute + fp32 Master | 112 GB + 42.9 GB act | Master delta -0.0100 | SOTA DEFAULT |
| Sqrt Checkpointing (L=64) | -75.0% activation mem | +33.33% FLOPs (SAC 4.0%) | O(sqrt(L)) SAFE |
PyTorch 2.x Tensor Strides, _version Guard, TorchDynamo & Roofline
| Audit Gate | Observed Metric | Failure Trap | CI Canary Result |
|---|---|---|---|
| Strided View vs Reshape | xt stride [1, 64] | xt.view(-1) RuntimeError; reshape copies | ALIAS CHECKED |
| Autograd _version & Inference | v0=0 -> v1=1 | h[:,:2]=0 backward crash; inference_mode no ver | GUARD VERIFIED |
| TorchDynamo + aot_eager | 0 breaks (diff 0.0e+00) | .item() triggers 1 break | FULLGRAPH PASS |
| Roofline & SwiGLU 8/3*d | H100 I*=295.2 FLOP/B | gemm_b1=1.0 vs large=683 | d_ff=11008 ALIGNED |
02-track-1-data-science-and-ai/part-03-deep-learning-and-modern-cv/labs/ch14-neural-networks-and-pytorch-workbench
[build-system]
requires = ["setuptools>=68.0"]
build-backend = "setuptools.build_meta"
[project]
name = "nn-pytorch-lab"
version = "0.1.0"
description = "WB-Ch14: Neural Networks & PyTorch 2.x Internals Two-Tier Production Workbench (T1-P3-U01)."
readme = "README.md"
requires-python = ">=3.12"
dependencies = [
"numpy>=1.26",
"pydantic>=2.0",
"scikit-learn>=1.5",
"scipy>=1.11",
"torch>=2.5",
]
[project.optional-dependencies]
dev = [
"mypy>=1.11",
"pytest>=8.0",
"ruff>=0.6",
]
[[tool.uv.index]]
name = "pytorch-cpu"
url = "https://download.pytorch.org/whl/cpu"
explicit = true
[tool.uv.sources]
torch = { index = "pytorch-cpu" }
[tool.setuptools]
package-dir = {"" = "src"}
[tool.setuptools.packages.find]
where = ["src"]
[tool.pytest.ini_options]
pythonpath = ["src"]
testpaths = ["tests"]
addopts = "-v"
[tool.ruff]
line-length = 110
target-version = "py312"
[tool.ruff.lint]
select = ["E", "F", "I", "UP", "B"]
[tool.mypy]
python_version = "3.12"
ignore_missing_imports = true
warn_unused_ignores = true
"""Public API for WB-Ch14 (`nn_pytorch_lab`): Tier 1 Reference Core & Tier 2 PyTorch Parity."""
from __future__ import annotations
from nn_pytorch_lab.autograd_core import (
NS5_COEFFS,
AutogradBenchConfig,
CheckpointMemoryConfig,
EarlyStoppingConfig,
InitBenchConfig,
OptimizerConfig,
RooflineConfig,
TapeTensor,
audit_adam_coupled_vs_adamw_decoupled,
audit_muon_ns5_spectrum,
audit_swiglu_param_flop_parity,
benchmark_deep_init_propagation,
benchmark_telgarsky_depth_separation,
central_diff_grad_check,
compute_roofline_and_fusion_savings,
log_sum_exp_cross_entropy,
moonlight_rms_scale,
simulate_checkpointing_tradeoff,
telgarsky_triangle_wave,
zeropower_via_newtonschulz5,
)
from nn_pytorch_lab.pytorch_training_lab import (
PreNormResidualBlock,
SwiGLUFFN,
audit_batchnorm_collapse_and_eval_mode,
audit_dynamo_compile_and_checkpoint,
audit_mixed_precision_fp16_bf16_cpu,
audit_regularization_techniques,
audit_tensor_strides_and_version_traps,
benchmark_optimizers_arena,
build_hybrid_muon_adamw_optimizers,
build_split_adamw_param_groups,
run_early_stopping_restoration_bench,
run_full_ch14_wb14_benchmarks,
verify_tier1_vs_torch_autograd_parity,
)
__all__ = [
"NS5_COEFFS",
"AutogradBenchConfig",
"CheckpointMemoryConfig",
"EarlyStoppingConfig",
"InitBenchConfig",
"OptimizerConfig",
"RooflineConfig",
"TapeTensor",
"audit_adam_coupled_vs_adamw_decoupled",
"audit_muon_ns5_spectrum",
"audit_swiglu_param_flop_parity",
"benchmark_deep_init_propagation",
"benchmark_telgarsky_depth_separation",
"central_diff_grad_check",
"compute_roofline_and_fusion_savings",
"log_sum_exp_cross_entropy",
"moonlight_rms_scale",
"simulate_checkpointing_tradeoff",
"telgarsky_triangle_wave",
"zeropower_via_newtonschulz5",
"PreNormResidualBlock",
"SwiGLUFFN",
"audit_batchnorm_collapse_and_eval_mode",
"audit_dynamo_compile_and_checkpoint",
"audit_mixed_precision_fp16_bf16_cpu",
"audit_regularization_techniques",
"audit_tensor_strides_and_version_traps",
"benchmark_optimizers_arena",
"build_hybrid_muon_adamw_optimizers",
"build_split_adamw_param_groups",
"run_early_stopping_restoration_bench",
"run_full_ch14_wb14_benchmarks",
"verify_tier1_vs_torch_autograd_parity",
]
"""Tier 1 Reference Core (`autograd_core.py`): Pure NumPy/Python reverse-mode autograd & numerical audits.
Strictly isolated from `torch` to provide an independent first-principles mathematical reference.
"""
from __future__ import annotations
import math
from collections.abc import Callable
from typing import Any, Literal
import numpy as np
from pydantic import BaseModel, ConfigDict, Field
from scipy.special import erf as scipy_erf
NS5_COEFFS: tuple[float, float, float] = (3.4445, -4.7750, 2.0315)
# ---------------------------------------------------------------------------
# Strict Pydantic v2 Configuration Contracts
# ---------------------------------------------------------------------------
class InitBenchConfig(BaseModel):
"""Configuration for deep MLP signal & gradient propagation benchmarks."""
model_config = ConfigDict(extra="forbid")
depth: int = Field(default=20, ge=2, le=64)
width: int = Field(default=64, ge=8, le=512)
batch_size: int = Field(default=64, ge=4, le=512)
activation: Literal["relu", "gelu", "silu", "tanh"] = "relu"
seed: int = Field(default=42, ge=0)
class AutogradBenchConfig(BaseModel):
"""Configuration for finite-difference and Tier-1 vs PyTorch autograd parity checks."""
model_config = ConfigDict(extra="forbid")
d_in: int = Field(default=8, ge=2, le=128)
d_hidden: int = Field(default=16, ge=2, le=256)
n_classes: int = Field(default=4, ge=2, le=64)
batch_size: int = Field(default=6, ge=2, le=128)
eps_fd: float = Field(default=1e-6, gt=0.0, le=1e-3)
seed: int = Field(default=42, ge=0)
class OptimizerConfig(BaseModel):
"""Configuration for SGD, Adam, AdamW, Muon NS5, and LR schedule audits."""
model_config = ConfigDict(extra="forbid")
lr: float = Field(default=0.01, gt=0.0, le=1.0)
weight_decay: float = Field(default=0.1, ge=0.0, le=1.0)
momentum: float = Field(default=0.95, ge=0.0, lt=1.0)
beta1: float = Field(default=0.9, ge=0.0, lt=1.0)
beta2: float = Field(default=0.999, ge=0.0, lt=1.0)
eps: float = Field(default=1e-8, gt=0.0)
ns_steps: int = Field(default=5, ge=1, le=12)
warmup_steps: int = Field(default=10, ge=0)
total_steps: int = Field(default=100, ge=1)
class CheckpointMemoryConfig(BaseModel):
"""Configuration for 16*Psi mixed-precision static VRAM and activation checkpointing simulation."""
model_config = ConfigDict(extra="forbid")
n_layers: int = Field(default=32, ge=4, le=256)
batch_size: int = Field(default=8, ge=1, le=256)
seq_len: int = Field(default=2048, ge=1, le=32768)
hidden_dim: int = Field(default=4096, ge=64, le=16384)
param_billions: float = Field(default=7.0, gt=0.0, le=1000.0)
dtype_bytes: int = Field(default=2, ge=1, le=4)
gemm_flops_share: float = Field(default=0.88, gt=0.0, le=1.0)
class RooflineConfig(BaseModel):
"""Configuration for hardware Roofline arithmetic intensity and kernel fusion byte savings."""
model_config = ConfigDict(extra="forbid")
peak_tflops: float = Field(default=989.0, gt=0.0)
mem_bw_gb_s: float = Field(default=3350.0, gt=0.0)
tokens: int = Field(default=1024, ge=1)
hidden_dim: int = Field(default=4096, ge=16)
d_ff: int = Field(default=11008, ge=16)
dtype_bytes: int = Field(default=2, ge=1, le=4)
class EarlyStoppingConfig(BaseModel):
"""Configuration for validation plateau early stopping and best_state_dict restoration."""
model_config = ConfigDict(extra="forbid")
patience: int = Field(default=5, ge=0, le=50)
min_delta: float = Field(default=1e-4, ge=0.0)
restore_best_weights: bool = True
# ---------------------------------------------------------------------------
# Reverse-Mode Autograd Micro-Engine (Wengert DAG, Float64, Numerator Layout)
# ---------------------------------------------------------------------------
def _unbroadcast(grad: np.ndarray, target_shape: tuple[int, ...]) -> np.ndarray:
"""Reduce broadcasted gradient dimensions back to `target_shape`."""
out = np.asarray(grad, dtype=np.float64)
if target_shape == ():
return np.array(float(np.sum(out)), dtype=np.float64)
while out.ndim > len(target_shape):
out = out.sum(axis=0)
for axis, dim in enumerate(target_shape):
if dim == 1 and out.shape[axis] != 1:
out = out.sum(axis=axis, keepdims=True)
return out.reshape(target_shape)
def _stable_sigmoid(x: np.ndarray) -> np.ndarray:
"""Overflow-safe logistic sigmoid on float64 arrays."""
pos_mask = x >= 0.0
z = np.empty_like(x, dtype=np.float64)
z[pos_mask] = 1.0 / (1.0 + np.exp(-x[pos_mask]))
exp_x = np.exp(x[~pos_mask])
z[~pos_mask] = exp_x / (1.0 + exp_x)
return z
class TapeTensor:
"""Pure-NumPy float64 Wengert DAG reverse-mode autodiff tensor node."""
def __init__(
self,
data: np.ndarray | list[Any] | float | int,
requires_grad: bool = False,
_prev: tuple[TapeTensor, ...] = (),
_op: str = "leaf",
) -> None:
self.data: np.ndarray = np.array(data, dtype=np.float64, copy=True)
self.grad: np.ndarray = np.zeros_like(self.data, dtype=np.float64)
self.requires_grad: bool = bool(requires_grad)
self._prev: tuple[TapeTensor, ...] = _prev
self._op: str = _op
self._backward: Callable[[], None] = lambda: None
@staticmethod
def _coerce(other: TapeTensor | np.ndarray | list[Any] | float | int) -> TapeTensor:
if isinstance(other, TapeTensor):
return other
return TapeTensor(other, requires_grad=False)
@property
def shape(self) -> tuple[int, ...]:
return tuple(self.data.shape)
@property
def ndim(self) -> int:
return int(self.data.ndim)
@property
def size(self) -> int:
return int(self.data.size)
@property
def T(self) -> TapeTensor:
return self.transpose()
def zero_grad(self) -> None:
self.grad = np.zeros_like(self.data, dtype=np.float64)
def transpose(self, *axes: int) -> TapeTensor:
perm: tuple[int, ...] | None = axes if axes else None
out_data = np.transpose(self.data, axes=perm)
out = TapeTensor(out_data, requires_grad=self.requires_grad, _prev=(self,), _op="transpose")
if perm is None:
inv_perm: tuple[int, ...] | None = None
else:
inv = [0] * len(perm)
for i, ax in enumerate(perm):
inv[ax] = i
inv_perm = tuple(inv)
def _backward() -> None:
if self.requires_grad:
self.grad += np.transpose(out.grad, axes=inv_perm)
out._backward = _backward
return out
def __neg__(self) -> TapeTensor:
out = TapeTensor(-self.data, requires_grad=self.requires_grad, _prev=(self,), _op="neg")
def _backward() -> None:
if self.requires_grad:
self.grad -= out.grad
out._backward = _backward
return out
def __add__(self, other: TapeTensor | np.ndarray | float | int) -> TapeTensor:
rhs = self._coerce(other)
req = self.requires_grad or rhs.requires_grad
out = TapeTensor(self.data + rhs.data, requires_grad=req, _prev=(self, rhs), _op="add")
def _backward() -> None:
if self.requires_grad:
self.grad += _unbroadcast(out.grad, self.shape)
if rhs.requires_grad:
rhs.grad += _unbroadcast(out.grad, rhs.shape)
out._backward = _backward
return out
def __radd__(self, other: TapeTensor | np.ndarray | float | int) -> TapeTensor:
return self._coerce(other).__add__(self)
def __sub__(self, other: TapeTensor | np.ndarray | float | int) -> TapeTensor:
rhs = self._coerce(other)
req = self.requires_grad or rhs.requires_grad
out = TapeTensor(self.data - rhs.data, requires_grad=req, _prev=(self, rhs), _op="sub")
def _backward() -> None:
if self.requires_grad:
self.grad += _unbroadcast(out.grad, self.shape)
if rhs.requires_grad:
rhs.grad += _unbroadcast(-out.grad, rhs.shape)
out._backward = _backward
return out
def __rsub__(self, other: TapeTensor | np.ndarray | float | int) -> TapeTensor:
return self._coerce(other).__sub__(self)
def __mul__(self, other: TapeTensor | np.ndarray | float | int) -> TapeTensor:
rhs = self._coerce(other)
req = self.requires_grad or rhs.requires_grad
out = TapeTensor(self.data * rhs.data, requires_grad=req, _prev=(self, rhs), _op="mul")
def _backward() -> None:
if self.requires_grad:
self.grad += _unbroadcast(out.grad * rhs.data, self.shape)
if rhs.requires_grad:
rhs.grad += _unbroadcast(out.grad * self.data, rhs.shape)
out._backward = _backward
return out
def __rmul__(self, other: TapeTensor | np.ndarray | float | int) -> TapeTensor:
return self._coerce(other).__mul__(self)
def matmul(self, other: TapeTensor | np.ndarray) -> TapeTensor:
"""Shape-preserving matrix multiply (dgrad + wgrad in Numerator Layout)."""
rhs = self._coerce(other)
req = self.requires_grad or rhs.requires_grad
out = TapeTensor(np.matmul(self.data, rhs.data), requires_grad=req, _prev=(self, rhs), _op="matmul")
def _backward() -> None:
if self.requires_grad:
d_self = np.matmul(out.grad, np.swapaxes(rhs.data, -1, -2))
self.grad += _unbroadcast(d_self, self.shape)
if rhs.requires_grad:
d_rhs = np.matmul(np.swapaxes(self.data, -1, -2), out.grad)
rhs.grad += _unbroadcast(d_rhs, rhs.shape)
out._backward = _backward
return out
def __matmul__(self, other: TapeTensor | np.ndarray) -> TapeTensor:
return self.matmul(other)
def sum(self, axis: int | tuple[int, ...] | None = None, keepdims: bool = False) -> TapeTensor:
if keepdims:
out_data = np.sum(self.data, axis=axis, keepdims=True)
else:
out_data = np.sum(self.data, axis=axis)
out = TapeTensor(out_data, requires_grad=self.requires_grad, _prev=(self,), _op="sum")
def _backward() -> None:
if not self.requires_grad:
return
g = out.grad
if axis is not None and not keepdims:
g = np.expand_dims(g, axis=axis)
self.grad += np.broadcast_to(g, self.shape)
out._backward = _backward
return out
def mean(self, axis: int | tuple[int, ...] | None = None, keepdims: bool = False) -> TapeTensor:
if keepdims:
out_data = np.mean(self.data, axis=axis, keepdims=True)
else:
out_data = np.mean(self.data, axis=axis)
out = TapeTensor(out_data, requires_grad=self.requires_grad, _prev=(self,), _op="mean")
scale = float(out.data.size) / float(self.data.size)
def _backward() -> None:
if not self.requires_grad:
return
g = out.grad * scale
if axis is not None and not keepdims:
g = np.expand_dims(g, axis=axis)
self.grad += np.broadcast_to(g, self.shape)
out._backward = _backward
return out
def relu(self) -> TapeTensor:
mask = self.data > 0.0
out_data = np.where(mask, self.data, 0.0)
out = TapeTensor(out_data, requires_grad=self.requires_grad, _prev=(self,), _op="relu")
def _backward() -> None:
if self.requires_grad:
self.grad += out.grad * mask.astype(np.float64)
out._backward = _backward
return out
def gelu(self) -> TapeTensor:
"""Exact Gaussian Error Linear Unit: z * Phi(z) matching torch.nn.functional.gelu."""
inv_sqrt2 = 1.0 / math.sqrt(2.0)
inv_sqrt2pi = 1.0 / math.sqrt(2.0 * math.pi)
x = self.data
cdf = 0.5 * (1.0 + scipy_erf(x * inv_sqrt2))
pdf = inv_sqrt2pi * np.exp(-0.5 * x * x)
out = TapeTensor(x * cdf, requires_grad=self.requires_grad, _prev=(self,), _op="gelu")
def _backward() -> None:
if self.requires_grad:
self.grad += out.grad * (cdf + x * pdf)
out._backward = _backward
return out
def silu(self) -> TapeTensor:
"""Sigmoid Linear Unit: z * sigmoid(z)."""
x = self.data
sig = _stable_sigmoid(x)
out = TapeTensor(x * sig, requires_grad=self.requires_grad, _prev=(self,), _op="silu")
def _backward() -> None:
if self.requires_grad:
d_silu = sig * (1.0 + x * (1.0 - sig))
self.grad += out.grad * d_silu
out._backward = _backward
return out
def swiglu(
self,
w_gate: TapeTensor,
w_up: TapeTensor,
w_down: TapeTensor,
) -> TapeTensor:
"""Row-major SwiGLU: (SiLU(x @ w_gate.T) * (x @ w_up.T)) @ w_down.T."""
gate = self.matmul(w_gate.T).silu()
up = self.matmul(w_up.T)
return (gate * up).matmul(w_down.T)
def rmsnorm(self, gamma: TapeTensor, eps: float = 1e-6) -> TapeTensor:
"""Root Mean Square Normalization along the last axis."""
x = self.data
d = float(x.shape[-1])
ms = np.mean(x * x, axis=-1, keepdims=True)
inv_rms = 1.0 / np.sqrt(ms + eps)
x_norm = x * inv_rms
out_data = x_norm * gamma.data
req = self.requires_grad or gamma.requires_grad
out = TapeTensor(out_data, requires_grad=req, _prev=(self, gamma), _op="rmsnorm")
def _backward() -> None:
dy = out.grad
if gamma.requires_grad:
gamma.grad += _unbroadcast(dy * x_norm, gamma.shape)
if self.requires_grad:
dx_norm = dy * gamma.data
proj = np.sum(dx_norm * x_norm, axis=-1, keepdims=True) / d
self.grad += inv_rms * (dx_norm - x_norm * proj)
out._backward = _backward
return out
def layernorm(self, gamma: TapeTensor, beta: TapeTensor, eps: float = 1e-5) -> TapeTensor:
"""Layer Normalization along the last axis with learnable affine scale & bias."""
x = self.data
d = float(x.shape[-1])
mu = np.mean(x, axis=-1, keepdims=True)
xc = x - mu
var = np.mean(xc * xc, axis=-1, keepdims=True)
inv_std = 1.0 / np.sqrt(var + eps)
x_hat = xc * inv_std
out_data = x_hat * gamma.data + beta.data
req = self.requires_grad or gamma.requires_grad or beta.requires_grad
out = TapeTensor(out_data, requires_grad=req, _prev=(self, gamma, beta), _op="layernorm")
def _backward() -> None:
dy = out.grad
if gamma.requires_grad:
gamma.grad += _unbroadcast(dy * x_hat, gamma.shape)
if beta.requires_grad:
beta.grad += _unbroadcast(dy, beta.shape)
if self.requires_grad:
dx_hat = dy * gamma.data
mean_dx = np.sum(dx_hat, axis=-1, keepdims=True) / d
mean_dx_xhat = np.sum(dx_hat * x_hat, axis=-1, keepdims=True) / d
self.grad += inv_std * (dx_hat - mean_dx - x_hat * mean_dx_xhat)
out._backward = _backward
return out
def cross_entropy_logits(self, targets: np.ndarray | list[int]) -> TapeTensor:
"""Shift-invariant Log-Sum-Exp mean cross-entropy over logits (B, K)."""
idx = np.asarray(targets, dtype=np.int64)
logits = self.data
if logits.ndim != 2 or idx.shape != (logits.shape[0],):
raise ValueError(
f"Expected logits shape (B, K) and targets shape (B,), got {logits.shape} & {idx.shape}"
)
batch_size = logits.shape[0]
m = np.max(logits, axis=1, keepdims=True)
shifted = logits - m
exp_s = np.exp(shifted)
sum_exp = np.sum(exp_s, axis=1, keepdims=True)
probs = exp_s / sum_exp
lse = m[:, 0] + np.log(sum_exp[:, 0])
target_logits = logits[np.arange(batch_size), idx]
loss_val = float(np.mean(lse - target_logits))
out = TapeTensor(loss_val, requires_grad=self.requires_grad, _prev=(self,), _op="cross_entropy")
def _backward() -> None:
if not self.requires_grad:
return
grad_logits = probs.copy()
grad_logits[np.arange(batch_size), idx] -= 1.0
grad_logits *= float(np.sum(out.grad)) / float(batch_size)
self.grad += grad_logits
out._backward = _backward
return out
def backward(self) -> None:
"""Iterative reverse topological sweep computing reverse-mode cotangents."""
topo: list[TapeTensor] = []
visited: set[int] = set()
stack: list[tuple[TapeTensor, bool]] = [(self, False)]
while stack:
node, expanded = stack.pop()
node_id = id(node)
if expanded:
topo.append(node)
continue
if node_id in visited:
continue
visited.add(node_id)
stack.append((node, True))
for child in node._prev:
if id(child) not in visited:
stack.append((child, False))
self.grad = np.ones_like(self.data, dtype=np.float64)
for node in reversed(topo):
node._backward()
# ---------------------------------------------------------------------------
# Numerical Gradcheck, Log-Sum-Exp, Telgarsky & Deep Signal Propagation
# ---------------------------------------------------------------------------
def central_diff_grad_check(
fn: Callable[[np.ndarray], float],
x: np.ndarray,
analytic_grad: np.ndarray,
eps: float = 1e-6,
) -> dict[str, float | bool]:
"""Compare analytical gradient against O(eps^2) float64 central finite differences."""
x_arr = np.asarray(x, dtype=np.float64)
analytic = np.asarray(analytic_grad, dtype=np.float64)
num_grad = np.zeros_like(x_arr, dtype=np.float64)
for idx in np.ndindex(x_arr.shape):
x_plus = x_arr.copy()
x_minus = x_arr.copy()
x_plus[idx] += eps
x_minus[idx] -= eps
num_grad[idx] = (float(fn(x_plus)) - float(fn(x_minus))) / (2.0 * eps)
diff = np.abs(num_grad - analytic)
max_abs_err = float(np.max(diff))
denom = max(float(np.linalg.norm(num_grad) + np.linalg.norm(analytic)), 1e-12)
rel_err = float(np.linalg.norm(num_grad - analytic) / denom)
return {
"max_abs_err": max_abs_err,
"rel_err": rel_err,
"passed": bool(max_abs_err < 1e-6),
}
def log_sum_exp_cross_entropy(logits: np.ndarray, targets: np.ndarray) -> tuple[float, np.ndarray]:
"""Numerically stable shift-invariant LSE cross-entropy loss & logit gradient."""
z = np.asarray(logits, dtype=np.float64)
y = np.asarray(targets, dtype=np.int64)
if z.ndim != 2 or y.shape != (z.shape[0],):
raise ValueError(f"Shape mismatch: logits={z.shape}, targets={y.shape}")
batch_size = z.shape[0]
m = np.max(z, axis=1, keepdims=True)
shifted = z - m
exp_s = np.exp(shifted)
sum_exp = np.sum(exp_s, axis=1, keepdims=True)
probs = exp_s / sum_exp
lse = m[:, 0] + np.log(sum_exp[:, 0])
loss = float(np.mean(lse - z[np.arange(batch_size), y]))
grad = probs.copy()
grad[np.arange(batch_size), y] -= 1.0
grad /= float(batch_size)
return loss, grad
def telgarsky_triangle_wave(x: np.ndarray, k: int) -> np.ndarray:
"""Compute k-fold composition of Telgarsky's 3-ReLU tent map on R."""
if k < 1:
raise ValueError(f"k must be >= 1, got {k}")
y = np.asarray(x, dtype=np.float64).copy()
for _ in range(k):
y = np.maximum(0.0, 2.0 * y) - 2.0 * np.maximum(0.0, 2.0 * y - 1.0) + np.maximum(
0.0, 2.0 * y - 2.0
)
return y
def _best_depth2_disagreement_uniform_knots(
x_grid: np.ndarray,
y_true_cls: np.ndarray,
width_m: int,
) -> float:
"""Fit a width-m depth-2 ReLU classifier on [0, 1] and return minimum sign disagreement."""
# Exact 1D depth-2 ReLU basis: [1, x, ReLU(x - t_1), ..., ReLU(x - t_m)]
knots = np.linspace(0.0, 1.0, width_m + 2)[1:-1]
design_cols = [np.ones_like(x_grid), x_grid]
for t_j in knots:
design_cols.append(np.maximum(0.0, x_grid - t_j))
design = np.column_stack(design_cols)
targets = np.where(y_true_cls > 0, 1.0, -1.0)
coef, *_ = np.linalg.lstsq(design, targets, rcond=None)
pred_sign = (design @ coef) >= 0.0
return float(np.mean(pred_sign != (y_true_cls > 0)))
def benchmark_telgarsky_depth_separation(
k_values: tuple[int, ...] = (1, 2, 3, 4, 5),
max_depth2_width: int = 32,
) -> dict[str, Any]:
"""Audit exponential oscillation count 2^k vs depth-2 width lower bound 0.5*(1 - (m+2)/2^k)."""
x_grid = np.linspace(0.0, 1.0, 4097)
x_mid = 0.5 * (x_grid[:-1] + x_grid[1:])
by_k: list[dict[str, Any]] = []
for k in k_values:
y_vals = telgarsky_triangle_wave(x_grid, k=k)
y_mid = telgarsky_triangle_wave(x_mid, k=k)
# Count peaks (> 0.99) and linear slopes (sign changes of derivative)
dy = np.diff(y_vals)
slope_sign_changes = int(np.sum(np.diff(np.signbit(dy))))
empirical_pieces = slope_sign_changes + 1
empirical_peaks = int(np.sum((y_vals[1:-1] > y_vals[:-2]) & (y_vals[1:-1] > y_vals[2:])))
# Evaluate depth-2 width strictly below half-pieces threshold when possible
eval_m = min(max_depth2_width, max(2, 2 ** max(0, k - 2)))
lb = max(0.0, 0.5 * (1.0 - float(eval_m + 2) / float(2**k)))
y_cls = (y_mid >= 0.5).astype(np.int64)
emp_err = _best_depth2_disagreement_uniform_knots(x_mid, y_cls, width_m=eval_m)
by_k.append(
{
"k": int(k),
"exact_pieces": int(2**k),
"empirical_pieces": empirical_pieces,
"exact_peaks": int(2 ** (k - 1)),
"empirical_peaks": empirical_peaks,
"depth2_eval_width": int(eval_m),
"depth2_theoretical_lower_bound": lb,
"empirical_depth2_disagreement": emp_err,
}
)
k_max = max(k_values)
y_max_cls = (telgarsky_triangle_wave(x_mid, k=k_max) >= 0.5).astype(np.int64)
width_sweep: list[dict[str, float | int]] = []
m_cur = 2
while m_cur <= max_depth2_width:
lb_m = max(0.0, 0.5 * (1.0 - float(m_cur + 2) / float(2**k_max)))
emp_m = _best_depth2_disagreement_uniform_knots(x_mid, y_max_cls, width_m=m_cur)
width_sweep.append(
{
"width_m": int(m_cur),
"theoretical_lower_bound": lb_m,
"empirical_disagreement": emp_m,
}
)
m_cur *= 2
return {
"by_k": by_k,
"k_max": int(k_max),
"width_sweep_at_k_max": width_sweep,
}
def _apply_act_np(z: np.ndarray, act: str) -> tuple[np.ndarray, np.ndarray]:
"""Return forward activation output and elementwise derivative for plain MLP propagation."""
if act == "relu":
mask = (z > 0.0).astype(np.float64)
return np.maximum(0.0, z), mask
if act == "tanh":
h = np.tanh(z)
return h, 1.0 - h * h
if act == "gelu":
inv_sqrt2 = 1.0 / math.sqrt(2.0)
inv_sqrt2pi = 1.0 / math.sqrt(2.0 * math.pi)
cdf = 0.5 * (1.0 + scipy_erf(z * inv_sqrt2))
pdf = inv_sqrt2pi * np.exp(-0.5 * z * z)
return z * cdf, cdf + z * pdf
if act == "silu":
sig = _stable_sigmoid(z)
return z * sig, sig * (1.0 + z * (1.0 - sig))
raise ValueError(f"Unsupported activation: {act}")
def benchmark_deep_init_propagation(cfg: InitBenchConfig) -> dict[str, dict[str, Any]]:
"""Measure L-layer forward variance trace & layer-1 gradient norm across 5 init regimes."""
rng = np.random.default_rng(cfg.seed)
x0 = rng.normal(0.0, 1.0, size=(cfg.batch_size, cfg.width))
# Unit-RMS upstream sensitivity vector per sample so ||g_L[b]||_2 == 1.0
g_out_base = rng.choice([-1.0, 1.0], size=(cfg.batch_size, cfg.width)) / math.sqrt(float(cfg.width))
regimes = ("naive_small", "naive_large", "xavier", "kaiming", "prenorm_res_scaled")
results: dict[str, dict[str, Any]] = {}
for regime in regimes:
local_rng = np.random.default_rng(cfg.seed + 101)
if regime == "prenorm_res_scaled":
scale_res = 1.0 / math.sqrt(2.0 * float(cfg.depth))
h = x0.copy()
var_trace: list[float] = [float(np.var(h))]
cache_res: list[
tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray]
] = []
for _ in range(cfg.depth):
w1 = local_rng.normal(0.0, math.sqrt(2.0 / cfg.width), size=(cfg.width, cfg.width))
w2 = local_rng.normal(0.0, math.sqrt(1.0 / cfg.width), size=(cfg.width, cfg.width))
ms = np.mean(h * h, axis=-1, keepdims=True)
inv_rms = 1.0 / np.sqrt(ms + 1e-6)
h_norm = h * inv_rms
z1 = h_norm @ w1.T
a1, da1 = _apply_act_np(z1, cfg.activation)
f_out = a1 @ w2.T
cache_res.append((h, inv_rms, h_norm, da1, w1, w2, a1))
h = h + scale_res * f_out
var_trace.append(float(np.var(h)))
g = g_out_base.copy()
layer1_grad_norm = 0.0
for layer_idx in reversed(range(cfg.depth)):
_h_in, inv_rms, h_norm, da1, w1, w2, _a1 = cache_res[layer_idx]
g_f = scale_res * g
g_a1 = g_f @ w2
g_z1 = g_a1 * da1
g_hnorm = g_z1 @ w1
proj = np.sum(g_hnorm * h_norm, axis=-1, keepdims=True) / float(cfg.width)
g_res_branch = inv_rms * (g_hnorm - h_norm * proj)
g = g + g_res_branch
if layer_idx == 0:
layer1_grad_norm = float(np.sqrt(np.mean(np.sum(g * g, axis=1))))
final_ratio = float(var_trace[-1] / max(var_trace[0], 1e-30))
else:
if regime == "naive_small":
std = 0.02
elif regime == "naive_large":
std = 0.35
elif regime == "xavier":
std = math.sqrt(2.0 / float(cfg.width + cfg.width))
elif regime == "kaiming":
std = math.sqrt(2.0 / float(cfg.width))
else:
raise ValueError(f"Unknown regime: {regime}")
h_cur = x0.copy()
var_trace = [float(np.var(h_cur))]
cache_plain: list[tuple[np.ndarray, np.ndarray]] = []
for _ in range(cfg.depth):
w = local_rng.normal(0.0, std, size=(cfg.width, cfg.width))
z = h_cur @ w.T
h_next, d_act = _apply_act_np(z, cfg.activation)
cache_plain.append((w, d_act))
var_trace.append(float(np.var(z)))
h_cur = h_next
g = g_out_base.copy()
layer1_grad_norm = 0.0
for layer_idx in reversed(range(cfg.depth)):
w, d_act = cache_plain[layer_idx]
g_z = g * d_act
g = g_z @ w
if layer_idx == 0:
layer1_grad_norm = float(np.sqrt(np.mean(np.sum(g * g, axis=1))))
final_ratio = float(var_trace[-1] / max(var_trace[0], 1e-30))
status = "O(1)_STABLE"
if final_ratio < 1e-3:
status = "VANISH"
elif final_ratio > 1e3:
status = "EXPLODE"
results[regime] = {
"forward_var_trace": var_trace,
"final_var_ratio": final_ratio,
"layer1_grad_norm": layer1_grad_norm,
"status": status,
}
return results
def audit_swiglu_param_flop_parity(d_model: int = 4096) -> dict[str, Any]:
"""Compare standard 4d 2-matrix FFN vs SwiGLU exact 8/3*d and TensorCore-aligned d_ff."""
d_ff_std = 4 * d_model
params_std = 2 * d_model * d_ff_std
flops_std = 2 * params_std
d_ff_swiglu_exact = (8.0 * float(d_model)) / 3.0
params_swiglu_exact = int(round(3.0 * float(d_model) * d_ff_swiglu_exact))
flops_swiglu_exact = 2 * params_swiglu_exact
d_ff_aligned_256 = int(math.ceil(d_ff_swiglu_exact / 256.0) * 256)
params_swiglu_aligned = 3 * d_model * d_ff_aligned_256
flops_swiglu_aligned = 2 * params_swiglu_aligned
overhead_pct = ((params_swiglu_aligned - params_std) / float(params_std)) * 100.0
return {
"d_model": int(d_model),
"d_ff_std": int(d_ff_std),
"params_std": int(params_std),
"flops_per_token_std": int(flops_std),
"d_ff_swiglu_exact": float(d_ff_swiglu_exact),
"params_swiglu_exact": int(params_swiglu_exact),
"flops_per_token_swiglu_exact": int(flops_swiglu_exact),
"param_ratio_exact": float(params_swiglu_exact / float(params_std)),
"d_ff_aligned_256": int(d_ff_aligned_256),
"params_swiglu_aligned": int(params_swiglu_aligned),
"flops_per_token_swiglu_aligned": int(flops_swiglu_aligned),
"aligned_overhead_pct": float(overhead_pct),
}
def audit_adam_coupled_vs_adamw_decoupled(
weight_decay: float = 0.1,
lr: float = 0.02,
n_steps: int = 80,
) -> dict[str, Any]:
"""Demonstrate coupled L2 Adam shrinkage distortion vs uniform AdamW decay on (g1=+-100, g2=+-0.01)."""
beta1 = 0.9
beta2 = 0.999
eps = 1e-8
w_coupled = np.array([2.0, 2.0], dtype=np.float64)
m_c = np.zeros(2, dtype=np.float64)
v_c = np.zeros(2, dtype=np.float64)
w_decoupled = np.array([2.0, 2.0], dtype=np.float64)
m_d = np.zeros(2, dtype=np.float64)
v_d = np.zeros(2, dtype=np.float64)
base_grads = np.array([100.0, 0.01], dtype=np.float64)
for t in range(1, n_steps + 1):
# Zero-mean alternating gradient isolates adaptive preconditioner vs weight decay
sign = 1.0 if (t % 2 == 1) else -1.0
g_data = sign * base_grads
# Coupled L2 Adam: g_tilde = g + lambda * w inside adaptive moments
g_coupled = g_data + weight_decay * w_coupled
m_c = beta1 * m_c + (1.0 - beta1) * g_coupled
v_c = beta2 * v_c + (1.0 - beta2) * (g_coupled * g_coupled)
m_c_hat = m_c / (1.0 - beta1**t)
v_c_hat = v_c / (1.0 - beta2**t)
w_coupled = w_coupled - lr * m_c_hat / (np.sqrt(v_c_hat) + eps)
# Decoupled AdamW: moments track g_data only, decay applied directly outside preconditioner
m_d = beta1 * m_d + (1.0 - beta1) * g_data
v_d = beta2 * v_d + (1.0 - beta2) * (g_data * g_data)
m_d_hat = m_d / (1.0 - beta1**t)
v_d_hat = v_d / (1.0 - beta2**t)
w_decoupled = w_decoupled * (1.0 - lr * weight_decay) - lr * m_d_hat / (np.sqrt(v_d_hat) + eps)
coupled_ratio = float(abs(w_coupled[0]) / max(abs(w_coupled[1]), 1e-12))
decoupled_diff = float(abs(w_decoupled[0] - w_decoupled[1]))
theoretical_decay_factor = (1.0 - lr * weight_decay) ** n_steps
return {
"initial_weights": [2.0, 2.0],
"grad_magnitudes": [100.0, 0.01],
"coupled_final_weights": [float(w_coupled[0]), float(w_coupled[1])],
"decoupled_final_weights": [float(w_decoupled[0]), float(w_decoupled[1])],
"coupled_weight_ratio": coupled_ratio,
"decoupled_weight_abs_diff": decoupled_diff,
"theoretical_uniform_decay_factor": float(theoretical_decay_factor),
}
def zeropower_via_newtonschulz5(G: np.ndarray, steps: int = 5, eps: float = 1e-7) -> np.ndarray:
"""5-step quintic Newton-Schulz orthogonalization matching Jordan / PyTorch Muon."""
arr = np.asarray(G, dtype=np.float64)
if arr.ndim != 2:
raise ValueError(f"Expected 2D matrix for Newton-Schulz5, got shape {arr.shape}")
a, b, c = NS5_COEFFS
X = arr.copy()
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
if transposed:
X = X.T
return X
def moonlight_rms_scale(d_out: int, d_in: int) -> float:
"""Moonlight AdamW-RMS matching multiplier: 0.2 * sqrt(max(d_out, d_in))."""
return float(0.2 * math.sqrt(float(max(d_out, d_in))))
def audit_muon_ns5_spectrum(
shapes: tuple[tuple[int, int], ...] = ((16, 128), (64, 64), (128, 16)),
seed: int = 42,
) -> dict[str, Any]:
"""Verify NS5 singular contraction [0.01, 1.0] -> [0.6818, 1.1344] & Moonlight uniform update RMS."""
a, b, c = NS5_COEFFS
s0 = np.linspace(0.01, 1.0, 200)
s = s0.copy()
for _ in range(5):
s = a * s + b * (s**3) + c * (s**5)
scalar_min_sv = float(np.min(s))
scalar_max_sv = float(np.max(s))
rng = np.random.default_rng(seed)
# Matrix SVD test with controlled normalized spectrum in [0.02, 0.90]
u, _ = np.linalg.qr(rng.normal(0.0, 1.0, size=(16, 16)))
v, _ = np.linalg.qr(rng.normal(0.0, 1.0, size=(32, 32)))
spec = np.geomspace(0.025, 0.65, 16)
spec = spec / float(np.linalg.norm(spec))
g_spec = u @ np.diag(spec) @ v[:16, :]
o_spec = zeropower_via_newtonschulz5(g_spec, steps=5)
matrix_sv = np.linalg.svd(o_spec, compute_uv=False)
by_shape: dict[str, dict[str, float]] = {}
for d_out, d_in in shapes:
g_mat = rng.normal(0.0, 1.0, size=(d_out, d_in))
o_mat = zeropower_via_newtonschulz5(g_mat, steps=5)
scale = moonlight_rms_scale(d_out, d_in)
scaled_update = scale * o_mat
raw_rms = float(np.sqrt(np.mean(o_mat**2)))
scaled_rms = float(np.sqrt(np.mean(scaled_update**2)))
by_shape[f"{d_out}x{d_in}"] = {
"moonlight_scale": scale,
"raw_update_rms": raw_rms,
"scaled_update_rms": scaled_rms,
}
return {
"scalar_ns5_min_sv": scalar_min_sv,
"scalar_ns5_max_sv": scalar_max_sv,
"matrix_ns5_min_sv": float(np.min(matrix_sv)),
"matrix_ns5_max_sv": float(np.max(matrix_sv)),
"by_shape": by_shape,
}
def simulate_checkpointing_tradeoff(cfg: CheckpointMemoryConfig) -> dict[str, dict[str, float]]:
"""Compute exact 16*Psi static states and O(L) vs O(sqrt(L)) (+33.3%) vs SAC activation tradeoffs."""
psi = cfg.param_billions * 1e9
static_breakdown = {
"bf16_weights_gb": (2.0 * psi) / 1e9,
"bf16_grads_gb": (2.0 * psi) / 1e9,
"fp32_master_gb": (4.0 * psi) / 1e9,
"adam_m_gb": (4.0 * psi) / 1e9,
"adam_v_gb": (4.0 * psi) / 1e9,
"static_total_gb": 16.0 * cfg.param_billions,
"static_bytes_per_param": 16.0,
}
# Standard Transformer block saves ~10 d-width activation tensors per layer (QKV/Attn/MLP/Norms)
tensors_per_layer = 10.0
tokens_x_hidden = cfg.batch_size * cfg.seq_len * cfg.hidden_dim * cfg.dtype_bytes
layer_act_bytes = tensors_per_layer * float(tokens_x_hidden)
full_act_bytes = float(cfg.n_layers) * layer_act_bytes
full_act_gb = full_act_bytes / 1e9
sqrt_kept = 2.0 * math.sqrt(float(cfg.n_layers))
sqrt_ratio = min(1.0, sqrt_kept / float(cfg.n_layers))
sqrt_act_gb = full_act_gb * sqrt_ratio
sqrt_mem_cut_pct = (1.0 - sqrt_ratio) * 100.0
sqrt_extra_flops_pct = 100.0 / 3.0 # +1 extra fwd over (1 fwd + 2 bwd) = 1/3
# Selective Activation Checkpointing (SAC): retain GEMM inputs (~28% act mem), recompute elementwise/norms
sac_ratio = 0.28
sac_act_gb = full_act_gb * sac_ratio
sac_mem_cut_pct = (1.0 - sac_ratio) * 100.0
sac_extra_flops_pct = ((1.0 - cfg.gemm_flops_share) / 3.0) * 100.0
static_gb = static_breakdown["static_total_gb"]
return {
"static_breakdown": static_breakdown,
"full_tape": {
"activation_gb": full_act_gb,
"activation_mb": full_act_bytes / 1e6,
"memory_reduction_pct": 0.0,
"extra_flops_pct": 0.0,
"total_vram_gb": static_gb + full_act_gb,
},
"sqrt_uniform": {
"activation_gb": sqrt_act_gb,
"activation_mb": (sqrt_act_gb * 1e9) / 1e6,
"memory_reduction_pct": sqrt_mem_cut_pct,
"extra_flops_pct": sqrt_extra_flops_pct,
"total_vram_gb": static_gb + sqrt_act_gb,
},
"selective_sac": {
"activation_gb": sac_act_gb,
"activation_mb": (sac_act_gb * 1e9) / 1e6,
"memory_reduction_pct": sac_mem_cut_pct,
"extra_flops_pct": sac_extra_flops_pct,
"total_vram_gb": static_gb + sac_act_gb,
},
}
def compute_roofline_and_fusion_savings(cfg: RooflineConfig) -> dict[str, Any]:
"""Compute hardware ridge point I*, kernel arithmetic intensities, and HBM fusion savings."""
ridge_cfg = (cfg.peak_tflops * 1000.0) / cfg.mem_bw_gb_s
ridge_h100_bf16 = (989.0 * 1000.0) / 3350.0
ridge_a100_bf16 = (312.0 * 1000.0) / 2039.0
t = float(cfg.tokens)
d = float(cfg.hidden_dim)
d_ff = float(cfg.d_ff)
b = float(cfg.dtype_bytes)
def _entry(name: str, flops: float, hbm_bytes: float) -> dict[str, Any]:
intensity = flops / max(hbm_bytes, 1.0)
regime = "compute_bound" if intensity >= ridge_cfg else "memory_bound"
attainable_tflops = min(cfg.peak_tflops, (intensity * cfg.mem_bw_gb_s) / 1000.0)
return {
"name": name,
"flops": float(flops),
"hbm_bytes": float(hbm_bytes),
"arithmetic_intensity": float(intensity),
"regime": regime,
"attainable_tflops": float(attainable_tflops),
}
m_large = max(t, 1024.0)
kernels = {
"rmsnorm_unfused": _entry("rmsnorm_unfused", 5.0 * t * d, 7.0 * t * d * b),
"rmsnorm_fused": _entry("rmsnorm_fused", 5.0 * t * d, 2.0 * t * d * b),
"swiglu_unfused": _entry("swiglu_unfused", 5.0 * t * d_ff, 8.0 * t * d_ff * b),
"swiglu_fused": _entry("swiglu_fused", 5.0 * t * d_ff, 3.0 * t * d_ff * b),
"bias_gelu_res_unfused": _entry("bias_gelu_res_unfused", 12.0 * t * d, 7.0 * t * d * b),
"bias_gelu_res_fused": _entry("bias_gelu_res_fused", 12.0 * t * d, 3.0 * t * d * b),
"adamw_step": _entry("adamw_step", 12.0 * d * d, 28.0 * d * d),
"gemm_b1": _entry("gemm_b1", 2.0 * 1.0 * d * d, (1.0 * d + d * d + 1.0 * d) * b),
"gemm_large_batch": _entry(
"gemm_large_batch",
2.0 * m_large * d * d,
(m_large * d + d * d + m_large * d) * b,
),
}
rmsnorm_cut_pct = (1.0 - 2.0 / 7.0) * 100.0
bias_gelu_res_cut_pct = (1.0 - 3.0 / 7.0) * 100.0
swiglu_cut_pct = (1.0 - 3.0 / 8.0) * 100.0
return {
"ridge_point_cfg": float(ridge_cfg),
"ridge_point_h100_bf16": float(ridge_h100_bf16),
"ridge_point_a100_bf16": float(ridge_a100_bf16),
"fusion_savings": {
"rmsnorm_hbm_cut_pct": float(rmsnorm_cut_pct),
"bias_gelu_res_hbm_cut_pct": float(bias_gelu_res_cut_pct),
"swiglu_hbm_cut_pct": float(swiglu_cut_pct),
},
"kernels": kernels,
}
"""Tier 2 PyTorch 2.15.0+cpu Parity, Optimizers, Mixed Precision, Internals & Compile Audits."""
from __future__ import annotations
import math
import time
from typing import Any
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.checkpoint import checkpoint as torch_checkpoint
from nn_pytorch_lab.autograd_core import (
AutogradBenchConfig,
CheckpointMemoryConfig,
EarlyStoppingConfig,
InitBenchConfig,
RooflineConfig,
TapeTensor,
audit_adam_coupled_vs_adamw_decoupled,
audit_muon_ns5_spectrum,
audit_swiglu_param_flop_parity,
benchmark_deep_init_propagation,
benchmark_telgarsky_depth_separation,
central_diff_grad_check,
compute_roofline_and_fusion_savings,
log_sum_exp_cross_entropy,
simulate_checkpointing_tradeoff,
)
# ---------------------------------------------------------------------------
# Modern Transformer Sub-Blocks (SwiGLU + Pre-Norm RMSNorm + 1/sqrt(2L) Scale)
# ---------------------------------------------------------------------------
class SwiGLUFFN(nn.Module):
"""3-matrix gated SwiGLU feed-forward network with default d_ff ~ (8/3)*d_model."""
def __init__(self, d_model: int, d_ff: int | None = None, bias: bool = False) -> None:
super().__init__()
hidden_dim = d_ff if d_ff is not None else max(4, int(round((8.0 * float(d_model)) / 3.0)))
self.w_gate = nn.Linear(d_model, hidden_dim, bias=bias)
self.w_up = nn.Linear(d_model, hidden_dim, bias=bias)
self.w_down = nn.Linear(hidden_dim, d_model, bias=bias)
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.w_down(F.silu(self.w_gate(x)) * self.w_up(x))
class PreNormResidualBlock(nn.Module):
"""Pre-Norm residual block with nn.RMSNorm, SwiGLUFFN, and 1/sqrt(2L) residual scaling."""
def __init__(
self,
d_model: int,
d_ff: int | None = None,
depth_scale: float = 1.0,
dropout_p: float = 0.0,
norm_eps: float = 1e-6,
) -> None:
super().__init__()
self.norm = nn.RMSNorm(d_model, eps=norm_eps)
self.ffn = SwiGLUFFN(d_model, d_ff=d_ff, bias=False)
self.drop = nn.Dropout(p=dropout_p)
self.depth_scale = float(depth_scale)
def forward(self, x: torch.Tensor) -> torch.Tensor:
return x + self.depth_scale * self.drop(self.ffn(self.norm(x)))
# ---------------------------------------------------------------------------
# 1. Exact Float64 Autograd Parity: Tier 1 TapeTensor vs Tier 2 torch.autograd
# ---------------------------------------------------------------------------
def verify_tier1_vs_torch_autograd_parity(cfg: AutogradBenchConfig) -> dict[str, float | bool]:
"""Compare Tier 1 NumPy TapeTensor vs Tier 2 PyTorch float64 on RMSNorm+SwiGLU+GELU+CE."""
rng = np.random.default_rng(cfg.seed)
x_np = rng.normal(0.0, 0.7, size=(cfg.batch_size, cfg.d_in))
gamma_np = 1.0 + rng.normal(0.0, 0.1, size=(cfg.d_in,))
w_gate_np = rng.normal(0.0, 1.0 / math.sqrt(cfg.d_in), size=(cfg.d_hidden, cfg.d_in))
w_up_np = rng.normal(0.0, 1.0 / math.sqrt(cfg.d_in), size=(cfg.d_hidden, cfg.d_in))
w_down_np = rng.normal(0.0, 1.0 / math.sqrt(cfg.d_hidden), size=(cfg.d_in, cfg.d_hidden))
w_gelu_np = rng.normal(0.0, 1.0 / math.sqrt(cfg.d_in), size=(cfg.d_hidden, cfg.d_in))
w_cls_np = rng.normal(0.0, 1.0 / math.sqrt(cfg.d_hidden), size=(cfg.n_classes, cfg.d_hidden))
b_cls_np = rng.normal(0.0, 0.1, size=(cfg.n_classes,))
targets_np = rng.integers(0, cfg.n_classes, size=(cfg.batch_size,), dtype=np.int64)
# Tier 1 TapeTensor forward + backward
t_x = TapeTensor(x_np, requires_grad=True)
t_gamma = TapeTensor(gamma_np, requires_grad=True)
t_wg = TapeTensor(w_gate_np, requires_grad=True)
t_wu = TapeTensor(w_up_np, requires_grad=True)
t_wd = TapeTensor(w_down_np, requires_grad=True)
t_wgelu = TapeTensor(w_gelu_np, requires_grad=True)
t_wcls = TapeTensor(w_cls_np, requires_grad=True)
t_bcls = TapeTensor(b_cls_np, requires_grad=True)
h_norm = t_x.rmsnorm(t_gamma, eps=1e-6)
h_glu = h_norm.swiglu(t_wg, t_wu, t_wd)
h_act = h_glu.matmul(t_wgelu.T).gelu()
logits_np = h_act.matmul(t_wcls.T) + t_bcls
loss_np_node = logits_np.cross_entropy_logits(targets_np)
loss_np_node.backward()
loss_np = float(loss_np_node.data)
# Tier 2 PyTorch float64 forward + backward
p_x = torch.tensor(x_np, dtype=torch.float64, requires_grad=True)
p_gamma = torch.tensor(gamma_np, dtype=torch.float64, requires_grad=True)
p_wg = torch.tensor(w_gate_np, dtype=torch.float64, requires_grad=True)
p_wu = torch.tensor(w_up_np, dtype=torch.float64, requires_grad=True)
p_wd = torch.tensor(w_down_np, dtype=torch.float64, requires_grad=True)
p_wgelu = torch.tensor(w_gelu_np, dtype=torch.float64, requires_grad=True)
p_wcls = torch.tensor(w_cls_np, dtype=torch.float64, requires_grad=True)
p_bcls = torch.tensor(b_cls_np, dtype=torch.float64, requires_grad=True)
p_targets = torch.tensor(targets_np, dtype=torch.long)
p_h_norm = F.rms_norm(p_x, (cfg.d_in,), weight=p_gamma, eps=1e-6)
p_h_glu = (F.silu(p_h_norm @ p_wg.T) * (p_h_norm @ p_wu.T)) @ p_wd.T
p_h_act = F.gelu(p_h_glu @ p_wgelu.T, approximate="none")
p_logits = p_h_act @ p_wcls.T + p_bcls
p_loss = F.cross_entropy(p_logits, p_targets)
p_loss.backward()
pairs: list[tuple[str, np.ndarray, torch.Tensor]] = [
("x", t_x.grad, p_x),
("gamma", t_gamma.grad, p_gamma),
("w_gate", t_wg.grad, p_wg),
("w_up", t_wu.grad, p_wu),
("w_down", t_wd.grad, p_wd),
("w_gelu", t_wgelu.grad, p_wgelu),
("w_cls", t_wcls.grad, p_wcls),
("b_cls", t_bcls.grad, p_bcls),
]
max_grad_abs_diff = 0.0
for _name, g_np, p_tensor in pairs:
assert p_tensor.grad is not None
g_th = p_tensor.grad.detach().cpu().numpy()
diff = float(np.max(np.abs(g_np - g_th)))
max_grad_abs_diff = max(max_grad_abs_diff, diff)
def _scalar_fn(arr_x: np.ndarray) -> float:
tx = TapeTensor(arr_x, requires_grad=False)
hn = tx.rmsnorm(TapeTensor(gamma_np), eps=1e-6)
hg = hn.swiglu(TapeTensor(w_gate_np), TapeTensor(w_up_np), TapeTensor(w_down_np))
ha = hg.matmul(TapeTensor(w_gelu_np).T).gelu()
lg = ha.matmul(TapeTensor(w_cls_np).T) + TapeTensor(b_cls_np)
return float(lg.cross_entropy_logits(targets_np).data)
fd_check = central_diff_grad_check(_scalar_fn, x_np, t_x.grad, eps=cfg.eps_fd)
loss_abs_diff = abs(loss_np - float(p_loss.item()))
return {
"tier1_loss": loss_np,
"torch_loss": float(p_loss.item()),
"loss_abs_diff": float(loss_abs_diff),
"max_grad_abs_diff": float(max_grad_abs_diff),
"central_diff_max_abs_err": float(fd_check["max_abs_err"]),
"parity_passed": bool(
loss_abs_diff < 1e-8 and max_grad_abs_diff < 1e-5 and bool(fd_check["passed"])
),
}
# ---------------------------------------------------------------------------
# 2. BatchNorm B=2 Collapse & train()/eval() Trap vs LayerNorm & RMSNorm
# ---------------------------------------------------------------------------
def audit_batchnorm_collapse_and_eval_mode(seed: int = 42) -> dict[str, Any]:
"""Verify BatchNorm B=1 error, B=2 +-1 collapse & eval drift vs B=1-safe LayerNorm/RMSNorm."""
torch.manual_seed(seed)
d = 16
bn_raw = nn.BatchNorm1d(d, eps=1e-8, affine=False)
bn_raw.train()
# 1) B=1 raises ValueError in BatchNorm train()
b1_raised = False
try:
_ = bn_raw(torch.randn(1, d))
except ValueError:
b1_raised = True
# 2) B=2 quantization collapse to +-1.0
x_b2 = torch.randn(2, d)
# Ensure non-identical rows so denominator > 0
x_b2[1] = x_b2[0] + torch.where(x_b2[1] >= x_b2[0], 0.85, -0.85)
y_b2 = bn_raw(x_b2)
b2_abs_dev_from_1 = float((y_b2.abs() - 1.0).abs().max().item())
# Empirical B=2 batch variance bias (50% downward bias vs true Var=1.0)
samples_b2 = torch.randn(2000, 2, d)
b2_var_mean = float(samples_b2.var(dim=1, unbiased=False).mean().item())
# 3) train() vs eval() mutation trap on running_mean
bn_tracked = nn.BatchNorm1d(d, momentum=0.1, affine=True)
bn_tracked.train()
for _ in range(10):
_ = bn_tracked(torch.randn(32, d))
assert bn_tracked.running_mean is not None
saved_mean_before_eval = bn_tracked.running_mean.detach().clone()
# Proper eval() preserves running stats
bn_tracked.eval()
x_shift = 5.0 + 2.0 * torch.randn(32, d)
with torch.no_grad():
_ = bn_tracked(x_shift)
eval_running_mean_drift = float((bn_tracked.running_mean - saved_mean_before_eval).abs().max().item())
# Omitting eval() mutates running_mean on shifted inference traffic
bn_tracked.train()
with torch.no_grad():
y_train_b32 = bn_tracked(x_shift)
y_train_b2 = bn_tracked(x_shift[:2])
forgot_eval_running_mean_drift = float(
(bn_tracked.running_mean - saved_mean_before_eval).abs().max().item()
)
bn_b2_vs_b32_row0_diff = float((y_train_b2[0] - y_train_b32[0]).abs().max().item())
# 4) LayerNorm & RMSNorm B=1 vs B=32 invariance + RMSNorm weight-scaling invariance
ln = nn.LayerNorm(d, eps=1e-6)
rms = nn.RMSNorm(d, eps=1e-8)
x_test = torch.randn(32, d)
ln.train()
ln_train_b1 = ln(x_test[:1])[0]
ln.eval()
ln_eval_b32 = ln(x_test)[0]
ln_b1_vs_b32_max_diff = float((ln_train_b1 - ln_eval_b32).abs().max().item())
rms.train()
rms_train_b1 = rms(x_test[:1])[0]
rms.eval()
rms_eval_b32 = rms(x_test)[0]
rmsnorm_b1_vs_b32_max_diff = float((rms_train_b1 - rms_eval_b32).abs().max().item())
# Positive weight scaling invariance: RMSNorm(alpha * W x) == RMSNorm(W x)
w_proj = torch.randn(d, d)
alpha = 7.5
out_base = rms(x_test @ w_proj.T)
out_scaled = rms(x_test @ (alpha * w_proj).T)
rmsnorm_weight_scale_max_diff = float((out_base - out_scaled).abs().max().item())
return {
"bn_b1_raises_value_error": b1_raised,
"bn_b2_abs_dev_from_unit": b2_abs_dev_from_1,
"bn_b2_biased_var_mean": b2_var_mean,
"eval_running_mean_drift": eval_running_mean_drift,
"forgot_eval_running_mean_drift": forgot_eval_running_mean_drift,
"bn_b2_vs_b32_row0_diff": bn_b2_vs_b32_row0_diff,
"ln_b1_vs_b32_max_diff": ln_b1_vs_b32_max_diff,
"rmsnorm_b1_vs_b32_max_diff": rmsnorm_b1_vs_b32_max_diff,
"rmsnorm_weight_scale_max_diff": rmsnorm_weight_scale_max_diff,
}
# ---------------------------------------------------------------------------
# 3. Split Param Groups, HybridMuonAdamW & Multi-Optimizer Arena
# ---------------------------------------------------------------------------
def build_split_adamw_param_groups(model: nn.Module, weight_decay: float) -> list[dict[str, Any]]:
"""Separate 2D weight decay parameters from 1D norm/bias zero-decay parameters."""
decay_params: list[torch.Tensor] = []
no_decay_params: list[torch.Tensor] = []
for name, param in model.named_parameters():
if not param.requires_grad:
continue
if param.ndim < 2 or "norm" in name.lower() or name.endswith(".bias"):
no_decay_params.append(param)
else:
decay_params.append(param)
groups: list[dict[str, Any]] = []
if decay_params:
groups.append({"params": decay_params, "weight_decay": float(weight_decay), "group_name": "decay_2d"})
if no_decay_params:
groups.append({"params": no_decay_params, "weight_decay": 0.0, "group_name": "no_decay_1d"})
return groups
def build_hybrid_muon_adamw_optimizers(
model: nn.Module,
lr: float,
weight_decay: float,
momentum: float = 0.95,
) -> tuple[torch.optim.Muon, torch.optim.AdamW]:
"""Route 2D hidden linear matrices to Muon(match_rms_adamw) and 1D/head/embed to AdamW."""
muon_params: list[torch.Tensor] = []
adamw_decay_params: list[torch.Tensor] = []
adamw_no_decay_params: list[torch.Tensor] = []
for name, param in model.named_parameters():
if not param.requires_grad:
continue
lower_name = name.lower()
if param.ndim == 2 and "embed" not in lower_name and "head" not in lower_name:
muon_params.append(param)
elif param.ndim >= 2:
adamw_decay_params.append(param)
else:
adamw_no_decay_params.append(param)
if not muon_params:
raise ValueError("Model must contain at least one 2D hidden weight matrix for Muon.")
muon_opt = torch.optim.Muon(
muon_params,
lr=float(lr),
weight_decay=float(weight_decay),
momentum=float(momentum),
nesterov=True,
ns_steps=5,
adjust_lr_fn="match_rms_adamw",
)
adamw_groups: list[dict[str, Any]] = []
if adamw_decay_params:
adamw_groups.append(
{"params": adamw_decay_params, "weight_decay": float(weight_decay), "group_name": "adamw_2d_io"}
)
if adamw_no_decay_params:
adamw_groups.append(
{"params": adamw_no_decay_params, "weight_decay": 0.0, "group_name": "adamw_1d_no_decay"}
)
adamw_opt = torch.optim.AdamW(adamw_groups, lr=float(lr), betas=(0.9, 0.95), eps=1e-8)
return muon_opt, adamw_opt
class _ArenaSwiGLUClassifier(nn.Module):
"""Deterministic Pre-Norm SwiGLU network with input proj, L residual blocks, RMSNorm, and head."""
def __init__(self, d_in: int, d_model: int, n_layers: int, n_classes: int) -> None:
super().__init__()
self.in_proj = nn.Linear(d_in, d_model, bias=True)
depth_scale = 1.0 / math.sqrt(2.0 * float(n_layers))
self.blocks = nn.ModuleList(
[PreNormResidualBlock(d_model, depth_scale=depth_scale) for _ in range(n_layers)]
)
self.final_norm = nn.RMSNorm(d_model, eps=1e-6)
self.head = nn.Linear(d_model, n_classes, bias=True)
def forward(self, x: torch.Tensor) -> torch.Tensor:
h = self.in_proj(x)
for blk in self.blocks:
h = blk(h)
return self.head(self.final_norm(h))
def _make_nonlinear_classification_dataset(
seed: int,
n_train: int,
n_val: int,
d_in: int = 6,
n_classes: int = 4,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
"""Generate deterministic structured multi-class manifold data separable by SwiGLU."""
gen = torch.Generator().manual_seed(seed)
n_total = n_train + n_val
x = torch.randn(n_total, d_in, generator=gen)
# Clean nonlinear XOR + radial + trigonometric class boundaries in 6D
s0 = 1.6 * x[:, 0] * x[:, 1] + 0.8 * torch.tanh(x[:, 2]) + 0.4 * (x[:, 3] ** 2 - 1.0)
s1 = -1.6 * x[:, 0] * x[:, 1] + 0.8 * torch.tanh(x[:, 3]) + 0.4 * (x[:, 4] ** 2 - 1.0)
s2 = 1.6 * x[:, 4] * x[:, 5] + 0.8 * torch.sin(x[:, 0]) - 0.4 * (x[:, 2] ** 2 - 1.0)
s3 = -1.6 * x[:, 4] * x[:, 5] + 0.8 * torch.cos(x[:, 1]) - 0.4 * (x[:, 5] ** 2 - 1.0)
scores = torch.stack([s0, s1, s2, s3], dim=1)
if n_classes != 4:
scores = scores[:, :n_classes]
y = torch.argmax(scores, dim=1)
return x[:n_train], y[:n_train], x[n_train:], y[n_train:]
def _warmup_cosine_multiplier(
step_idx: int,
warmup_steps: int,
total_steps: int,
min_ratio: float = 0.1,
) -> float:
"""Linear warmup [1..Tw] followed by cosine decay [Tw+1..T]."""
t = step_idx + 1
if warmup_steps > 0 and t <= warmup_steps:
return float(t) / float(warmup_steps)
if total_steps <= warmup_steps:
return 1.0
progress = min(1.0, max(0.0, float(t - warmup_steps) / float(total_steps - warmup_steps)))
return min_ratio + 0.5 * (1.0 - min_ratio) * (1.0 + math.cos(math.pi * progress))
def benchmark_optimizers_arena(seed: int = 42, quick: bool = False) -> dict[str, Any]:
"""Train identical SwiGLU Pre-Norm models across SGD, coupled Adam, split AdamW, and Hybrid Muon."""
n_train = 1024 if quick else 1280
n_val = 384 if quick else 512
n_epochs = 24 if quick else 36
label_smoothing = 0.05 if quick else 0.0
batch_size = 64
d_in, d_model, n_layers, n_classes = 6, 24, 2, 4
x_tr, y_tr, x_va, y_va = _make_nonlinear_classification_dataset(
seed=seed, n_train=n_train, n_val=n_val, d_in=d_in, n_classes=n_classes
)
torch.manual_seed(seed)
template_model = _ArenaSwiGLUClassifier(
d_in=d_in, d_model=d_model, n_layers=n_layers, n_classes=n_classes
)
init_state = {k: v.detach().clone() for k, v in template_model.state_dict().items()}
steps_per_epoch = max(1, (n_train + batch_size - 1) // batch_size)
total_steps = n_epochs * steps_per_epoch
warmup_steps = max(2, int(0.1 * total_steps))
methods = ("sgd_momentum", "adam_coupled_l2", "adamw_split_warmup_cosine", "hybrid_muon_adamw")
results: dict[str, Any] = {}
lr_trace_sample: list[float] = []
for method in methods:
model = _ArenaSwiGLUClassifier(
d_in=d_in, d_model=d_model, n_layers=n_layers, n_classes=n_classes
)
model.load_state_dict({k: v.clone() for k, v in init_state.items()})
base_lr = 0.015
optimizers: list[torch.optim.Optimizer] = []
use_schedule = False
split_1d_zero_wd = False
muon_count = 0
adamw_count = 0
if method == "sgd_momentum":
base_lr = 0.08
optimizers = [
torch.optim.SGD(
model.parameters(), lr=base_lr, momentum=0.9, nesterov=True, weight_decay=1e-3
)
]
elif method == "adam_coupled_l2":
base_lr = 0.01
# Deliberate coupled L2 weight_decay on all parameters including 1D RMSNorm scales
optimizers = [torch.optim.Adam(model.parameters(), lr=base_lr, weight_decay=0.08)]
elif method == "adamw_split_warmup_cosine":
base_lr = 0.015
groups = build_split_adamw_param_groups(model, weight_decay=0.05)
split_1d_zero_wd = all(
g["weight_decay"] == 0.0 for g in groups if g.get("group_name") == "no_decay_1d"
)
optimizers = [torch.optim.AdamW(groups, lr=base_lr, betas=(0.9, 0.95), eps=1e-8)]
use_schedule = True
elif method == "hybrid_muon_adamw":
base_lr = 0.015
muon_opt, adamw_opt = build_hybrid_muon_adamw_optimizers(
model, lr=base_lr, weight_decay=0.05, momentum=0.95
)
split_1d_zero_wd = all(
g["weight_decay"] == 0.0
for g in adamw_opt.param_groups
if g.get("group_name") == "adamw_1d_no_decay"
)
muon_count = sum(p.numel() for g in muon_opt.param_groups for p in g["params"])
adamw_count = sum(p.numel() for g in adamw_opt.param_groups for p in g["params"])
optimizers = [muon_opt, adamw_opt]
use_schedule = True
else:
raise ValueError(f"Unknown optimizer method: {method}")
gen_perm = torch.Generator().manual_seed(seed + 7)
step_counter = 0
final_train_loss = 0.0
model.train()
for _epoch in range(n_epochs):
perm = torch.randperm(n_train, generator=gen_perm)
for start in range(0, n_train, batch_size):
idx = perm[start : start + batch_size]
xb, yb = x_tr[idx], y_tr[idx]
if use_schedule:
mult = _warmup_cosine_multiplier(step_counter, warmup_steps, total_steps, min_ratio=0.1)
cur_lr = base_lr * mult
for opt in optimizers:
for pg in opt.param_groups:
pg["lr"] = cur_lr
is_sample_step = step_counter % max(1, total_steps // 12) == 0
if method == "hybrid_muon_adamw" and (
is_sample_step or step_counter == total_steps - 1
):
lr_trace_sample.append(float(cur_lr))
for opt in optimizers:
opt.zero_grad()
logits = model(xb)
loss = F.cross_entropy(logits, yb, label_smoothing=label_smoothing)
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
for opt in optimizers:
opt.step()
final_train_loss = float(loss.item())
step_counter += 1
model.eval()
with torch.no_grad():
val_logits = model(x_va)
val_loss = float(F.cross_entropy(val_logits, y_va).item())
val_acc = float((val_logits.argmax(dim=1) == y_va).float().mean().item())
# Measure 1D RMSNorm weight drift from initial 1.0
norm_drifts = [
float((p.detach() - 1.0).abs().mean().item())
for n, p in model.named_parameters()
if "norm" in n.lower()
]
norm_drift = float(sum(norm_drifts) / max(len(norm_drifts), 1))
results[method] = {
"final_train_loss": final_train_loss,
"final_val_loss": val_loss,
"final_val_acc": val_acc,
"norm_weight_drift": norm_drift,
"split_1d_weight_decay_is_zero": split_1d_zero_wd,
"muon_param_count": muon_count,
"adamw_param_count": adamw_count,
}
return {
"methods": results,
"warmup_cosine_lr_trace": lr_trace_sample,
"warmup_steps": int(warmup_steps),
"total_steps": int(total_steps),
}
# ---------------------------------------------------------------------------
# 4. Regularization Audits (Dropout, Label Smoothing, MixUp, CutMix)
# ---------------------------------------------------------------------------
def audit_regularization_techniques(seed: int = 42) -> dict[str, Any]:
"""Verify Inverted Dropout unbiasedness, Label Smoothing finite logit gap, MixUp & CutMix."""
torch.manual_seed(seed)
# 1) Inverted Dropout (p=0.3)
p_drop = 0.3
drop = nn.Dropout(p=p_drop)
x_ones = torch.full((4096, 64), 2.5)
drop.train()
y_train = drop(x_ones)
train_mean = float(y_train.mean().item())
train_zero_frac = float((y_train == 0.0).float().mean().item())
active_vals = y_train[y_train > 0.0]
active_scale_val = float(active_vals.mean().item()) if active_vals.numel() > 0 else 0.0
drop.eval()
y_eval_1 = drop(x_ones)
y_eval_2 = drop(x_ones)
eval_identity_diff = float((y_eval_1 - x_ones).abs().max().item())
eval_repeat_diff = float((y_eval_1 - y_eval_2).abs().max().item())
# 2) Label Smoothing (eps=0.1) vs Hard CE logit margin
n_samples, d_feat, n_cls = 128, 16, 4
x_sep = torch.randn(n_samples, d_feat)
w_true = torch.randn(d_feat, n_cls)
y_sep = torch.argmax(x_sep @ w_true, dim=1)
def _fit_margin(label_smoothing: float) -> float:
torch.manual_seed(seed)
clf = nn.Linear(d_feat, n_cls)
opt = torch.optim.AdamW(clf.parameters(), lr=0.15, weight_decay=0.0)
crit = nn.CrossEntropyLoss(label_smoothing=label_smoothing)
for _ in range(150):
opt.zero_grad()
loss = crit(clf(x_sep), y_sep)
loss.backward()
opt.step()
with torch.no_grad():
logits = clf(x_sep)
true_logits = logits.gather(1, y_sep[:, None])[:, 0]
mask = F.one_hot(y_sep, num_classes=n_cls).bool()
other_max = logits.masked_fill(mask, -1e9).max(dim=1).values
return float((true_logits - other_max).mean().item())
hard_ce_logit_margin = _fit_margin(0.0)
ls_logit_margin = _fit_margin(0.1)
theoretical_ls_gap = math.log(((1.0 - 0.1) * n_cls + 0.1) / 0.1)
# 3) MixUp & CutMix exact convex combination and mask conservation
img_a = torch.zeros(2, 3, 32, 32)
img_b = torch.ones(2, 3, 32, 32)
y_a = F.one_hot(torch.tensor([0, 1]), num_classes=4).float()
y_b = F.one_hot(torch.tensor([2, 3]), num_classes=4).float()
lam_mixup = 0.65
x_mixup = lam_mixup * img_a + (1.0 - lam_mixup) * img_b
y_mixup = lam_mixup * y_a + (1.0 - lam_mixup) * y_b
mixup_y_row_sum = float(y_mixup.sum(dim=1).mean().item())
mixup_x_mean = float(x_mixup.mean().item())
# CutMix: insert bounding box of size r_h x r_w = 12 x 16 inside 32 x 32 image
h_img, w_img = 32, 32
y1, y2 = 6, 18
x1, x2 = 8, 24
r_h, r_w = y2 - y1, x2 - x1
lam_cutmix = 1.0 - float(r_h * r_w) / float(h_img * w_img)
x_cutmix = img_a.clone()
x_cutmix[:, :, y1:y2, x1:x2] = img_b[:, :, y1:y2, x1:x2]
y_cutmix = lam_cutmix * y_a + (1.0 - lam_cutmix) * y_b
# img_a is 0 and img_b is 1 -> fraction of zeros in x_cutmix == lam_cutmix
empirical_unmasked_frac = float((x_cutmix == 0.0).float().mean().item())
return {
"dropout_p": p_drop,
"dropout_train_mean": train_mean,
"dropout_expected_mean": 2.5,
"dropout_train_zero_frac": train_zero_frac,
"dropout_active_scaled_val": active_scale_val,
"dropout_eval_identity_diff": eval_identity_diff,
"dropout_eval_repeat_diff": eval_repeat_diff,
"hard_ce_logit_margin": hard_ce_logit_margin,
"label_smoothing_logit_margin": ls_logit_margin,
"theoretical_ls_gap": float(theoretical_ls_gap),
"mixup_lam": lam_mixup,
"mixup_y_row_sum": mixup_y_row_sum,
"mixup_x_mean": mixup_x_mean,
"cutmix_lam": lam_cutmix,
"cutmix_empirical_unmasked_frac": empirical_unmasked_frac,
"cutmix_y_row_sum": float(y_cutmix.sum(dim=1).mean().item()),
}
# ---------------------------------------------------------------------------
# 5. Early Stopping Plateau State Machine & best_state_dict Restoration
# ---------------------------------------------------------------------------
def run_early_stopping_restoration_bench(
cfg: EarlyStoppingConfig,
seed: int = 42,
) -> dict[str, Any]:
"""Demonstrate patience=0 premature stop, post-optimum overfit drift & best_state_dict rollback."""
torch.manual_seed(seed)
n_train, n_val, n_test, d_in = 72, 160, 200, 48
n_total = n_train + n_val + n_test
x_all = torch.randn(n_total, d_in)
w_true = torch.randn(d_in, 1) / math.sqrt(float(d_in))
y_clean = torch.sin(1.6 * (x_all @ w_true)) + 0.3 * (x_all @ w_true) ** 2
y_noisy = y_clean + 0.65 * torch.randn(n_total, 1)
x_tr, y_tr = x_all[:n_train], y_noisy[:n_train]
x_va, y_va = x_all[n_train : n_train + n_val], y_noisy[n_train : n_train + n_val]
x_te, y_te = x_all[n_train + n_val :], y_noisy[n_train + n_val :]
model = nn.Sequential(
nn.Linear(d_in, 96),
nn.GELU(),
nn.Linear(96, 96),
nn.GELU(),
nn.Linear(96, 1),
)
opt = torch.optim.AdamW(model.parameters(), lr=0.012, weight_decay=0.0)
n_epochs = 80
train_trace: list[float] = []
val_trace: list[float] = []
test_trace: list[float] = []
snapshots: list[dict[str, torch.Tensor]] = []
best_val = float("inf")
best_epoch = 0
best_state: dict[str, torch.Tensor] = {k: v.detach().clone() for k, v in model.state_dict().items()}
patience_counter = 0
stopped_epoch = n_epochs
has_stopped = False
patience0_stop_epoch: int | None = None
patience0_val_loss: float | None = None
prev_val_for_p0 = float("inf")
gen_b = torch.Generator().manual_seed(seed + 19)
for epoch in range(1, n_epochs + 1):
model.train()
# Mini-batch SGD injects slight early val noise so patience=0 trips before true optimum
perm = torch.randperm(n_train, generator=gen_b)
for start in range(0, n_train, 18):
idx = perm[start : start + 18]
opt.zero_grad()
loss_tr = F.mse_loss(model(x_tr[idx]), y_tr[idx])
loss_tr.backward()
opt.step()
model.eval()
with torch.no_grad():
tr_loss = float(F.mse_loss(model(x_tr), y_tr).item())
va_loss = float(F.mse_loss(model(x_va), y_va).item())
te_loss = float(F.mse_loss(model(x_te), y_te).item())
train_trace.append(tr_loss)
val_trace.append(va_loss)
test_trace.append(te_loss)
snapshots.append({k: v.detach().clone() for k, v in model.state_dict().items()})
if patience0_stop_epoch is None and epoch >= 2 and va_loss >= prev_val_for_p0 - cfg.min_delta:
patience0_stop_epoch = epoch
patience0_val_loss = va_loss
prev_val_for_p0 = va_loss
if not has_stopped:
if va_loss < best_val - cfg.min_delta:
best_val = va_loss
best_epoch = epoch
best_state = {k: v.detach().clone() for k, v in model.state_dict().items()}
patience_counter = 0
else:
patience_counter += 1
if cfg.patience > 0 and patience_counter >= cfg.patience:
stopped_epoch = epoch
has_stopped = True
break
if patience0_stop_epoch is None or patience0_val_loss is None:
patience0_stop_epoch = 1
patience0_val_loss = val_trace[0]
# Evaluate final post-patience degraded weights at stopped_epoch (or later overfit end if patience==0)
post_idx = max(0, stopped_epoch - 1)
model.load_state_dict(snapshots[post_idx])
model.eval()
with torch.no_grad():
final_val_loss = float(F.mse_loss(model(x_va), y_va).item())
final_test_loss = float(F.mse_loss(model(x_te), y_te).item())
# Explicitly restore best_state_dict
if cfg.restore_best_weights:
model.load_state_dict(best_state)
model.eval()
with torch.no_grad():
restored_val_loss = float(F.mse_loss(model(x_va), y_va).item())
restored_test_loss = float(F.mse_loss(model(x_te), y_te).item())
return {
"best_epoch": int(best_epoch),
"stopped_epoch": int(stopped_epoch),
"patience0_stop_epoch": int(patience0_stop_epoch),
"patience0_val_loss": float(patience0_val_loss),
"best_val_loss": float(best_val),
"final_val_loss": float(final_val_loss),
"restored_val_loss": float(restored_val_loss),
"final_test_loss": float(final_test_loss),
"restored_test_loss": float(restored_test_loss),
"deploy_gap_val_loss": float(final_val_loss - best_val),
"restore_abs_diff": float(abs(restored_val_loss - best_val)),
"train_loss_trace": train_trace,
"val_loss_trace": val_trace,
}
# ---------------------------------------------------------------------------
# 6. Mixed Precision Bit Physics (fp16 Traps vs bf16 ULP Stagnation & CPU Autocast)
# ---------------------------------------------------------------------------
def audit_mixed_precision_fp16_bf16_cpu(seed: int = 42) -> dict[str, Any]:
"""Verify fp16 underflow/overflow, bf16 ULP swamping vs fp32 master, and CPU bf16 autocast."""
torch.manual_seed(seed)
fp16_small = float(torch.tensor([1e-8], dtype=torch.float16).item())
fp16_large = torch.tensor([70000.0], dtype=torch.float16)
fp16_overflow_is_inf = bool(torch.isinf(fp16_large).item())
bf16_small = float(torch.tensor([1e-8], dtype=torch.bfloat16).item())
bf16_large = float(torch.tensor([70000.0], dtype=torch.bfloat16).item())
# Sub-ULP update stagnation in pure bf16 vs fp32 master accumulation
w_bf16 = torch.tensor([1.0], dtype=torch.bfloat16)
w_fp32 = torch.tensor([1.0], dtype=torch.float32)
step_delta = -1e-4
n_updates = 100
for _ in range(n_updates):
w_bf16 = w_bf16 + torch.tensor([step_delta], dtype=torch.bfloat16)
w_fp32 = w_fp32 + step_delta
pure_bf16_total_change = float((w_bf16 - 1.0).item())
fp32_master_total_change = float((w_fp32 - 1.0).item())
# Real CPU bfloat16 autocast forward + backward step
block = PreNormResidualBlock(d_model=32, d_ff=85)
head = nn.Linear(32, 4)
x = torch.randn(16, 32)
targets = torch.randint(0, 4, (16,))
with torch.autocast("cpu", dtype=torch.bfloat16):
h = block(x)
logits = head(h)
loss = F.cross_entropy(logits, targets)
loss.backward()
all_grads_finite = all(
bool(torch.isfinite(p.grad).all().item())
for m in (block, head)
for p in m.parameters()
if p.grad is not None
)
fp8_e4m3_max = float(torch.finfo(torch.float8_e4m3fn).max)
fp8_e5m2_max = float(torch.finfo(torch.float8_e5m2).max)
return {
"fp16_small_1e8": fp16_small,
"fp16_overflow_70000_is_inf": fp16_overflow_is_inf,
"bf16_small_1e8": bf16_small,
"bf16_large_70000": bf16_large,
"pure_bf16_total_change": pure_bf16_total_change,
"fp32_master_total_change": fp32_master_total_change,
"cpu_bf16_autocast_loss": float(loss.item()),
"cpu_bf16_autocast_loss_finite": bool(math.isfinite(float(loss.item()))),
"cpu_bf16_autocast_grads_finite": all_grads_finite,
"fp8_e4m3_max": fp8_e4m3_max,
"fp8_e5m2_max": fp8_e5m2_max,
}
# ---------------------------------------------------------------------------
# 7. PyTorch 2.x Internals: Strides, view vs reshape, _version & inference_mode
# ---------------------------------------------------------------------------
def audit_tensor_strides_and_version_traps(seed: int = 42) -> dict[str, Any]:
"""Audit untyped_storage().data_ptr(), stride contiguity, _version mutation & inference_mode."""
torch.manual_seed(seed)
x = torch.arange(64 * 64, dtype=torch.float32).reshape(64, 64)
x_ptr = int(x.untyped_storage().data_ptr())
xv = x.view(-1)
view_shares_storage = int(xv.untyped_storage().data_ptr()) == x_ptr
xt = x.t()
xt_shares_storage = int(xt.untyped_storage().data_ptr()) == x_ptr
xt_view_raises = False
try:
_ = xt.view(-1)
except RuntimeError:
xt_view_raises = True
xr = xt.reshape(-1)
xt_reshape_breaks_alias = int(xr.untyped_storage().data_ptr()) != x_ptr
# Contiguous vs non-contiguous row-sum micro-benchmark
mat_c = torch.randn(512, 512)
mat_nc = mat_c.t()
t0 = time.perf_counter()
for _ in range(150):
_ = mat_c.sum(dim=-1)
contig_ms = (time.perf_counter() - t0) * 1000.0
t1 = time.perf_counter()
for _ in range(150):
_ = mat_nc.sum(dim=-1)
noncontig_ms = (time.perf_counter() - t1) * 1000.0
# In-place slice mutation _version backward trap
a = torch.ones((4, 4), requires_grad=True)
h = a * 2.0
version_before = int(h._version)
y = (h * h).sum()
h[:, :2] = 0.0
version_after = int(h._version)
inplace_version_trap_raises = False
try:
y.backward()
except RuntimeError:
inplace_version_trap_raises = True
# torch.no_grad() vs torch.inference_mode() version tracking
with torch.no_grad():
t_ng = torch.ones(4)
ng_ver = int(t_ng._version)
no_grad_tracks_version = ng_ver == 0
inference_mode_disables_version = False
with torch.inference_mode():
t_inf = torch.ones(4)
try:
_ = t_inf._version
except RuntimeError:
inference_mode_disables_version = True
return {
"x_stride": list(x.stride()),
"xt_stride": list(xt.stride()),
"x_is_contiguous": bool(x.is_contiguous()),
"xt_is_contiguous": bool(xt.is_contiguous()),
"view_shares_storage": view_shares_storage,
"xt_shares_storage": xt_shares_storage,
"xt_view_raises_runtime_error": xt_view_raises,
"xt_reshape_breaks_storage_alias": xt_reshape_breaks_alias,
"contig_row_sum_ms": float(contig_ms),
"noncontig_row_sum_ms": float(noncontig_ms),
"slowdown_ratio": float(noncontig_ms / max(contig_ms, 1e-6)),
"version_before": version_before,
"version_after": version_after,
"inplace_version_trap_raises": inplace_version_trap_raises,
"no_grad_tracks_version": no_grad_tracks_version,
"inference_mode_disables_version": inference_mode_disables_version,
}
# ---------------------------------------------------------------------------
# 8. TorchDynamo Explain, aot_eager Compile & Gradient Checkpointing Parity
# ---------------------------------------------------------------------------
class _BrokenItemModel(nn.Module):
"""Module intentionally triggering a TorchDynamo graph break via .item()."""
def __init__(self, inner: nn.Module) -> None:
super().__init__()
self.inner = inner
def forward(self, x: torch.Tensor) -> torch.Tensor:
if float(x.sum().item()) > 0.0:
return self.inner(x)
return self.inner(x) * 0.5
def audit_dynamo_compile_and_checkpoint(seed: int = 42) -> dict[str, Any]:
"""Verify TorchDynamo 0-break explain vs .item() break, aot_eager compile, and checkpoint parity."""
torch.manual_seed(seed)
torch._dynamo.reset()
clean_block = PreNormResidualBlock(d_model=32, d_ff=85)
clean_block.eval()
x = torch.randn(8, 32)
with torch.no_grad():
eager_out = clean_block(x)
exp_clean = torch._dynamo.explain(clean_block)(x)
clean_graph_count = int(exp_clean.graph_count)
clean_graph_break_count = int(exp_clean.graph_break_count)
compiled_clean = torch.compile(clean_block, backend="aot_eager", fullgraph=True)
with torch.no_grad():
compiled_out = compiled_clean(x)
compile_max_abs_diff = float((eager_out - compiled_out).abs().max().item())
broken_model = _BrokenItemModel(PreNormResidualBlock(d_model=32, d_ff=85))
broken_model.eval()
exp_broken = torch._dynamo.explain(broken_model)(x)
broken_graph_break_count = int(exp_broken.graph_break_count)
fullgraph_rejects_broken = False
compiled_broken = torch.compile(broken_model, backend="aot_eager", fullgraph=True)
try:
_ = compiled_broken(x)
except Exception:
fullgraph_rejects_broken = True
torch._dynamo.reset()
# torch.utils.checkpoint gradient parity on 4-block PreNorm stack
d_scale = 1.0 / math.sqrt(8.0)
layers_ref = nn.ModuleList(
[PreNormResidualBlock(d_model=32, d_ff=85, depth_scale=d_scale) for _ in range(4)]
)
layers_ckpt = nn.ModuleList(
[PreNormResidualBlock(d_model=32, d_ff=85, depth_scale=d_scale) for _ in range(4)]
)
layers_ckpt.load_state_dict(layers_ref.state_dict())
x_ref = torch.randn(6, 32, requires_grad=True)
x_ckpt = x_ref.detach().clone().requires_grad_(True)
h_ref = x_ref
for blk in layers_ref:
h_ref = blk(h_ref)
loss_ref = (h_ref**2).mean()
loss_ref.backward()
h_ckpt = x_ckpt
for blk in layers_ckpt:
h_ckpt = torch_checkpoint(blk, h_ckpt, use_reentrant=False)
loss_ckpt = (h_ckpt**2).mean()
loss_ckpt.backward()
assert x_ref.grad is not None and x_ckpt.grad is not None
max_ckpt_grad_diff = float((x_ref.grad - x_ckpt.grad).abs().max().item())
for p_r, p_c in zip(layers_ref.parameters(), layers_ckpt.parameters(), strict=True):
assert p_r.grad is not None and p_c.grad is not None
max_ckpt_grad_diff = max(max_ckpt_grad_diff, float((p_r.grad - p_c.grad).abs().max().item()))
return {
"clean_graph_count": clean_graph_count,
"clean_graph_break_count": clean_graph_break_count,
"compile_backend": "aot_eager",
"compile_max_abs_diff": compile_max_abs_diff,
"broken_graph_break_count": broken_graph_break_count,
"fullgraph_rejects_broken": fullgraph_rejects_broken,
"checkpoint_loss_abs_diff": float(abs(float(loss_ref.item()) - float(loss_ckpt.item()))),
"checkpoint_max_grad_diff": max_ckpt_grad_diff,
}
# ---------------------------------------------------------------------------
# 9. Full End-to-End WB-Ch14 Benchmark Runner & Workbench Panels Builder
# ---------------------------------------------------------------------------
def _log10_drift(ratio: float) -> float:
return float(abs(math.log10(max(abs(ratio), 1e-45))))
def run_full_ch14_wb14_benchmarks(seed: int = 42, quick: bool = False) -> dict[str, Any]:
"""Run all Tier 1 + Tier 2 WB-Ch14 benchmarks and assemble workbench_panels JSON."""
init_cfg = InitBenchConfig(depth=20, width=64, batch_size=64, activation="relu", seed=seed)
ag_cfg = AutogradBenchConfig(seed=seed)
ckpt_cfg = CheckpointMemoryConfig()
roof_cfg = RooflineConfig()
es_cfg = EarlyStoppingConfig(patience=5, min_delta=1e-4, restore_best_weights=True)
# Tier 1 & Tier 2 Autograd, Init, Telgarsky, SwiGLU, BatchNorm
parity = verify_tier1_vs_torch_autograd_parity(ag_cfg)
telgarsky = benchmark_telgarsky_depth_separation(k_values=(1, 2, 3, 4, 5), max_depth2_width=32)
init_prop = benchmark_deep_init_propagation(init_cfg)
swiglu_parity = audit_swiglu_param_flop_parity(d_model=4096)
bn_audit = audit_batchnorm_collapse_and_eval_mode(seed=seed)
# LSE stress check on [-1e4, +1e4]
lse_targets = np.array([2, 0], dtype=np.int64)
lse_logits = np.array([[-1e4, 0.0, 1e4], [1e4, -1e4, 9999.0]], dtype=np.float64)
lse_loss, lse_grad = log_sum_exp_cross_entropy(lse_logits, lse_targets)
lse_probs = lse_grad * 2.0 + np.eye(3)[lse_targets]
# Optimizers, Regularization, Early Stopping
coupled_vs_adamw = audit_adam_coupled_vs_adamw_decoupled(weight_decay=0.1, lr=0.02, n_steps=80)
muon_spec = audit_muon_ns5_spectrum(seed=seed)
arena = benchmark_optimizers_arena(seed=seed, quick=quick)
reg_audit = audit_regularization_techniques(seed=seed)
early_stop = run_early_stopping_restoration_bench(es_cfg, seed=seed)
# Precision, Checkpointing & Roofline
mp_audit = audit_mixed_precision_fp16_bf16_cpu(seed=seed)
ckpt_mem = simulate_checkpointing_tradeoff(ckpt_cfg)
ckpt_l64 = simulate_checkpointing_tradeoff(CheckpointMemoryConfig(n_layers=64))
roofline = compute_roofline_and_fusion_savings(roof_cfg)
# PyTorch 2.x Internals & Compile
stride_audit = audit_tensor_strides_and_version_traps(seed=seed)
dynamo_audit = audit_dynamo_compile_and_checkpoint(seed=seed)
# Extract concise metrics for workbench_panels (zero LaTeX $ or backticks)
m_sgd = arena["methods"]["sgd_momentum"]
m_adam = arena["methods"]["adam_coupled_l2"]
m_adamw = arena["methods"]["adamw_split_warmup_cosine"]
m_muon = arena["methods"]["hybrid_muon_adamw"]
var_small = init_prop["naive_small"]["final_var_ratio"]
var_xavier = init_prop["xavier"]["final_var_ratio"]
var_kaiming = init_prop["kaiming"]["final_var_ratio"]
var_prenorm = init_prop["prenorm_res_scaled"]["final_var_ratio"]
full_act_mb = ckpt_mem["full_tape"]["activation_mb"]
sqrt_act_mb = ckpt_mem["sqrt_uniform"]["activation_mb"]
sac_act_mb = ckpt_mem["selective_sac"]["activation_mb"]
k_rms_un = roofline["kernels"]["rmsnorm_unfused"]["arithmetic_intensity"]
k_rms_fu = roofline["kernels"]["rmsnorm_fused"]["arithmetic_intensity"]
k_glu_un = roofline["kernels"]["swiglu_unfused"]["arithmetic_intensity"]
k_glu_fu = roofline["kernels"]["swiglu_fused"]["arithmetic_intensity"]
workbench_panels = {
"kpis": [
{
"id": "kpi_autograd_parity",
"label": "Tier 1 vs PyTorch & Central Diff Parity",
"value": f"{parity['max_grad_abs_diff']:.2e}",
"unit": f"(FD {parity['central_diff_max_abs_err']:.2e})",
"status": "ok",
"detail": (
f"Pure NumPy TapeTensor matches PyTorch float64 loss diff {parity['loss_abs_diff']:.2e} "
f"and central diff < 1e-6."
),
},
{
"id": "kpi_l20_init_stability",
"label": "L=20 Init & Pre-Norm 1/sqrt(2L) Stability",
"value": f"{var_prenorm:.2f}x",
"unit": f"(Xavier {var_xavier:.1e})",
"status": "ok",
"detail": (
f"Xavier collapses to {var_xavier:.2e}; Kaiming ({var_kaiming:.2f}x) and "
f"Pre-Norm 1/sqrt(2L) ({var_prenorm:.2f}x) stay in O(1) band."
),
},
{
"id": "kpi_batchnorm_b2_collapse",
"label": "BatchNorm B=2 Collapse vs RMSNorm B=1",
"value": f"dev {bn_audit['bn_b2_abs_dev_from_unit']:.1e}",
"unit": f"(RMS B=1 diff {bn_audit['rmsnorm_b1_vs_b32_max_diff']:.1e})",
"status": "warn",
"detail": (
"BatchNorm B=2 snaps channels to +-1.0 with 50% var bias; "
"RMSNorm stays exact across B=1 and B=32."
),
},
{
"id": "kpi_adamw_muon_ns5",
"label": "AdamW Decoupled & Muon NS5 Spectral Band",
"value": f"val {m_muon['final_val_loss']:.3f}",
"unit": f"(acc {m_muon['final_val_acc']:.1%})",
"status": "ok",
"detail": (
f"NS5 maps [0.01,1.0] to [{muon_spec['scalar_ns5_min_sv']:.3f}, "
f"{muon_spec['scalar_ns5_max_sv']:.3f}]; AdamW uniform diff "
f"{coupled_vs_adamw['decoupled_weight_abs_diff']:.1e}."
),
},
{
"id": "kpi_precision_bf16_memory",
"label": "fp16 Trap vs bf16 Master & 16*Psi VRAM",
"value": f"{ckpt_mem['static_breakdown']['static_total_gb']:.0f} GB @ 7B",
"unit": "(bf16 ULP rescued)",
"status": "ok",
"detail": (
"fp16 flushes 1e-8 to 0.0 and 70000 to inf; pure bf16 stalls at 0.0 "
"while fp32 master moves -0.010."
),
},
{
"id": "kpi_dynamo_fusion_roofline",
"label": "TorchDynamo Graph Breaks & Fusion HBM Cut",
"value": f"{dynamo_audit['clean_graph_break_count']} breaks",
"unit": f"(vs .item()={dynamo_audit['broken_graph_break_count']})",
"status": "ok",
"detail": (
f"Bias+GELU+Res saves {roofline['fusion_savings']['bias_gelu_res_hbm_cut_pct']:.1f}% "
f"HBM; RMSNorm saves {roofline['fusion_savings']['rmsnorm_hbm_cut_pct']:.1f}% HBM."
),
},
],
"bars": [
{
"id": "bar_l20_signal_propagation",
"title": "L=20 Signal Variance Drift |log10(Var_L / Var_0)| (Lower is Better)",
"metric_label": "|log10(Var_L / Var_0)|",
"items": [
{
"label": "naive_small",
"value": _log10_drift(var_small),
"display": f"{var_small:.1e} (VANISH)",
"css_class": "is-slow",
},
{
"label": "xavier_relu",
"value": _log10_drift(var_xavier),
"display": f"{var_xavier:.2e} (VANISH)",
"css_class": "is-slow",
},
{
"label": "kaiming_relu",
"value": _log10_drift(var_kaiming),
"display": f"{var_kaiming:.2f}x (O(1))",
"css_class": "is-fast",
},
{
"label": "prenorm_res_scaled",
"value": _log10_drift(var_prenorm),
"display": f"{var_prenorm:.2f}x (O(1))",
"css_class": "is-fast",
},
],
},
{
"id": "bar_optimizer_val_loss",
"title": "Pre-Norm SwiGLU Optimizer Arena Validation Loss (Lower is Better)",
"metric_label": "Val Loss",
"items": [
{
"label": "sgd_momentum",
"value": m_sgd["final_val_loss"],
"display": f"{m_sgd['final_val_loss']:.3f} (acc {m_sgd['final_val_acc']:.1%})",
"css_class": "is-mid",
},
{
"label": "adam_coupled_l2",
"value": m_adam["final_val_loss"],
"display": (
f"{m_adam['final_val_loss']:.3f} "
f"(norm drift {m_adam['norm_weight_drift']:.2f})"
),
"css_class": "is-slow",
},
{
"label": "adamw_split_cosine",
"value": m_adamw["final_val_loss"],
"display": f"{m_adamw['final_val_loss']:.3f} (acc {m_adamw['final_val_acc']:.1%})",
"css_class": "is-fast",
},
{
"label": "hybrid_muon_adamw",
"value": m_muon["final_val_loss"],
"display": f"{m_muon['final_val_loss']:.3f} (acc {m_muon['final_val_acc']:.1%})",
"css_class": "is-fast",
},
],
},
{
"id": "bar_checkpoint_vram_vs_flops",
"title": "Activation Memory vs Recompute Overhead at L=32 (% of Full Tape / Step)",
"metric_label": "Percent (%)",
"items": [
{
"label": "full_tape_act_mb",
"value": 100.0,
"display": f"{full_act_mb:,.0f} MB (100% mem | +0.0% FLOPs)",
"css_class": "is-slow",
},
{
"label": "sqrt_ckpt_act_mb",
"value": 100.0 - ckpt_mem["sqrt_uniform"]["memory_reduction_pct"],
"display": (
f"{sqrt_act_mb:,.0f} MB "
f"(-{ckpt_mem['sqrt_uniform']['memory_reduction_pct']:.1f}% mem)"
),
"css_class": "is-mid",
},
{
"label": "selective_sac_act_mb",
"value": 100.0 - ckpt_mem["selective_sac"]["memory_reduction_pct"],
"display": (
f"{sac_act_mb:,.0f} MB "
f"(-{ckpt_mem['selective_sac']['memory_reduction_pct']:.1f}% mem | "
f"+{ckpt_mem['selective_sac']['extra_flops_pct']:.1f}% FLOPs)"
),
"css_class": "is-fast",
},
{
"label": "sqrt_extra_flops_pct",
"value": ckpt_mem["sqrt_uniform"]["extra_flops_pct"],
"display": f"+{ckpt_mem['sqrt_uniform']['extra_flops_pct']:.2f}% Extra Step FLOPs",
"css_class": "is-mid",
},
],
},
{
"id": "bar_roofline_intensity_fusion",
"title": "Roofline Arithmetic Intensity I (FLOP/B) Before vs After TorchInductor Fusion",
"metric_label": "Intensity (FLOP/B)",
"items": [
{
"label": "rmsnorm_unfused",
"value": k_rms_un,
"display": f"{k_rms_un:.2f} FLOP/B (7Tdb)",
"css_class": "is-slow",
},
{
"label": "rmsnorm_fused",
"value": k_rms_fu,
"display": f"{k_rms_fu:.2f} FLOP/B (-71.4% HBM)",
"css_class": "is-fast",
},
{
"label": "swiglu_unfused",
"value": k_glu_un,
"display": f"{k_glu_un:.2f} FLOP/B (8T*d_ff*b)",
"css_class": "is-slow",
},
{
"label": "swiglu_fused",
"value": k_glu_fu,
"display": f"{k_glu_fu:.2f} FLOP/B (-62.5% HBM)",
"css_class": "is-fast",
},
],
},
],
"tables": [
{
"id": "tbl_init_norm_and_telgarsky",
"title": "Signal Propagation (L=20), Normalization Collapse & Telgarsky Depth Separation",
"columns": ["Regime / Norm", "Layer-20 Fwd Var", "Grad / B=2 Behavior", "Status"],
"rows": [
[
"Xavier on ReLU (L=20)",
f"{var_xavier:.2e}",
f"L1 grad {init_prop['xavier']['layer1_grad_norm']:.2e}",
"VANISH (0.5^20)",
],
[
"Kaiming + PreNorm 1/sqrt(2L)",
f"{var_kaiming:.2f}x | {var_prenorm:.2f}x",
f"L1 grad {init_prop['prenorm_res_scaled']['layer1_grad_norm']:.2f}",
"O(1) STABLE",
],
[
"BatchNorm1d (B=2 / No eval)",
f"Var bias {bn_audit['bn_b2_biased_var_mean']:.2f}",
f"+-1 dev {bn_audit['bn_b2_abs_dev_from_unit']:.1e}",
"COLLAPSE",
],
[
"Telgarsky k=5 vs Depth-2",
f"{telgarsky['by_k'][-1]['exact_pieces']} pieces",
f"m=8 LB {telgarsky['by_k'][-1]['depth2_theoretical_lower_bound']:.3f} > 0.25",
"EXP DEPTH GAP",
],
],
},
{
"id": "tbl_optimizers_and_early_stop",
"title": "Optimizer Preconditioning, Regularization & Early Stopping Rollback",
"columns": ["Optimizer / Stopping", "Val Loss", "Param Group / Decay Rule", "Verdict"],
"rows": [
[
"Coupled L2 Adam",
f"{m_adam['final_val_loss']:.3f}",
(
f"Skew ratio {coupled_vs_adamw['coupled_weight_ratio']:.2f}x | "
f"norm drift {m_adam['norm_weight_drift']:.2f}"
),
"NON-UNIFORM BUG",
],
[
"Split AdamW + WarmupCosine",
f"{m_adamw['final_val_loss']:.3f}",
f"1D decay=0.0 | diff {coupled_vs_adamw['decoupled_weight_abs_diff']:.1e}",
f"PASS ({m_adamw['final_val_acc']:.1%})",
],
[
"HybridMuonAdamW (NS5+Moonlight)",
f"{m_muon['final_val_loss']:.3f}",
(
f"NS5 [{muon_spec['scalar_ns5_min_sv']:.3f},"
f"{muon_spec['scalar_ns5_max_sv']:.3f}]"
),
f"PASS ({m_muon['final_val_acc']:.1%})",
],
[
f"EarlyStop Restore (t*={early_stop['best_epoch']})",
f"{early_stop['restored_val_loss']:.3f} (final {early_stop['final_val_loss']:.3f})",
(
f"p=0 stop @{early_stop['patience0_stop_epoch']} "
f"({early_stop['patience0_val_loss']:.3f})"
),
f"RESTORE diff {early_stop['restore_abs_diff']:.1e}",
],
],
},
{
"id": "tbl_precision_and_memory_budget",
"title": "Mixed-Precision Bit Physics, 16*Psi VRAM & Checkpointing Budget",
"columns": ["Format / Strategy", "7B Static + Act", "Extra FLOPs / ULP", "Numerical Safety"],
"rows": [
[
"fp16 (1-5-10, max 65504)",
"112 GB static (with master)",
"1e-8 -> 0.0 | 70000 -> inf",
"NEEDS GradScaler",
],
[
"Pure bf16 (No fp32 master)",
"14 GB weights only",
f"100x(-1e-4) -> {mp_audit['pure_bf16_total_change']:.1f}",
"ULP STAGNATION",
],
[
"bf16 Compute + fp32 Master",
(
f"{ckpt_mem['static_breakdown']['static_total_gb']:.0f} GB + "
f"{full_act_mb / 1000:.1f} GB act"
),
f"Master delta {mp_audit['fp32_master_total_change']:.4f}",
"SOTA DEFAULT",
],
[
"Sqrt Checkpointing (L=64)",
f"-{ckpt_l64['sqrt_uniform']['memory_reduction_pct']:.1f}% activation mem",
(
f"+{ckpt_l64['sqrt_uniform']['extra_flops_pct']:.2f}% FLOPs "
f"(SAC {ckpt_l64['selective_sac']['extra_flops_pct']:.1f}%)"
),
"O(sqrt(L)) SAFE",
],
],
},
{
"id": "tbl_pytorch_internals_and_compile",
"title": "PyTorch 2.x Tensor Strides, _version Guard, TorchDynamo & Roofline",
"columns": ["Audit Gate", "Observed Metric", "Failure Trap", "CI Canary Result"],
"rows": [
[
"Strided View vs Reshape",
f"xt stride {stride_audit['xt_stride']}",
"xt.view(-1) RuntimeError; reshape copies",
"ALIAS CHECKED",
],
[
"Autograd _version & Inference",
f"v0={stride_audit['version_before']} -> v1={stride_audit['version_after']}",
"h[:,:2]=0 backward crash; inference_mode no ver",
"GUARD VERIFIED",
],
[
"TorchDynamo + aot_eager",
(
f"{dynamo_audit['clean_graph_break_count']} breaks "
f"(diff {dynamo_audit['compile_max_abs_diff']:.1e})"
),
f".item() triggers {dynamo_audit['broken_graph_break_count']} break",
"FULLGRAPH PASS",
],
[
"Roofline & SwiGLU 8/3*d",
f"H100 I*={roofline['ridge_point_h100_bf16']:.1f} FLOP/B",
(
f"gemm_b1={roofline['kernels']['gemm_b1']['arithmetic_intensity']:.1f} "
f"vs large="
f"{roofline['kernels']['gemm_large_batch']['arithmetic_intensity']:.0f}"
),
f"d_ff={swiglu_parity['d_ff_aligned_256']} ALIGNED",
],
],
},
],
}
return {
"config": {
"seed": int(seed),
"quick": bool(quick),
"torch_version": str(torch.__version__),
"device": "cpu",
"compile_backend": "aot_eager",
"output": "artifacts/ch14_wb14_results.json",
},
"workbench_panels": workbench_panels,
"autograd_and_init": {
"tier1_vs_torch_parity": parity,
"lse_stress_test": {
"loss": float(lse_loss),
"probs_sum": float(np.sum(lse_probs, axis=1).mean()),
"finite": bool(math.isfinite(lse_loss) and np.all(np.isfinite(lse_grad))),
},
"telgarsky_depth_separation": telgarsky,
"deep_init_propagation": init_prop,
"swiglu_param_flop_parity": swiglu_parity,
"batchnorm_vs_layernorm_rmsnorm": bn_audit,
},
"optimizers_and_regularization": {
"adam_coupled_vs_adamw_decoupled": coupled_vs_adamw,
"muon_ns5_spectrum": muon_spec,
"optimizer_arena": arena,
"regularization_audit": reg_audit,
"early_stopping_restoration": early_stop,
},
"precision_and_memory": {
"mixed_precision_fp16_bf16_cpu": mp_audit,
"checkpointing_tradeoff_l32": ckpt_mem,
"checkpointing_tradeoff_l64": ckpt_l64,
"roofline_and_fusion": roofline,
},
"pytorch_internals_and_compile": {
"tensor_strides_and_version": stride_audit,
"dynamo_compile_and_checkpoint": dynamo_audit,
},
}
"""End-to-end CLI benchmark runner for WB-Ch14: Neural Networks & PyTorch 2.x Internals."""
from __future__ import annotations
import argparse
import json
import sys
from pathlib import Path
if hasattr(sys.stdout, "reconfigure"):
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
try:
import nn_pytorch_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 nn_pytorch_lab.pytorch_training_lab import run_full_ch14_wb14_benchmarks # noqa: E402
def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
"""Parse CLI arguments for WB-Ch14 benchmark execution."""
parser = argparse.ArgumentParser(
description=(
"Run WB-Ch14: Neural Networks, Autograd Core, Optimizers, "
"Mixed Precision & PyTorch Internals."
)
)
parser.add_argument("--seed", type=int, default=42, help="Deterministic RNG seed.")
parser.add_argument(
"--quick",
action="store_true",
help="Run lighter epoch/sample sizes for fast CI verification (<4s CPU).",
)
parser.add_argument(
"--output",
type=str,
default="artifacts/ch14_wb14_results.json",
help="Output JSON artifact path.",
)
return parser.parse_args(argv)
def main(argv: list[str] | None = None) -> int:
"""Execute Tier 1 + Tier 2 benchmarks, print telemetry summary, and write JSON artifact."""
args = parse_args(argv)
payload = run_full_ch14_wb14_benchmarks(seed=args.seed, quick=args.quick)
payload["config"]["output"] = args.output
ag = payload["autograd_and_init"]
parity = ag["tier1_vs_torch_parity"]
tel = ag["telgarsky_depth_separation"]["by_k"][-1]
init_p = ag["deep_init_propagation"]
bn = ag["batchnorm_vs_layernorm_rmsnorm"]
opt_reg = payload["optimizers_and_regularization"]
coupled = opt_reg["adam_coupled_vs_adamw_decoupled"]
muon_sp = opt_reg["muon_ns5_spectrum"]
arena = opt_reg["optimizer_arena"]["methods"]
es = opt_reg["early_stopping_restoration"]
pm = payload["precision_and_memory"]
mp = pm["mixed_precision_fp16_bf16_cpu"]
ck64 = pm["checkpointing_tradeoff_l64"]
rf = pm["roofline_and_fusion"]
internals = payload["pytorch_internals_and_compile"]
st = internals["tensor_strides_and_version"]
dy = internals["dynamo_compile_and_checkpoint"]
print("=== Ch 14 + WB-Ch14: Neural Networks, Autograd Core & PyTorch 2.x Internals ===")
print(
f"[1] Tier 1 Autograd Parity, Telgarsky Depth & L=20 Init/Norm Stability: "
f"loss_diff={parity['loss_abs_diff']:.2e}, "
f"grad_diff={parity['max_grad_abs_diff']:.2e}, "
f"FD_err={parity['central_diff_max_abs_err']:.2e} | "
f"Telgarsky k={tel['k']} ({tel['exact_pieces']} pieces, "
f"m={tel['depth2_eval_width']} LB={tel['depth2_theoretical_lower_bound']:.3f}) | "
f"L20 Var(Xavier={init_p['xavier']['final_var_ratio']:.2e}, "
f"Kaiming={init_p['kaiming']['final_var_ratio']:.2f}, "
f"PreNorm={init_p['prenorm_res_scaled']['final_var_ratio']:.2f}) | "
f"BN B=2 dev={bn['bn_b2_abs_dev_from_unit']:.1e} "
f"vs RMS B=1 diff={bn['rmsnorm_b1_vs_b32_max_diff']:.1e}"
)
print(
"[2] Optimizers (Adam Coupled Bug vs AdamW, Muon NS5 Moonlight), "
"Regularization & Early Stopping: "
f"Coupled Ratio={coupled['coupled_weight_ratio']:.2f}x "
f"vs AdamW Diff={coupled['decoupled_weight_abs_diff']:.1e} | "
f"NS5=[{muon_sp['scalar_ns5_min_sv']:.4f}, {muon_sp['scalar_ns5_max_sv']:.4f}] | "
f"Arena ValLoss(AdamW={arena['adamw_split_warmup_cosine']['final_val_loss']:.3f}, "
f"Muon={arena['hybrid_muon_adamw']['final_val_loss']:.3f}, "
f"acc={arena['hybrid_muon_adamw']['final_val_acc']:.1%}) | "
f"EarlyStop best@{es['best_epoch']}={es['best_val_loss']:.3f} "
f"vs final={es['final_val_loss']:.3f} (restore_diff={es['restore_abs_diff']:.1e})"
)
print(
"[3] Mixed Precision (fp16 Trap vs bf16 Master + CPU Autocast), "
"Checkpointing & Roofline: "
f"fp16(1e-8->{mp['fp16_small_1e8']}, "
f"70000->inf={mp['fp16_overflow_70000_is_inf']}) | "
f"bf16 stagnate={mp['pure_bf16_total_change']:.1f} "
f"vs fp32 master={mp['fp32_master_total_change']:.4f} | "
f"7B Static={ck64['static_breakdown']['static_total_gb']:.0f}GB | "
f"L=64 SqrtCkpt=-{ck64['sqrt_uniform']['memory_reduction_pct']:.1f}% mem "
f"(+{ck64['sqrt_uniform']['extra_flops_pct']:.2f}% FLOPs) | "
f"H100 I*={rf['ridge_point_h100_bf16']:.1f} FLOP/B, "
f"Fusion Cut(Bias+GELU+Res=-{rf['fusion_savings']['bias_gelu_res_hbm_cut_pct']:.2f}%, "
f"RMSNorm=-{rf['fusion_savings']['rmsnorm_hbm_cut_pct']:.2f}%)"
)
print(
"[4] PyTorch 2.x Internals "
"(Strides, _version, inference_mode, Dynamo Explain & Checkpointing): "
f"xt.view raises={st['xt_view_raises_runtime_error']}, "
f"reshape_alias_broken={st['xt_reshape_breaks_storage_alias']}, "
f"inplace _version trap={st['inplace_version_trap_raises']}, "
f"inf_mode_no_ver={st['inference_mode_disables_version']} | "
f"Dynamo clean_breaks={dy['clean_graph_break_count']} "
f"vs .item()_breaks={dy['broken_graph_break_count']} "
f"(aot_eager diff={dy['compile_max_abs_diff']:.1e}, "
f"ckpt_grad_diff={dy['checkpoint_max_grad_diff']:.1e})"
)
out_path = Path(args.output)
out_path.parent.mkdir(parents=True, exist_ok=True)
out_path.write_text(json.dumps(payload, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
return 0
if __name__ == "__main__":
raise SystemExit(main())
"""16 automated deterministic CPU-only pytest contracts & AST guard for WB-Ch14 (nn_pytorch_lab)."""
from __future__ import annotations
import ast
import json
import re
import subprocess
import sys
from pathlib import Path
import numpy as np
import pytest
import torch
from pydantic import ValidationError
from nn_pytorch_lab.autograd_core import (
AutogradBenchConfig,
CheckpointMemoryConfig,
EarlyStoppingConfig,
InitBenchConfig,
OptimizerConfig,
RooflineConfig,
TapeTensor,
audit_adam_coupled_vs_adamw_decoupled,
audit_muon_ns5_spectrum,
audit_swiglu_param_flop_parity,
benchmark_deep_init_propagation,
benchmark_telgarsky_depth_separation,
central_diff_grad_check,
compute_roofline_and_fusion_savings,
log_sum_exp_cross_entropy,
moonlight_rms_scale,
simulate_checkpointing_tradeoff,
telgarsky_triangle_wave,
zeropower_via_newtonschulz5,
)
from nn_pytorch_lab.pytorch_training_lab import (
PreNormResidualBlock,
audit_batchnorm_collapse_and_eval_mode,
audit_dynamo_compile_and_checkpoint,
audit_mixed_precision_fp16_bf16_cpu,
audit_regularization_techniques,
audit_tensor_strides_and_version_traps,
benchmark_optimizers_arena,
build_split_adamw_param_groups,
run_early_stopping_restoration_bench,
verify_tier1_vs_torch_autograd_parity,
)
LAB_ROOT = Path(__file__).resolve().parents[1]
FORBIDDEN_UNSAFE_IMPORTS = {
"pickle",
"_pickle",
"cPickle",
"joblib",
"cloudpickle",
"dill",
"shelve",
"marshal",
}
# ---------------------------------------------------------------------------
# Test 01: Strict Pydantic v2 Extra-Forbid Contracts & Domain Bounds
# ---------------------------------------------------------------------------
def test_01_pydantic_configs_strict_forbid() -> None:
with pytest.raises(ValidationError):
InitBenchConfig(unknown_field=123) # type: ignore[call-arg]
with pytest.raises(ValidationError):
AutogradBenchConfig(extra_param=True) # type: ignore[call-arg]
with pytest.raises(ValidationError):
OptimizerConfig(momentum=1.0) # must be < 1.0
with pytest.raises(ValidationError):
InitBenchConfig(depth=1) # must be >= 2
with pytest.raises(ValidationError):
CheckpointMemoryConfig(n_layers=2) # must be >= 4
with pytest.raises(ValidationError):
RooflineConfig(peak_tflops=-10.0)
with pytest.raises(ValidationError):
EarlyStoppingConfig(patience=-1)
cfg = InitBenchConfig()
assert cfg.depth == 20
assert cfg.width == 64
# ---------------------------------------------------------------------------
# Test 02: Pure NumPy TapeTensor Autograd & Central Finite-Diff Gradcheck
# ---------------------------------------------------------------------------
def test_02_numpy_autograd_microengine_central_diff_gradcheck() -> None:
rng = np.random.default_rng(42)
b, d_in, d_hid, k = 4, 5, 7, 3
x_np = rng.normal(0.0, 0.8, size=(b, d_in))
gamma_np = 1.0 + rng.normal(0.0, 0.1, size=(d_in,))
ln_gamma_np = 1.0 + rng.normal(0.0, 0.1, size=(d_in,))
ln_beta_np = rng.normal(0.0, 0.1, size=(d_in,))
wg_np = rng.normal(0.0, 0.4, size=(d_hid, d_in))
wu_np = rng.normal(0.0, 0.4, size=(d_hid, d_in))
wd_np = rng.normal(0.0, 0.4, size=(d_in, d_hid))
w_gelu_np = rng.normal(0.0, 0.4, size=(d_hid, d_in))
w_cls_np = rng.normal(0.0, 0.4, size=(k, d_hid))
targets = np.array([0, 2, 1, 0], dtype=np.int64)
tx = TapeTensor(x_np, requires_grad=True)
t_gamma = TapeTensor(gamma_np, requires_grad=True)
t_ln_g = TapeTensor(ln_gamma_np, requires_grad=True)
t_ln_b = TapeTensor(ln_beta_np, requires_grad=True)
twg = TapeTensor(wg_np, requires_grad=True)
twu = TapeTensor(wu_np, requires_grad=True)
twd = TapeTensor(wd_np, requires_grad=True)
twgelu = TapeTensor(w_gelu_np, requires_grad=True)
twcls = TapeTensor(w_cls_np, requires_grad=True)
h1 = tx.rmsnorm(t_gamma, eps=1e-6)
h2 = h1.swiglu(twg, twu, twd) + h1.layernorm(t_ln_g, t_ln_b, eps=1e-5)
h3 = (h2.matmul(twgelu.T).gelu() - 0.1 * h2.matmul(twgelu.T).relu()).sum(axis=None)
# Also compose directly through logits to CE loss
logits = (h2.matmul(twgelu.T).gelu()).matmul(twcls.T)
loss = logits.cross_entropy_logits(targets) + 0.01 * h3
loss.backward()
def _eval_x(arr: np.ndarray) -> float:
nx = TapeTensor(arr)
nh1 = nx.rmsnorm(TapeTensor(gamma_np), eps=1e-6)
nh2 = nh1.swiglu(TapeTensor(wg_np), TapeTensor(wu_np), TapeTensor(wd_np)) + nh1.layernorm(
TapeTensor(ln_gamma_np), TapeTensor(ln_beta_np), eps=1e-5
)
h_gelu_proj = nh2.matmul(TapeTensor(w_gelu_np).T)
nh3 = (h_gelu_proj.gelu() - 0.1 * h_gelu_proj.relu()).sum()
nlogits = h_gelu_proj.gelu().matmul(TapeTensor(w_cls_np).T)
return float((nlogits.cross_entropy_logits(targets) + 0.01 * nh3).data)
check_x = central_diff_grad_check(_eval_x, x_np, tx.grad, eps=1e-6)
assert check_x["passed"] is True
assert float(check_x["max_abs_err"]) < 1e-6
def _eval_wg(arr: np.ndarray) -> float:
nh1 = TapeTensor(x_np).rmsnorm(TapeTensor(gamma_np), eps=1e-6)
nh2 = nh1.swiglu(TapeTensor(arr), TapeTensor(wu_np), TapeTensor(wd_np)) + nh1.layernorm(
TapeTensor(ln_gamma_np), TapeTensor(ln_beta_np), eps=1e-5
)
h_gelu_proj = nh2.matmul(TapeTensor(w_gelu_np).T)
nh3 = (h_gelu_proj.gelu() - 0.1 * h_gelu_proj.relu()).sum()
nlogits = h_gelu_proj.gelu().matmul(TapeTensor(w_cls_np).T)
return float((nlogits.cross_entropy_logits(targets) + 0.01 * nh3).data)
check_wg = central_diff_grad_check(_eval_wg, wg_np, twg.grad, eps=1e-6)
assert check_wg["passed"] is True
assert float(check_wg["max_abs_err"]) < 1e-6
# ---------------------------------------------------------------------------
# Test 03: Tier 1 NumPy vs Tier 2 PyTorch Float64 Autograd Exact Parity
# ---------------------------------------------------------------------------
def test_03_tier1_numpy_vs_torch_autograd_exact_parity() -> None:
res = verify_tier1_vs_torch_autograd_parity(AutogradBenchConfig(seed=42))
assert res["parity_passed"] is True
assert float(res["loss_abs_diff"]) < 1e-8
assert float(res["max_grad_abs_diff"]) < 1e-5
assert float(res["central_diff_max_abs_err"]) < 1e-6
# ---------------------------------------------------------------------------
# Test 04: Deep L=20 Init Variance & Pre-Norm 1/sqrt(2L) Residual Scaling
# ---------------------------------------------------------------------------
def test_04_deep_l20_init_variance_and_prenorm_residual_scaling() -> None:
res = benchmark_deep_init_propagation(InitBenchConfig(depth=20, width=64, batch_size=64, seed=42))
assert res["naive_small"]["final_var_ratio"] < 1e-4
assert res["xavier"]["final_var_ratio"] < 1e-4
assert res["naive_large"]["final_var_ratio"] > 1e3
assert 0.2 <= res["kaiming"]["final_var_ratio"] <= 5.0
assert 0.2 <= res["prenorm_res_scaled"]["final_var_ratio"] <= 5.0
assert 0.2 <= res["prenorm_res_scaled"]["layer1_grad_norm"] <= 5.0
# ---------------------------------------------------------------------------
# Test 05: Telgarsky Exponential Depth Separation & SwiGLU 8/3*d Parity
# ---------------------------------------------------------------------------
def test_05_telgarsky_triangle_wave_exponential_pieces_and_swiglu_parity() -> None:
x_pts = np.array([0.0, 0.25, 0.5, 0.75, 1.0])
phi1 = telgarsky_triangle_wave(x_pts, k=1)
assert np.allclose(phi1, [0.0, 0.5, 1.0, 0.5, 0.0], atol=1e-12)
tel = benchmark_telgarsky_depth_separation(k_values=(1, 2, 3, 4, 5), max_depth2_width=32)
for row in tel["by_k"]:
k = row["k"]
assert row["exact_pieces"] == 2**k
assert row["empirical_pieces"] == 2**k
assert row["exact_peaks"] == 2 ** (k - 1)
assert row["empirical_peaks"] == 2 ** (k - 1)
if row["depth2_eval_width"] < 2 ** (k - 1) - 2:
assert row["depth2_theoretical_lower_bound"] > 0.25
assert row["empirical_depth2_disagreement"] >= 0.25
swi = audit_swiglu_param_flop_parity(d_model=4096)
assert swi["params_swiglu_exact"] == swi["params_std"]
assert swi["flops_per_token_swiglu_exact"] == swi["flops_per_token_std"]
assert swi["d_ff_aligned_256"] == 11008
# ---------------------------------------------------------------------------
# Test 06: BatchNorm B=2 Collapse & eval() Trap vs LayerNorm & RMSNorm
# ---------------------------------------------------------------------------
def test_06_batchnorm_b2_collapse_and_eval_trap_vs_layernorm_rmsnorm() -> None:
bn = audit_batchnorm_collapse_and_eval_mode(seed=42)
assert bn["bn_b1_raises_value_error"] is True
assert bn["bn_b2_abs_dev_from_unit"] < 1e-4
assert 0.40 <= bn["bn_b2_biased_var_mean"] <= 0.60
assert bn["eval_running_mean_drift"] == pytest.approx(0.0, abs=1e-12)
assert bn["forgot_eval_running_mean_drift"] > 0.1
assert bn["ln_b1_vs_b32_max_diff"] < 1e-6
assert bn["rmsnorm_b1_vs_b32_max_diff"] < 1e-6
assert bn["rmsnorm_weight_scale_max_diff"] < 1e-5
# ---------------------------------------------------------------------------
# Test 07: LSE CrossEntropy Stability & Coupled Adam vs Decoupled AdamW
# ---------------------------------------------------------------------------
def test_07_lse_crossentropy_stability_and_optimizer_adam_coupled_bug() -> None:
extreme_logits = np.array([[-1e4, 0.0, 1e4], [1e4, -1e4, 9999.0]], dtype=np.float64)
targets = np.array([2, 0], dtype=np.int64)
loss, grad = log_sum_exp_cross_entropy(extreme_logits, targets)
assert np.isfinite(loss)
assert np.all(np.isfinite(grad))
probs = grad * 2.0 + np.eye(3)[targets]
assert np.allclose(np.sum(probs, axis=1), 1.0, atol=1e-12)
opt_audit = audit_adam_coupled_vs_adamw_decoupled(weight_decay=0.1, lr=0.02, n_steps=80)
assert opt_audit["coupled_weight_ratio"] > 1.5
assert opt_audit["decoupled_weight_abs_diff"] < 1e-5
# ---------------------------------------------------------------------------
# Test 08: Muon NS5 Spectral Contraction & Moonlight RMS Invariance
# ---------------------------------------------------------------------------
def test_08_muon_newton_schulz5_and_moonlight_rms_invariance() -> None:
ns5 = audit_muon_ns5_spectrum(shapes=((16, 128), (64, 64), (128, 16)), seed=42)
assert 0.68 <= ns5["scalar_ns5_min_sv"] <= ns5["scalar_ns5_max_sv"] <= 1.14
assert 0.68 <= ns5["matrix_ns5_min_sv"] <= ns5["matrix_ns5_max_sv"] <= 1.14
for _shape_key, stats in ns5["by_shape"].items():
assert 0.12 <= stats["scaled_update_rms"] <= 0.28
# Verify native torch.optim.Muon(..., adjust_lr_fn="match_rms_adamw") parity
torch.manual_seed(42)
lr = 0.01
for shape in ((16, 128), (64, 64), (128, 16)):
w = torch.zeros(shape, requires_grad=True)
opt = torch.optim.Muon(
[w],
lr=lr,
weight_decay=0.0,
momentum=0.95,
nesterov=True,
ns_steps=5,
adjust_lr_fn="match_rms_adamw",
)
w.grad = torch.randn(shape)
opt.step()
update_rms = float(w.detach().pow(2).mean().sqrt().item())
assert 0.12 * lr <= update_rms <= 0.28 * lr
# Smoke check direct zeropower & moonlight helper
z = zeropower_via_newtonschulz5(np.random.default_rng(7).normal(size=(8, 16)), steps=5)
assert z.shape == (8, 16)
assert moonlight_rms_scale(16, 128) == pytest.approx(0.2 * np.sqrt(128.0))
# ---------------------------------------------------------------------------
# Test 09: PyTorch Training Arena (Split AdamW vs HybridMuonAdamW + WarmupCosine)
# ---------------------------------------------------------------------------
def test_09_pytorch_training_arena_adamw_hybrid_muon_warmup_cosine() -> None:
arena = benchmark_optimizers_arena(seed=42, quick=True)
methods = arena["methods"]
assert methods["adamw_split_warmup_cosine"]["split_1d_weight_decay_is_zero"] is True
assert methods["hybrid_muon_adamw"]["split_1d_weight_decay_is_zero"] is True
assert methods["adamw_split_warmup_cosine"]["final_val_acc"] >= 0.85
assert methods["hybrid_muon_adamw"]["final_val_acc"] >= 0.85
assert (
methods["adam_coupled_l2"]["norm_weight_drift"]
> methods["adamw_split_warmup_cosine"]["norm_weight_drift"]
)
# Direct check on build_split_adamw_param_groups
blk = PreNormResidualBlock(d_model=16)
groups = build_split_adamw_param_groups(blk, weight_decay=0.1)
assert any(g["weight_decay"] == 0.0 for g in groups)
assert any(g["weight_decay"] == pytest.approx(0.1) for g in groups)
# ---------------------------------------------------------------------------
# Test 10: Regularization (Inverted Dropout, Label Smoothing, MixUp, CutMix)
# ---------------------------------------------------------------------------
def test_10_regularization_dropout_label_smoothing_mixup_cutmix() -> None:
reg = audit_regularization_techniques(seed=42)
assert abs(reg["dropout_train_mean"] - reg["dropout_expected_mean"]) < 0.05
assert reg["dropout_eval_identity_diff"] == pytest.approx(0.0, abs=1e-12)
assert reg["dropout_eval_repeat_diff"] == pytest.approx(0.0, abs=1e-12)
assert reg["label_smoothing_logit_margin"] < reg["hard_ce_logit_margin"]
assert reg["mixup_y_row_sum"] == pytest.approx(1.0, abs=1e-6)
assert reg["cutmix_empirical_unmasked_frac"] == pytest.approx(reg["cutmix_lam"], abs=1e-12)
assert reg["cutmix_y_row_sum"] == pytest.approx(1.0, abs=1e-6)
# ---------------------------------------------------------------------------
# Test 11: Early Stopping Patience=0 Trap & Best State Dict Restoration
# ---------------------------------------------------------------------------
def test_11_early_stopping_patience_and_best_state_dict_restoration() -> None:
es = run_early_stopping_restoration_bench(
EarlyStoppingConfig(patience=5, min_delta=1e-4, restore_best_weights=True),
seed=42,
)
assert es["patience0_stop_epoch"] < es["best_epoch"] < es["stopped_epoch"]
assert es["patience0_val_loss"] > es["best_val_loss"]
assert es["final_val_loss"] > es["best_val_loss"]
assert es["restore_abs_diff"] < 1e-12
assert es["restored_test_loss"] <= es["final_test_loss"]
# ---------------------------------------------------------------------------
# Test 12: Mixed Precision fp16 Underflow/Overflow, bf16 ULP Stagnation & CPU Autocast
# ---------------------------------------------------------------------------
def test_12_mixed_precision_fp16_underflow_bf16_stagnation_and_cpu_autocast() -> None:
mp = audit_mixed_precision_fp16_bf16_cpu(seed=42)
assert mp["fp16_small_1e8"] == 0.0
assert mp["fp16_overflow_70000_is_inf"] is True
assert mp["bf16_small_1e8"] > 0.0
assert np.isfinite(mp["bf16_large_70000"])
assert mp["pure_bf16_total_change"] == 0.0
assert mp["fp32_master_total_change"] == pytest.approx(-0.01, abs=1e-5)
assert mp["cpu_bf16_autocast_loss_finite"] is True
assert mp["cpu_bf16_autocast_grads_finite"] is True
# ---------------------------------------------------------------------------
# Test 13: Gradient Checkpointing O(sqrt(L)) (+33.3% FLOPs) & PyTorch Checkpoint Parity
# ---------------------------------------------------------------------------
def test_13_gradient_checkpointing_memory_and_torch_checkpoint_parity() -> None:
ckpt_64 = simulate_checkpointing_tradeoff(CheckpointMemoryConfig(n_layers=64))
assert ckpt_64["sqrt_uniform"]["memory_reduction_pct"] >= 70.0
assert abs(ckpt_64["sqrt_uniform"]["extra_flops_pct"] - (100.0 / 3.0)) < 1e-3
assert ckpt_64["selective_sac"]["extra_flops_pct"] < 15.0
dy = audit_dynamo_compile_and_checkpoint(seed=42)
assert dy["checkpoint_loss_abs_diff"] < 1e-7
assert dy["checkpoint_max_grad_diff"] < 1e-6
# ---------------------------------------------------------------------------
# Test 14: Hardware Roofline Intensity, 16*Psi VRAM & Fusion Byte Savings
# ---------------------------------------------------------------------------
def test_14_roofline_intensity_and_fusion_byte_savings() -> None:
ckpt = simulate_checkpointing_tradeoff(CheckpointMemoryConfig(param_billions=7.0))
assert ckpt["static_breakdown"]["static_total_gb"] == pytest.approx(112.0)
rf = compute_roofline_and_fusion_savings(RooflineConfig())
assert rf["ridge_point_h100_bf16"] == pytest.approx(295.22388, rel=1e-3)
assert rf["ridge_point_a100_bf16"] == pytest.approx(153.01618, rel=1e-3)
kernels = rf["kernels"]
mem_kernels = (
"rmsnorm_unfused",
"rmsnorm_fused",
"swiglu_unfused",
"swiglu_fused",
"adamw_step",
"gemm_b1",
)
for mem_name in mem_kernels:
assert kernels[mem_name]["regime"] == "memory_bound"
assert kernels[mem_name]["arithmetic_intensity"] < rf["ridge_point_a100_bf16"]
assert kernels["gemm_large_batch"]["regime"] == "compute_bound"
assert kernels["gemm_large_batch"]["arithmetic_intensity"] > rf["ridge_point_h100_bf16"]
assert rf["fusion_savings"]["bias_gelu_res_hbm_cut_pct"] == pytest.approx(57.142857, abs=1e-3)
assert rf["fusion_savings"]["rmsnorm_hbm_cut_pct"] == pytest.approx(71.428571, abs=1e-3)
# ---------------------------------------------------------------------------
# Test 15: Tensor Strides, view vs reshape, _version Trap & TorchDynamo Explain
# ---------------------------------------------------------------------------
def test_15_tensor_strides_view_reshape_version_trap_and_dynamo_explain() -> None:
st = audit_tensor_strides_and_version_traps(seed=42)
assert st["view_shares_storage"] is True
assert st["xt_view_raises_runtime_error"] is True
assert st["xt_reshape_breaks_storage_alias"] is True
assert st["inplace_version_trap_raises"] is True
assert st["no_grad_tracks_version"] is True
assert st["inference_mode_disables_version"] is True
dy = audit_dynamo_compile_and_checkpoint(seed=42)
assert dy["clean_graph_break_count"] == 0
assert dy["clean_graph_count"] == 1
assert dy["broken_graph_break_count"] >= 1
assert dy["fullgraph_rejects_broken"] is True
assert dy["compile_max_abs_diff"] < 1e-6
# ---------------------------------------------------------------------------
# Test 16: CLI Demo Workbench JSON Schema & AST Deserialization Security Guard
# ---------------------------------------------------------------------------
def test_16_cli_demo_workbench_json_schema_and_ast_deserialization_guard(tmp_path: Path) -> None:
out_json = tmp_path / "ch14_wb14_quick.json"
proc = subprocess.run(
[
sys.executable,
str(LAB_ROOT / "scripts" / "run_lab_demo.py"),
"--seed",
"42",
"--quick",
"--output",
str(out_json),
],
cwd=str(LAB_ROOT),
capture_output=True,
text=True,
check=False,
)
assert proc.returncode == 0, f"CLI failed: {proc.stderr}"
payload = json.loads(out_json.read_text(encoding="utf-8"))
for key in (
"config",
"workbench_panels",
"autograd_and_init",
"optimizers_and_regularization",
"precision_and_memory",
"pytorch_internals_and_compile",
):
assert key in payload
wb = payload["workbench_panels"]
assert len(wb["kpis"]) == 6
assert len(wb["bars"]) == 4
assert len(wb["tables"]) == 4
# Ensure clean plain text inside workbench_panels (no LaTeX $ or raw backticks)
wb_str = json.dumps(wb, ensure_ascii=False)
assert "`" not in wb_str
assert not re.search(r"\$", wb_str)
# AST security guard: ban ONLY unsafe deserialization & keep Tier 1 pure from torch
py_files = sorted(
list((LAB_ROOT / "src").rglob("*.py"))
+ list((LAB_ROOT / "scripts").rglob("*.py"))
+ list((LAB_ROOT / "tests").rglob("*.py"))
)
assert len(py_files) >= 5
violations: list[str] = []
for fpath in py_files:
tree = ast.parse(fpath.read_text(encoding="utf-8"), filename=str(fpath))
for node in ast.walk(tree):
if isinstance(node, ast.Import):
for alias in node.names:
root_mod = alias.name.split(".", 1)[0]
if root_mod in FORBIDDEN_UNSAFE_IMPORTS:
violations.append(f"{fpath.name}: import {alias.name}")
if fpath.name == "autograd_core.py" and root_mod == "torch":
violations.append("autograd_core.py must not import torch")
elif isinstance(node, ast.ImportFrom) and node.module:
root_mod = node.module.split(".", 1)[0]
if root_mod in FORBIDDEN_UNSAFE_IMPORTS:
violations.append(f"{fpath.name}: from {node.module} import ...")
if fpath.name == "autograd_core.py" and root_mod == "torch":
violations.append("autograd_core.py must not import torch")
assert violations == [], f"AST policy violations found: {violations}"
WB-Ch14 (Test 05), tại \(k=5\) và \(m=8\), cận dưới lý thuyết là 0.344 > 0.25 (thực nghiệm 0.491).
WB-Ch14 (Test 04), vì sao khởi tạo Xavier trên mạng ReLU sụp đổ còn Kaiming và Pre-Norm 1/\sqrt{2L} giữ ổn định bậc \(\mathcal{O}(1)\)?WB-Ch14 (Test 04), xavier tụt phương sai lớp 20 xuống 1.02e-06 (VANISH), naive_large nổ 7.86e+11, còn kaiming (1.07x) và prenorm_res_scaled (1.59x, L1 grad = 1.25) giữ vững dải ổn định \(\mathcal{O}(1)\).
SwiGLU và các lớp chuẩn hóa (BatchNorm, LayerNorm, RMSNorm) được kiểm chứng trong WB-Ch14 (Test 05, Test 06), phát biểu nào ĐÚNG?B=2, \(\hat{x}_{1,j} = \operatorname{sgn}(x_{1,j}-x_{2,j}) \in \{-1, +1\}\) làm BatchNorm mất toàn bộ biên độ liên tục (Test 06); RMSNorm chỉ bất biến theo tỷ lệ dương \(\alpha\mathbf{W}\) (4.77e-07) chứ không bất biến theo phép dịch.
autograd trong PyTorch 2.x (WB-Ch14, Test 15), kết luận kỹ thuật nào CHÍNH XÁC?reshape() âm thầm cấp phát bản sao mới khi stride không liên tục (Test 15). no_grad() vẫn duy trì _version và view metadata để tensor có thể vào đồ thị sau này, còn inference_mode() vô hiệu hóa cả hai (truy cập ._version ném RuntimeError).
PyTorch 2), Mô hình Roofline (H100 bf16 \(I^* = 295.2\text{ FLOP/B}\)) và kiểm toán WB-Ch14 (Test 14, Test 15), phát biểu nào ĐÚNG?RMSNorm (0.36 -> 1.25), SwiGLU (0.31 -> 0.83), AdamW (0.43) và gemm_b1 (1.00) đều nằm sâu dưới điểm gãy H100 295.2 FLOP/B (memory_bound). Chỉ gemm_large_batch (682.67 FLOP/B) vượt điểm gãy vào vùng compute_bound.
WB-Ch14 (Test 12, Test 13), điều gì xảy ra với fp16, bf16 không có trọng số chủ fp32, và Gradient Checkpointing tại \(L=64\)?bf16 có 8 bit mũ khớp fp32 (không cần GradScaler) nhưng chỉ 7 bit phần trị (\(\varepsilon_{\text{mach}} = 2^{-7}\)), nên bắt buộc phải có fp32 master copy trong 16*Psi (2+2+4+4+4). Checkpointing thêm đúng 1 lượt xuôi (4L vs 3L \(\Rightarrow\) +33.33% tổng bước).
Adam ghép \(L_2\), AdamW tách nhóm 2D/1D và HybridMuonAdamW trong WB-Ch14 (Test 07, Test 08, Test 09), phát biểu nào ĐÚNG?Muon lên tham số 1D/embedding phá hủy tỷ lệ kênh và làm rối token hiếm (Moonlight, 2025). Tách riêng 2D hidden cho Muon và 1D/đầu ra/head với weight_decay=0.0 trên 1D cho AdamW mới đảm bảo hội tụ sạch (Test 08, Test 09).
Early Stopping) của WB-Ch14 (Test 10, Test 11), sai lầm nào gây thiệt hại lớn nhất ngoài sản xuất và cách khắc phục đúng là gì?WB-Ch14 (Test 11), việc quên khôi phục best_state_dict làm đội thêm deploy_gap_val_loss = +0.035 và đẩy test_loss xấu đi từ 1.616 -> 1.707. Kiểm thử val_loss phải luôn chạy dưới model.eval() trên nhãn sạch không trộ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 Tách sâu Lũy thừa Telgarsky & Cân bằng Tham số SwiGLU 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Dùng quy nạp theo \(k\) trên sóng tam giác \(\phi_\triangle\) chứng minh \(\phi_k\) có đúng \(2^k\) đoạn tuyến tính liên tiếp và \(2^{k-1}\) đỉnh, suy ra cận dưới tỷ lệ sai khác \(\frac{1}{2}(1 - \frac{m+2}{2^k})\) cho mạng 2 lớp rộng \(m\).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Giải phương trình \(3 \cdot d \cdot d_{\text{ff}} = 2 \cdot d \cdot (4d)\) tìm \(d_{\text{ff}} = \frac{8}{3}d\) rồi đối chiếu trên telgarsky_triangle_wave, benchmark_telgarsky_depth_separation và audit_swiglu_param_flop_parity.
Tiêu chí Đáp án & Số đối chứng
Tại \(k=5\), \(\phi_5\) đạt 32 đoạn và 16 đỉnh; với \(m=8\), cận dưới đạt 0.344 > 0.25 (thực nghiệm 0.491). Tại \(d=4096\), SwiGLU khớp chính xác 134.2M tham số ở d_ff = 10922.67 và căn bội 256 TensorCore tại 11,008 (+0.78125%).
Bài tập 2 — Dẫn xuất Phương sai Khởi tạo (Xavier/Kaiming), Tỷ lệ 1/sqrt(2L) & Sụp đổ BatchNorm B=2 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Chứng minh \(\mathbb{E}[\operatorname{ReLU}(z)^2] = \frac{1}{2}\sigma_z^2\), suy ra điều kiện \(n_{\text{in}}\operatorname{Var}(W)=2\) và chứng minh \(\mathbb{E}[\lVert \mathbf{J}_{\mathbf{x}_{2L}}\mathbf{v}_0\rVert_2^2] = (1 + \frac{\nu^2}{2L})^{2L} \le e^{\nu^2}\) với tỷ lệ \(1/\sqrt{2L}\).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chứng minh ở \(B=2\) thì \(\hat{x}_{1,j} = \operatorname{sgn}(x_1-x_2) = \pm 1\) và chạy benchmark_deep_init_propagation, audit_batchnorm_collapse_and_eval_mode.
Tiêu chí Đáp án & Số đối chứng
Tại \(L=20\), xavier sập về 1.02e-06 (L1 grad = 8.03e-04), naive_large nổ 7.86e+11, còn kaiming (1.07x) và Pre-Norm 1/sqrt(2L) (1.59x) ổn định. BatchNorm B=2 lệch +-1 chỉ 2.38e-07, trong khi RMSNorm giữ sai khác B=1 vs B=32 bằng 0.0.
Bài tập 3 — Tự động Vi phân Ngược (TapeTensor), Sai phân Trung tâm & Kiểm toán Adam vs. Muon NS_5 20%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Cài đặt TapeTensor theo Bố cục Tử số (Numerator Layout) cho MatMul, SwiGLU, RMSNorm và LSE CrossEntropy, kiểm tra bằng sai phân trung tâm bước \(\epsilon^* = 10^{-6}\) ở float64 rồi đối chiếu torch.autograd.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chứng minh yếu tố \(\frac{\eta_t\lambda}{\sqrt{\hat{v}_t}}\) trong Adam ghép \(L_2\) và kiểm chứng nén phổ NS_5 + tỷ lệ Moonlight \(0.2\sqrt{\max(d_{\text{out}}, d_{\text{in}})}\) qua audit_adam_coupled_vs_adamw_decoupled, audit_muon_ns5_spectrum và benchmark_optimizers_arena.
Tiêu chí Đáp án & Số đối chứng
TapeTensor khớp torch.autograd với loss_diff = 2.22e-16, grad_diff = 9.71e-17 (FD = 2.12e-10). Adam ghép \(L_2\) lệch tỷ số 2.97x (val_acc = 44.7%), AdamW giữ lệch 3.0e-08 (91.2%), NS_5 nén phổ vào [0.682, 1.134] và HybridMuonAdamW giữ Update RMS ~0.172 (88.3%).
Bài tập 4 — Checkpointing O(sqrt(L)) (+33.3% FLOPs), Bẫy fp16/bf16 ULP & Roofline Dung hợp Nhân 20%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Cực tiểu hóa \(M(k) = m_{\text{act}}(k + L/k)\) suy ra \(k^* = \sqrt{L}\) và tỷ số tăng FLOP \((4L - 3L)/(3L) = +33.33\%\); cộng bảng 2+2+4+4+4 = 16*Psi bytes cho AdamW.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Tính cường độ số học \(I = \text{FLOP/B}\) so với H100 \(I^* = 295.2\) và đối chiếu qua simulate_checkpointing_tradeoff, compute_roofline_and_fusion_savings, audit_mixed_precision_fp16_bf16_cpu.
Tiêu chí Đáp án & Số đối chứng
Mô hình 7B chiếm 112 GB tĩnh; tại L=64, Checkpointing cắt 75.0% bộ nhớ kích hoạt tại +33.33% FLOP (SAC cắt 72.0% tại +4.0%). fp16 xóa 1e-8 -> 0.0 và tràn 70000 -> inf; bf16 thuần kẹt 0.0 vs fp32 master -0.010. Dung hợp cắt -57.14% (Bias+GELU+Res) và -71.43% (RMSNorm).
Bài tập 5 — Gỡ lỗi Nội tại PyTorch 2.x: Stride/view/reshape, _version & TorchDynamo Graph Breaks 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
So sánh untyped_storage().data_ptr() giữa x.view(...) và x.t().reshape(...); giải thích vì sao ghi lát cắt h[:, :2] = 0 phá .backward() và vì sao inference_mode() ném lỗi khi đọc ._version.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Dùng torch._dynamo.explain truy tìm điểm ngắt .item() / nhánh if phụ thuộc dữ liệu, thay bằng phép toán tensor thuần và biên dịch với torch.compile(..., backend="aot_eager", fullgraph=True).
Tiêu chí Đáp án & Số đối chứng
xt.view(-1) ném RuntimeError, xt.reshape(-1) cấp phát storage mới; h[:, :2] = 0 tăng _version (0 -> 1) gây crash backward; mô hình sạch đạt 0 graph break và compile_max_abs_diff = 0.0 với aot_eager (so với 1 break ở mô hình lỗi).
Bài tập 6 — Điều chuẩn (Dropout, Label Smoothing, CutMix), Dừng sớm Best-State & 16/16 Pytest 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Chứng minh chênh lệch logit tối ưu hữu hạn của Label Smoothing \(\epsilon_{\text{ls}}\), tỷ lệ diện tích \(\lambda_{\text{mix}}\) của CutMix, và thiết kế vòng lặp EarlyStopping lưu copy.deepcopy(model.state_dict()) dưới model.eval().
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy trọn bộ audit_regularization_techniques, run_early_stopping_restoration_bench, scripts/run_lab_demo.py --seed 42, ruff, mypy, và pytest -p no:cacheprovider -v.
Tiêu chí Đáp án & Số đối chứng
Label Smoothing giữ margin 2.16 (vs hard CE 7.75); CutMix khớp đúng 0.8125 == lam; EarlyStopping khôi phục cực tiểu epoch 7 (val_loss = 1.624, sai số 0.0, cải thiện test_loss 1.707 -> 1.616); đạt 16/16 pytest (0 skips, 0 lỗi ruff/mypy).