Chương 19 — Cơ chế Attention, Kiến trúc Transformer & Giải phẫu LLM Hiện đại (2026)
Từ 1/sqrt(d_k) (Var 128.96->1.01) & FlashAttention Online Softmax (8.88e-16, -74.8% HBM) đến KV-Cache 128K (70B GQA 8.0x; 671B MLA 56.9x -> 9.21 GB), RoPE/YaRN (9.54e-7), Sparse MoE (CV 1.73->0.16, 25.2% active), Min-p & FSM JSON (100% vs 0%).
Đơn vị học phần (
Unit ID):T1-P4-U02(Phần 4: Xử lý Ngôn ngữ Tự nhiên, Mô hình Ngôn ngữ Lớn, Hậu huấn luyện Suy luận & An toàn AI — Mục lục Phần 4)
Phòng thí nghiệm Thực hành (Workbench): WB-Ch19 — Attention, Transformers & Giải phẫu LLM Hiện đại (transformer_llm_lab)
Truy xuất nguồn & kế thừa: Kế thừa trực tiếp từChương 18(Tokenization, Embedding cổ điển & RNN/LSTM), Chương 14 (RMSNorm,SwiGLU, Roofline &PyTorch 2.x), và Chương trình gốc DSAI (R49— Large Language Model: Attention & Transformers). Chương tiếp theo làChương 20(Tiền huấn luyện LLM, Quy luật Scaling & Điều khiển Đầu ra bằngDSPy).
Bốn Thất bại Kiến trúc Thực chiến Mở màn: Vì sao Transformer 2017 Không thể Phục vụ LLM 2026?#
Mọi kỹ sư hệ thống AI hiện đại đều phải trả lời cùng một câu hỏi: Nếu bài báo "Attention Is All You Need" (2017) đã đặt ra nền móng Transformer, vì sao toàn bộ các mô hình biên giới 2024–2026 (Llama-3, Qwen-3, DeepSeek-V3) đều viết lại gần như toàn bộ cơ chế vị trí, chuẩn hóa, bộ nhớ đệm chú ý, tầng truyền thẳng và thuật toán giải mã? Bốn ca thất bại định lượng sau đây được tái hiện trọn vẹn trong WB-Ch19 (transformer_llm_lab):
-
Bão hòa Softmax khi Thiếu \(1/\sqrt{d_k}\) & Sụp đổ
HBMcủa Attention \(O(N^2)\) (WB-Ch19,Tests 03, 04, 05):Khi bỏ qua hệ số chuẩn hóa \(1/\sqrt{d_k}\) ở kích thước đầu phổ biến \(d_k = 128\), phương sai tích vô hướng \(\operatorname{Var}(\mathbf{q}^\top \mathbf{k})\) nhảy vọt lên
128.96(so với1.01sau khi chia \(\sqrt{128}\)), kéo entropy phân phối chú ý sụp từ86.8%xuống còn9.2%(max_prob = 0.878, dấu vết Jacobian Softmax tụt5.3×từ0.926còn0.173), làm đóng băng gradient ngay ở epoch đầu. Nghiêm trọng hơn, ở pha tiền điền ngữ cảnh32K(H = 32, d_h = 128, bf16), việc vật liệu hóa ma trận \(\mathbf{S}, \mathbf{P} \in \mathbb{R}^{N \times N}\) ngốn tới137.4 GBbộ nhớ kích hoạt đỉnh và275.95 GBlưu lượng đọc/ghi HBM mỗi tầng; ngược lại,FlashAttentiondùng Online Safe Softmax theo khối (B_r = 128, B_c = 64) cắt lưu lượng HBM còn69.53 GB(-74.8%, gấp3.97×), thu gọn kích hoạt đỉnh xuống chỉ4.19 MB(\(O(N)\)) với sai số số học tuyệt đối chỉ8.88e-16. -
Bức tường Bộ nhớ
KV-Cacheở Ngữ cảnh128K(WB-Ch19,Tests 06, 09, 10):Với kiến trúc
MHAcổ điển (\(n_{\text{kv}} = n_q\)) ở độ dài ngữ cảnh128K(bf16), một yêu cầu duy nhất của mô hình lớp70B(\(L = 80, H = 64, d_h = 128\)) chiếm tới343.60 GBKV-Cache (tràn cả cụm4× H100 80GB), còn mô hình lớp671B(\(L = 61, H = 128, d_h = 128\)) ngốn tới523.99 GB! Chuyển sangGQA 8:1(chuẩnLlama-3 70B) cắt giảm đúng8.0×xuống42.95 GB, trong khi DeepSeekMLA(Multi-head Latent Attention) nén chung Key/Value vào không gian tiềm ẩn hạng thấp \(d_c = 512\) kèm nhánhDecoupled RoPE\(d_R = 64\) cắt KV-Cache của lớp671Bxuống chỉ còn9.21 GB(nén56.9×so vớiMHA,7.1×so vớiGQA 8:1, và còn4.61 GBởfp8), cho phép phục vụ đồng thời nhiều người dùng trên cùng cụm GPU mà giữ sai lệch giải mã tăng dần dưới7.45e-08. -
Sụp đổ Bộ định tuyến
Sparse MoE(6/8Chuyên gia Chết) & Ngoại suy Ngữ cảnh Gãy khúc (WB-Ch19,Tests 08, 11):Khi mở rộng dung lượng mô hình bằng
Sparse MoE(Top-2trên8chuyên gia, chỉ kích hoạt25.2%tham số mỗi token), một bộ định tuyến không được cân bằng tải rơi ngay vào trạng thái sụp đổ (Router Collapse):2chuyên gia gánh trọn100%token (load_cv = 1.73,max_share = 50.0%), bỏ chết6/8chuyên gia còn lại. Áp dụng hàm mất mát cân bằng tải phụ trợ \(\mathcal{L}_{\text{aux}}\) hoặc cơ chế cập nhật thiên lệch động không cần aux-loss kiểuDeepSeek-V3kéo hệ số biến thiên tải vềCV = 0.16với0chuyên gia chết (max_share = 16.0%, sát mốc lý tưởng12.5%). Song song đó, nhúng vị trí tuyệt đối mất tác dụng ngoài cửa sổ huấn luyện, trong khiRoPEbảo toàn bất biến vị trí tương đối tới9.54e-07vàYaRN(8×) giữ nguyên tỷ lệ tần số cao1.000đồng thời nội suy tần số thấp0.125kèm hiệu chỉnh nhiệt độmscale = 1.208. -
Rò rỉ Đuôi Nhiễu
Top-pở Nhiệt độ Cao & Lỗi Cú pháp JSON Tự do (WB-Ch19,Tests 12, 13):Ở nhiệt độ sáng tạo \(\tau = 1.5\) trong trạng thái mô hình tự tin cao (\(p_{\max} = 0.727\)), lấy mẫu
Top-p (0.95)vẫn giữ tới41token hoạt động với11.1%khối lượng xác suất rò rỉ vào đuôi nhiễu vô nghĩa; ngược lại,Min-p (0.10)đặt ngưỡng thích ứng \(p_{\text{base}} \cdot p_{\max} = 0.0727\), cắt gọn về đúng2token đỉnh (0.0%rò đuôi) mà vẫn tự động mở rộng lên6token khi gặp phân phối bất định (\(p_{\max} = 0.137\)). Đối với API trích xuất dữ liệu có cấu trúc, giải mã tự do dưới logit nhiễu đạt tỷ lệ JSON hợp lệ đúng0/60 (0.0%)(phát sinh chuỗi rác kiểuSure!Sure!":...), còn mặt nạ logit bằng Máy Trạng thái Hữu hạn (FSM / Grammar-Constrained Decoding) đạt tuyệt đối60/60 (100.0%)JSON đúng lược đồ ({"status":"warn","score":71}).
Mục tiêu Học tập (Learning Objectives)#
Sau khi hoàn thành Chương 19 và vượt qua 16/16 bài kiểm thử của WB-Ch19 (transformer_llm_lab), học viên làm chủ toàn diện 5 năng lực cốt lõi sau:
- Dẫn xuất Cơ chế Attention từ First Principles: Giải thích nút thắt thông tin
Seq2Seqtrong dịch máy (NMT), cài đặt Bahdanau (cộng) vs. Luong (nhân), chứng minh chính xác \(\operatorname{Var}(\mathbf{q}^\top \mathbf{k}) = d_k\) và vì sao chia \(\sqrt{d_k}\) ngăn bão hòa Softmax/triệt tiêu gradient, cũng như phân biệtEncoder-only(ModernBERT),Encoder-Decoder(T5) vàDecoder-only(Llama-3/DeepSeek-V3) cùng cơ chế biểu diễn ngữ cảnh giải quyết hiện tượng đa nghĩa. - Chứng minh Hình học
RoPE& Ngoại suy Ngữ cảnh DàiYaRN: Chứng minh đẳng thức xoay trực giao \((\mathbf{R}_m \mathbf{q})^\top (\mathbf{R}_n \mathbf{k}) = \mathbf{q}^\top \mathbf{R}_{n-m} \mathbf{k}\), kiểm nghiệm sai số bất biến< 1e-5, và thiết kế lịch trình trộn bước sóngYaRN(\(\gamma_j\) giữa \(\alpha, \beta\) và hệ số nhiệt độ \(\sqrt{1/t} = 0.1\ln s + 1\)). - Tính toán Bức tường
KV-Cache& Triển khaiGQA/MLA: Thành thạo công thức bộ nhớ KV-Cache chuẩn \(2 L n_{\text{kv}} d_h S B b_{\text{dtype}}\) và nén hạng thấpMLA\(L (d_c + d_R) S B b_{\text{dtype}}\); tự tay xây dựng giải mã tăng dần (incremental cached decode) cho cảGQAAttentionvàMLAAttentionkhớp tuyệt đối< 1e-5với lượt tiền điền toàn phần. - Làm chủ Thuật toán IO-Aware
FlashAttention&Sparse MoE: Chứng minh đệ quy Online Safe Softmax Tiling (\(m_{\text{new}}, \ell_{\text{new}}, \mathbf{o}_{\text{new}}\)) loại bỏ ma trận \(N \times N\) khỏi HBM; xây dựng tầngSparseMoELayer(Top-k+ \(\mathcal{L}_{\text{aux}} = \alpha E \sum f_e P_e\) + thiên lệch động kiểuDeepSeek-V3) giải quyết sụp đổ bộ định tuyến. - Xây dựng Động cơ Giải mã Sản xuất (
Beam,Min-p,FSM JSON) & Lưu trữ An toàn (Safetensors): Cài đặt đủ Greedy, Beam Search (length penalty Wu et al.), Temperature, Top-\(k\), Top-\(p\),Min-p, bộ mặt nạ logitFSM JSONđạt100%hợp lệ và lưu/nạp mô hình bằngsafetensorskhông dùngpickle.
Truy xuất Nguồn (R49 Traceability) & Bảng Ký hiệu Phi Mơ hồ#
Thành phần Giáo trình Gốc (R49) |
Nâng cấp Chuẩn SOTA 2026 (ch-19) |
Vị trí trong Chương | Sơ đồ / Widget | Mô-đun & Kiểm thử (transformer_llm_lab) |
|---|---|---|---|---|
| 1. Intro to Machine Translation | Phân rã tự hồi quy NMT, nút thắt vector cố định \(\mathbf{c} \in \mathbb{R}^d\) trên câu dài |
Trụ cột 1 (§1.1) | Mermaid 1 |
attention_math_and_flash.py (Test 02) |
| 2. Encoder-Decoder Architecture | So sánh Encoder-only (ModernBERT), Encoder-Decoder (T5), Decoder-only (Llama-3/DeepSeek-V3) |
Trụ cột 1 (§1.1, §1.3) | Mermaid 1 |
modern_llm_blocks.py: ModernTransformerLM (Tests 14, 15) |
| 3. Attention Mechanisms | Bahdanau (Additive), Luong (Multiplicative), Scaled Dot-Product (\(\operatorname{Var}=d_k\)), MHA, FlashAttention Online Safe Softmax Tiling |
Trụ cột 1 (§1.2, §1.5) + Trụ cột 2 (§2.2) | Mermaid 2 + Widget 2 |
attention_math_and_flash.py: audit_scaled_dot_product_variance, flash_attention_tiled_forward, compute_attention_hbm_traffic (Tests 02–05) |
| 4. Transformer-based Models | Giải phẫu LLM 2026: Pre-Norm RMSNorm, SwiGLU (\(\frac{8}{3}d\)), RoPE + YaRN, GQA / MQA / MLA, Sparse MoE (Router Collapse & cân bằng tải) |
Trụ cột 1 (§1.4, §1.6) + Trụ cột 2 (§2.1, §2.3) | Mermaid 1, Mermaid 3 + Widget 1 + Widget 3 |
modern_llm_blocks.py: RMSNorm, SwiGLU, RotaryEmbedding, GQAAttention, MLAAttention, SparseMoELayer (Tests 06–11) |
| 5. Contextual Word Embedding | Tách biệt hình học đa nghĩa \(\mathbf{h}_i^{(L)} = f_\theta(x_{1:N})_i\) so với bảng nhúng tĩnh Word2Vec (cos = 1.000 -> 0.406) |
Trụ cột 1 (§1.3) | Mermaid 1 |
modern_llm_blocks.py: audit_contextual_embeddings_shift (Test 14) |
| 6. Decoding Methods | Greedy, Beam Search (length penalty \(\alpha\)), Temperature, Top-\(k\), Top-\(p\) (Nucleus), Min-p thích ứng & FSM JSON Logit Masking (100%) |
Trụ cột 1 (§1.7) + Trụ cột 2 (§2.4) | Mermaid 3 + Widget 3 |
kv_cache_and_decoding.py: decode_greedy, decode_beam_search, filter_logits_min_p, mask_logits_for_json_fsm, benchmark_fsm_json_decoding (Tests 12, 13) |
Bảng Ký hiệu Toán học Chuẩn hóa (ch-19)#
| Ký hiệu | Miền / Hình dạng | Ý nghĩa Chuẩn trong Chương 19 | Định danh transformer_llm_lab |
|---|---|---|---|
| \(B, N \text{ (hay } S\text{)}, L\) | \(\mathbb{N}_{>0}\) | Cỡ lô (batch), độ dài chuỗi (sequence length), số tầng Transformer | batch_size, seq_len, n_layers |
| \(d, d_{\text{ff}}, d_h\) | \(\mathbb{N}_{>0}\) | Chiều ẩn mô hình (\(d_{\text{model}}\)), chiều ẩn SwiGLU (\(\approx \frac{8}{3}d\)), chiều mỗi đầu chú ý (\(d/n_q\)) |
d_model, d_ff, d_head |
| \(n_q, n_{\text{kv}}, d_c, d_R\) | \(\mathbb{N}_{>0}\) | Số đầu Query, số đầu KV (GQA/MQA), chiều tiềm ẩn nén MLA, chiều nhánh Decoupled RoPE |
n_q_heads, n_kv_heads, d_c_latent, d_rope |
| \(\mathbf{R}_{\Theta, m}, \theta_j, s\) | \(\mathbb{R}^{d_h \times d_h}, \mathbb{R}_{>0}\) | Ma trận xoay RoPE tại vị trí \(m\), tần số \(\theta_j = b^{-2j/d_h}\), hệ số mở rộng YaRN |
RotaryEmbedding, compute_yarn_inv_freq |
| \(B_r, B_c, m_i, \ell_i\) | \(\mathbb{N}_{>0}, \mathbb{R}\) | Kích thước khối hàng/cột SRAM, cực đại chạy và mẫu số mũ chạy trong FlashAttention |
block_r, block_c, m_i, l_i |
| \(E, k, f_e, P_e, \alpha\) | \(\mathbb{N}_{>0}, [0,1], \mathbb{R}_{\ge 0}\) | Số chuyên gia MoE, số chuyên gia kích hoạt Top-\(k\), tỷ lệ phân bổ, xác suất cổng TB, hệ số \(\mathcal{L}_{\text{aux}}\) |
num_experts, top_k, aux_weight |
| \(\tau, p_{\text{top}}, p_{\text{base}}, \mathcal{A}(q_t)\) | \(\mathbb{R}_{>0}, (0,1], \subseteq V\) | Nhiệt độ, ngưỡng Nucleus Top-\(p\), hệ số Min-p, tập token hợp lệ tại trạng thái FSM \(q_t\) |
temperature, top_p, min_p, fsm_state |
Trụ cột 1 — Nền tảng Lý thuyết, Chứng minh Toán học & Giải phẫu Transformer Hiện đại#
1.1 Từ Nút thắt Seq2Seq trong Dịch máy (NMT) đến Attention Cổ điển#
Trong bài toán Dịch máy Nơ-ron (Neural Machine Translation — NMT), ta mô hình hóa xác suất có điều kiện của chuỗi đích \(y = (y_1, \dots, y_{T_t})\) khi biết chuỗi nguồn \(x = (x_1, \dots, x_{T_s})\):
Kiến trúc Encoder-Decoder RNN/LSTM cổ điển (Sutskever et al., 2014) ép toàn bộ chuỗi nguồn vào một vector ngữ cảnh duy nhất \(\mathbf{c} = \mathbf{h}_{T_s}^{\text{enc}} \in \mathbb{R}^d\). Khi câu nguồn dài (\(T_s > 30\)), \(\mathbf{c}\) trở thành nút thắt thông tin cố định (fixed-capacity bottleneck), đồng thời độ dài đường lan truyền gradient từ \(y_t\) về \(x_1\) tăng tuyến tính \(\mathcal{O}(T_s + t)\), gây triệt tiêu đạo hàm và cấm song song hóa theo chiều thời gian.
Cơ chế Attention phá vỡ nút thắt này bằng cách tính một vector ngữ cảnh động \(\mathbf{c}_t\) ở từng bước giải mã \(t\) dưới dạng tổ hợp lồi của toàn bộ chuỗi trạng thái mã hóa \(\{\mathbf{h}_1, \dots, \mathbf{h}_{T_s}\}\):
Hai thiết kế hàm chấm điểm kinh điển (WB-Ch19, Test 02):
- Bahdanau Additive Attention (ICLR 2015): \(e_{t,j} = \mathbf{v}_a^\top \tanh(\mathbf{W}_a \mathbf{s}_{t-1} + \mathbf{U}_a \mathbf{h}_j)\) — linh hoạt phi tuyến nhưng tốn phép cộng chiếu trung gian.
- Luong Multiplicative Attention (EMNLP 2015): \(e_{t,j} = \mathbf{s}_t^\top \mathbf{h}_j\) (hoặc song tuyến \(\mathbf{s}_t^\top \mathbf{W}_a \mathbf{h}_j\)) — tận dụng trực tiếp nhân ma trận
GEMMnhanh gấp nhiều lần trên phần cứng hiện đại.
1.2 Scaled Dot-Product Attention: Chứng minh Ổn định Phương sai \(1/\sqrt{d_k}\) & MHA#
Kiến trúc Transformer (Vaswani et al., NeurIPS 2017) bỏ hẳn chuỗi hồi quy và dùng Self-Attention kết nối trực tiếp mọi cặp token \((i, j)\) với độ dài đường truyền \(\mathcal{O}(1)\):
trong đó mặt nạ nhân quả \(\mathbf{M}_{ij} = 0\) với \(j \le i\) và \(-\infty\) với \(j > i\) ngăn rò rỉ thông tin từ tương lai (Test 03 xác minh tam giác trên của trọng số chú ý bằng chính xác 0.0).
Chứng minh Bất biến Phương sai \(1/\sqrt{d_k}\)#
Xét hai vector ngẫu nhiên \(\mathbf{q}, \mathbf{k} \in \mathbb{R}^{d_k}\) có các tọa độ độc lập cùng kỳ vọng \(0\) và phương sai \(1\). Đặt \(s = \mathbf{q}^\top \mathbf{k} = \sum_{r=1}^{d_k} q_r k_r\):
Nếu không chia cho \(\sqrt{d_k}\), biên độ logit tăng theo \(\sqrt{d_k}\). Vì đạo hàm của hàm Softmax có Jacobian \(\mathbf{J}_{\text{softmax}}(\mathbf{s}) = \operatorname{diag}(\mathbf{p}) - \mathbf{p}\mathbf{p}^\top\), dấu vết Jacobian \(\sum_i p_i(1 - p_i) \to 0\) ngay khi \(\max_i p_i \to 1\), làm nghẹt toàn bộ gradient! Khi chia cho \(\sqrt{d_k}\):
Kết quả kiểm chứng thực nghiệm trên WB-Ch19 (N = 32, entropy cực đại \(\ln 32 = 3.466\)):
| Kích thước đầu \(d_k\) | Phương sai Chưa chia | Phương sai Sau chia \(1/\sqrt{d_k}\) | Entropy Chưa chia (% trần) | Entropy Sau chia (% trần) | Dấu vết Jacobian (Chưa chia vs. Chia) |
|---|---|---|---|---|---|
16 |
16.19 |
1.01 |
1.12 (32.3%) |
3.02 (87.0%) |
0.492 vs. 0.926 |
64 |
64.19 |
1.00 |
0.50 (14.5%) |
3.01 (87.0%) |
0.259 vs. 0.927 |
128 |
128.96 |
1.01 |
0.32 (9.2%) |
3.01 (86.8%) |
0.173 vs. 0.926 |
256 |
254.59 |
0.99 |
0.23 (6.5%) |
3.02 (87.1%) |
0.127 vs. 0.928 |
Multi-Head Attention (MHA) chiếu song song sang \(n_q\) không gian con kích thước \(d_h = d / n_q\):
Chi phí mỗi tầng MHA gồm \(8 N d^2\) FLOPs cho bốn phép chiếu tuyến tính (Q, K, V, O) và \(4 N^2 d\) FLOPs cho nhân chú ý (\(\mathbf{Q}\mathbf{K}^\top\) và \(\mathbf{P}\mathbf{V}\); giảm một nửa ở chế độ nhân quả).
1.3 Phân loại Kiến trúc Transformer & Biểu diễn Ngữ cảnh (Contextual Embeddings)#
- Vì sao
Decoder-Onlythống trị LLM 2026? Mọi tác vụ (dịch thuật, tóm tắt, sinh mã, suy luận nhiều bước) đều quy về một mục tiêu thống nhất Next-Token Prediction (NTP), cung cấp tín hiệu giám sát dày đặc trên100%token thay vì chỉ15%token bị che củaMLM, đồng thời tận dụng tối đa cơ chế tái sử dụngKV-Cachegiữa các lượt hội thoại. Tuy nhiên,Encoder-Onlyhiện đại (ModernBERT) vẫn là lựa chọn tối ưu về chi phí/độ trễ cho bài toán embedding tìm kiếm, phân loại và Reranker. - Biểu diễn Ngữ cảnh giải quyết Đa nghĩa (Polysemy): Bảng nhúng tĩnh (
Word2Vec/FastText) gán cho từ "bank" đúng một vector duy nhất bất kể ngữ cảnh (độ tương đồng cosine1.000). TrongModernTransformerLM(WB-Ch19,Test 14), khi đặt cùngtoken_id = 7vào hai ngữ cảnh đối lập, các tầng Self-Attention trộn thông tin tiền tố vào dòng thặng dư khiến độ tương đồng cosine giữa hai trạng thái ẩn cuối giảm mạnh từ1.000xuống0.406(độ dịch ngữ cảnh0.594).
1.4 Giải phẫu Khối LLM 2026: Pre-Norm RMSNorm, SwiGLU, RoPE & YaRN#
Một khối Transformer hiện đại áp dụng Pre-Norm (ổn định gradient đường cao tốc thặng dư ở độ sâu \(L \ge 60\) như đã chứng minh tại Chương 14):
với \(\operatorname{RMSNorm}(\mathbf{x}) = \frac{\mathbf{x}}{\sqrt{\frac{1}{d}\sum x_i^2 + \varepsilon}} \odot \mathbf{g}\) (bất biến theo phép co giãn dương \(\alpha \mathbf{x}\), Test 07 kiểm định sai số < 1e-5, bỏ phép trừ trung bình HBM) và SwiGLU \(\big(\operatorname{SiLU}(\mathbf{x}\mathbf{W}_{\text{gate}}) \odot (\mathbf{x}\mathbf{W}_{\text{up}})\big)\mathbf{W}_{\text{down}}\) có \(d_{\text{ff}} \approx \frac{8}{3}d\) cân bằng đúng ngân sách tham số \(8d^2\).
Chứng minh Đẳng thức Vị trí Tương đối của RoPE (Su et al., 2021)#
Ghép từng cặp tọa độ \((2j, 2j+1)\) (\(j = 0, \dots, d_h/2 - 1\)) và xoay theo tần số \(\theta_j = b^{-2j/d_h}\) bằng ma trận khối trực giao \(\mathbf{R}_{\Theta, m}\) gồm các khối \(2 \times 2\):
Vì phép xoay trong nhóm \(SO(2)\) bảo toàn chuẩn (\(\|\mathbf{R}_m \mathbf{v}\|_2 = \|\mathbf{v}\|_2\)) và thỏa \(\mathbf{R}_j(m)^\top \mathbf{R}_j(n) = \mathbf{R}_j(n - m)\), tích vô hướng Attention thỏa mãn bất biến vị trí tương đối chính xác:
Trong WB-Ch19 (Test 08, \(m=7, n=19, \Delta=43\)), sai khác tuyệt đối giữa tích vô hướng gốc (7.959091) và sau dịch 43 vị trí (7.959090) chỉ là 9.54e-07.
Ngoại suy Ngữ cảnh Dài bằng YaRN (Peng et al., ICLR 2024)#
Khi kéo dài ngữ cảnh thêm hệ số \(s = L_{\text{ext}} / L_{\text{train}}\) (ví dụ 8× từ 4K lên 32K), nội suy tuyến tính đồng loạt \(\theta_j / s\) làm mờ độ phân giải khoảng cách gần. YaRN phân tích số vòng quay \(r_j = \frac{L_{\text{train}}\theta_j}{2\pi}\) của từng chiều so với hai ngưỡng \(\beta_{\text{slow}} = 1, \beta_{\text{fast}} = 32\):
Chiều tần số cao (\(r_j > 32\), bước sóng ngắn) giữ nguyên tỷ lệ 1.000, chiều tần số thấp (\(r_j < 1\), bước sóng dài) nội suy đúng 1/s = 0.125, và hệ số nhiệt độ chú ý đạt mscale = 1.208 tại \(s = 8\) (Test 08).
1.5 Thuật toán IO-Aware FlashAttention: Đệ quy Online Safe Softmax Tiling#
Điểm nghẽn của Attention tiêu chuẩn không phải số phép nhân FLOP mà là băng thông HBM do ghi/đọc ma trận \(\mathbf{S}, \mathbf{P} \in \mathbb{R}^{N \times N}\) (\(4 N^2 + 4 N d\) phần tử mỗi đầu). FlashAttention (Dao et al., 2022–2024) chia \(\mathbf{Q}\) thành các khối hàng \(B_r\) và \(\mathbf{K}, \mathbf{V}\) thành các khối cột \(B_c\) vừa khít SRAM trên chip, cập nhật đồng thời cực đại chạy \(m_i\), mẫu số mũ chạy \(\ell_i\) và đầu ra tích lũy \(\mathbf{O}_i\) qua từng khối \(j\):
Đẳng thức này là chính xác tuyệt đối về mặt toán học (không hề xấp xỉ!): kiểm thử WB-Ch19 (Test 04) cho sai số cực đại giữa flash_attention_tiled_forward và Attention vật liệu hóa \(O(N^2)\) chỉ là 8.88e-16 (sai số làm tròn float64), đồng thời bỏ qua hoàn toàn 28/64 khối tam giác trên dưới mặt nạ nhân quả.
1.6 Sparse Mixture-of-Experts (MoE) & Chống Sụp đổ Bộ định tuyến#
Tầng Sparse MoE thay một FFN dày đặc bằng \(E\) chuyên gia độc lập \(\{f_1, \dots, f_E\}\) và bộ định tuyến \(\mathbf{W}_g \in \mathbb{R}^{E \times d}\) chỉ kích hoạt Top-k chuyên gia cho mỗi token:
- Tách rời tham số khỏi FLOP: Với \(E = 8, k = 2\) (
WB-Ch19,Test 11), mỗi token chỉ kích hoạt49,664 / 197,120tham số (25.2%); ởDeepSeek-V3(256chuyên gia mịn +1chuyên gia dùng chung), chỉ37B / 671B(5.5%) tham số hoạt động mỗi token! - Hàm mất mát cân bằng tải (
Switch/Mixtral) vs. Thiên lệch Động (DeepSeek-V3):\[\mathcal{L}_{\text{aux}} = \alpha \cdot E \sum_{e=1}^{E} f_e \cdot P_e,\]đạt cực tiểu đúng bằng \(\alpha\) (0.01) khi phân bổ tải đồng đều (\(f_e = P_e = 1/E\)). Để tránh gradient của \(\mathcal{L}_{\text{aux}}\) xung đột với hàm mất mát ngôn ngữ,DeepSeek-V3cập nhật trực tiếp thiên lệch chọn \(\mathbf{b} \leftarrow \mathbf{b} + \gamma \operatorname{sgn}(\bar{c} - \mathbf{c})\) chỉ trong bước chọnTopK(không làm méo trọng số trộn \(p_e\)). TrongWB-Ch19, cơ chế này đưa bộ định tuyến sụp đổ (CV = 1.73,6chuyên gia chết,aux_loss = 0.0178) về trạng thái cân bằng (CV = 0.16,0chuyên gia chết,aux_loss = 0.0099).
1.7 Lý thuyết Giải mã: Beam Search, Min-p Thích ứng & Mặt nạ Văn phạm FSM#
- Greedy vs. Beam Search (Length Penalty): Tham lam cục bộ tại bước \(t\) có thể bỏ lỡ chuỗi tối ưu toàn cục. Trong
WB-Ch19(Test 12),Greedychọn nhánh[0, 1, 0](logp = -2.018), trong khiBeam Search(\(B_{\text{beam}} = 3\), chuẩn hóa độ dài \(\operatorname{LP}(L) = ((5 + L)/6)^{0.7}\)) tìm ra chuỗi tối ưu toàn cục[0, 2, 0](logp = -0.844). - Temperature, Top-\(k\), Top-\(p\) &
Min-p(Nguyen et al., ICLR 2025): Top-\(p\) tích lũy \(\sum_{v \in V^{(p)}} p(v) \ge p\) dễ gom hàng chục token đuôi nhiễu khi nâng nhiệt độ \(\tau > 1\).Min-pđặt ngưỡng cắt tỷ lệ thuận với đỉnh xác suất:\[\mathcal{V}_{\text{min-p}} = \big\{ v \in V \;\big|\; p(v) \ge p_{\text{base}} \cdot \max_{u \in V} p(u) \big\}.\]Trong thực nghiệmWB-Ch19ở \(\tau = 1.5\): khi mô hình tự tin (\(p_{\max} = 0.727\)),Top-p (0.95)lọt tới41token (11.1%rò đuôi), cònMin-p (0.10)giữ đúng2token (0.0%rò đuôi); khi mô hình bất định (\(p_{\max} = 0.137\)),Min-ptự động mở rộng lên đúng6ứng viên hợp lệ (so với54token nhiễu củaTop-p). - Giải mã Ràng buộc Văn phạm
FSM: Biên dịch JSON Schema thành máy trạng thái hữu hạn \(M = (Q, \Sigma, \delta, q_0, F)\) và gán mặt nạ cứng \(-\infty\) lên mọi token \(v \notin \mathcal{A}(q_t)\) trước bước Softmax \(\implies\) xác suất lỗi cú pháp bằng đúng0.0.
Trụ cột 2 — Kiến trúc Hệ thống Suy luận Sản xuất, Bức tường Bộ nhớ & Kinh tế GPU#
2.1 Bức tường Bộ nhớ KV-Cache: So sánh Định lượng MHA \(\to\) GQA \(\to\) MQA \(\to\) MLA#
Trong pha giải mã tự hồi quy (decode phase), lưu đệm Key/Value tránh tính lại \(O(S^2)\) toàn bộ ngữ cảnh trước đó: trong WB-Ch19 (Test 09), giải mã 64 token sau prompt 2048 token bằng KV-Cache cắt số FLOPs gấp 2,080× mà sai khác logit so với tính lại toàn phần chỉ 3.58e-07. Tuy nhiên, dung lượng KV-Cache nhanh chóng trở thành nút thắt VRAM quyết định số người dùng đồng thời (concurrency):
Bảng đối chiếu dung lượng KV-Cache chính xác tại ngữ cảnh 128K (S = 131,072, B = 1, bf16, trích trực tiếp từ artifacts/ch19_wb19_results.json):
Lớp Mô hình (128K, bf16) |
MHA (GB) |
GQA 8:1 (GB) |
MQA (GB) |
MLA bf16 (GB) |
MLA fp8 (GB) |
Hệ số Nén MLA / MHA |
|---|---|---|---|---|---|---|
| 7B Class (\(L=32, n_q=32, d_h=128\)) | 68.72 |
17.18 (4×) |
2.15 |
2.68 |
1.34 |
25.6× (6.4× vs GQA) |
| 70B Llama-3 (\(L=80, n_q=64, d_h=128\)) | 343.60 |
42.95 (8×) |
5.37 |
12.08 |
6.04 |
28.4× (3.6× vs GQA) |
| 671B DeepSeek-V3 (\(L=61, n_q=128, d_h=128\)) | 523.99 |
65.50 (8×) |
4.09 |
9.21 |
4.61 |
56.9× (7.1× vs GQA) |
Với DeepSeek MLA (d_c = 512, d_R = 64), một mô hình khổng lồ 671B chỉ cần 9.21 GB (bf16) hoặc 4.61 GB (fp8) KV-Cache cho toàn bộ chuỗi 128K — nhỏ hơn gần 5× so với GQA 8:1 của mô hình 70B! Trong kiểm thử MLAAttention của WB-Ch19 (Test 10), giải mã tăng dần trên cache nén (c_kv, k_rope) khớp chính xác với tính lại toàn phần tới 7.45e-08 và đạt nén 12.0× ngay trên cấu hình thử nghiệm nhỏ.
Cơ chế Hấp thụ Ma trận (Matrix Absorption) & Lý do Phải Tách Decoupled RoPE trong MLA#
Một câu hỏi kinh điển ở trình độ kỹ sư hệ thống: Nếu MLA chỉ lưu vector nén \(\mathbf{c}_t^{KV} \in \mathbb{R}^{d_c}\) trong bộ nhớ đệm, chẳng phải ở mỗi bước giải mã ta sẽ phải nhân giải nén \(\mathbf{k}_t^C = \mathbf{W}^{UK}\mathbf{c}_t^{KV}\) và \(\mathbf{v}_t^C = \mathbf{W}^{UV}\mathbf{c}_t^{KV}\) cho toàn bộ \(S\) token quá khứ sao? Câu trả lời nằm ở tính kết hợp của phép nhân ma trận cho nhánh nội dung (nope — không xoay RoPE):
Tương tự, phép nhân đầu ra \(\mathbf{W}^O \sum_j \alpha_{t,j} (\mathbf{W}^{UV}\mathbf{c}_j^{KV}) = (\mathbf{W}^O \mathbf{W}^{UV}) \sum_j \alpha_{t,j} \mathbf{c}_j^{KV}\) cho phép hấp thụ \(\mathbf{W}^{UV}\) thẳng vào \(\mathbf{W}^O\). Nhờ đó, pha giải mã thao tác trực tiếp trên vector tiềm ẩn \(\mathbf{c}_j^{KV}\) chỉ rộng 512 chiều mà không bao giờ phải tái tạo lại tensor Key/Value đầy đủ trên HBM!
Tuy nhiên, nếu chèn ma trận xoay phụ thuộc vị trí \(\mathbf{R}_j\) vào giữa (\(\mathbf{R}_j \mathbf{W}^{UK} \mathbf{c}_j^{KV}\)), vì \(\mathbf{R}_j\) không giao hoán với \(\mathbf{W}^{UK}\) và thay đổi theo từng vị trí \(j\), ta không thể hấp thụ \(\mathbf{W}^{UK}\) vào \(\mathbf{W}^Q\) nữa! Đây chính là lý do DeepSeek tách riêng một nhánh Decoupled RoPE dùng chung cho mọi đầu chú ý có chiều nhỏ \(d_R = 64\):
Toàn bộ bộ nhớ đệm cần lưu mỗi tầng/token chỉ còn đúng \(d_c + d_R = 512 + 64 = \mathbf{576}\) phần tử (56.9× nhỏ hơn 32,768 phần tử của MHA 128 đầu).
Hãy trực tiếp khám phá bức tường KV-Cache (MHA/GQA/MQA/MLA) và phép xoay bất biến RoPE + YaRN trong trình mô phỏng tương tác đầu tiên:
2.2 Kiến trúc IO-Aware FlashAttention giữa HBM & SRAM#
Tại độ dài chuỗi 32K (H = 32, d_h = 128, bf16, causal=True, B_r = 128, B_c = 64), WB-Ch19 (Test 05) ghi nhận:
- Lưu lượng HBM: Giảm từ
275.95 GB(Naive \(O(N^2)\)) xuống69.53 GB(-74.8%, hệ số3.97×). - Bộ nhớ kích hoạt đỉnh: Giảm từ
137.44 GB(lưu \(\mathbf{S}, \mathbf{P}\)) xuống đúng4.19 MB(chỉ lưu vector log-sum-expfp32kích thước \(B H N\)) — giảm hơn32,000×! - Cường độ số học Roofline (\(I = \text{FLOP/B}\)): Tăng từ
31.9 FLOP/Blên126.5 FLOP/B, kéo nhân Attention thoát khỏi vùng nghẽn băng thông HBM tiến sát trần tính toán Tensor Core trên H100/B200.
Hãy thao tác kích thước khối SRAM (B_r, B_c), độ dài chuỗi N và theo dõi từng bước cập nhật (m_new, l_new) trong trình mô phỏng tương tác thứ hai:
2.3 Đường ống Suy luận Sản xuất (Prefill / Decode, MoE & FSM JSON)#
Hai pha phục vụ LLM có đặc tính phần cứng đối lập nhau hoàn toàn:
- Pha
Prefill(quyết địnhTTFT— Time To First Token): Xử lý song song toàn bộ \(S_{\text{prompt}}\) token trong một lượtGEMMlớn \(\implies\) Compute-Bound (cường độ số học \(I_{\text{prefill}} \approx B \cdot S_{\text{prompt}} / b_{\text{dtype}} \gg I^*_{\text{H100}} = 295.2\text{ FLOP/B}\), bão hòa Tensor Core nhờFlashAttention). - Pha
Decode(quyết địnhTPOT— Time Per Output Token): Mỗi bước chỉ đọc toàn bộ trọng số mô hình \(\Psi_{\text{active}} \cdot b_{\text{dtype}}\) cộng toàn bộKV-Cachecủa lô \(B\) từ HBM để tính đúng1token mới cho mỗi yêu cầu \(\implies\) cường độ số học tuyến tính \(I_{\text{decode}} \approx \frac{2 B}{b_{\text{dtype}}} = B\) (bf16), nằm sâu trong vùng Memory-Bandwidth-Bound cho tới khi cỡ lô \(B \ge 256\). Thời gian sinh mỗi token bị chặn dưới bởi tốc độ đọc HBM:
Từ phương trình Roofline này, ta thấy ngay vì sao bộ ba kiến trúc 2026 (GQA/MLA cắt \(\text{KV}_{\text{bytes}}\), Sparse MoE cắt \(\Psi_{\text{active}}\) từ 671B xuống 37B, và Tách pha Prefill-Decode Disaggregation tránh để yêu cầu tiền điền dài chen ngang làm giật TPOT của các yêu cầu đang giải mã) quyết định trực tiếp chi phí tính trên mỗi triệu token (USD/1M tokens) trong vLLM / SGLang / TensorRT-LLM.
Tổng kết 4 Bài học Thực chiến Sản xuất (2024–2026)#
| Hệ thống / Kịch bản Thực tế | Điểm Nghẽn Gốc | Đột phá Kiến trúc Áp dụng | Tác động Định lượng Sản xuất |
|---|---|---|---|
Meta Llama-3 70B (128K) |
MHA chiếm 343.6 GB KV/yêu cầu (> 4× H100) |
GQA 8:1 + RoPE \(\theta = 500{,}000\) |
Cắt 8.0× KV-Cache còn 42.95 GB, tăng 8× concurrency trên cụm 8× H100 |
DeepSeek-V3 (671B / 37B) |
Dense 671B & MHA 524 GB KV quá đắt |
MLA (d_c=512, d_R=64) + Sparse MoE (bias-balanced + Shared Expert) |
Nén 56.9× KV-Cache còn 9.21 GB (4.61 GB fp8), chỉ đọc 5.5% tham số/token |
Prefill Ngữ cảnh 32K H100 |
Ma trận \(N \times N\) ngốn 137.4 GB kích hoạt, sập OOM |
FlashAttention-2/3 Online Safe Softmax Tiling (B_r=128) |
Cắt -74.8% lưu lượng HBM (3.97×), kích hoạt đỉnh còn 4.19 MB (\(O(N)\)) |
| Enterprise Extraction & Tool API | Prompt JSON + Top-p lỗi 4%–12%, tốn +25% retry |
FSM / xgrammar Logit Masking + trường "reasoning" trước "answer" |
Hợp lệ JSON đạt tuyệt đối 100.0% (60/60 vs 0/60), triệt tiêu retry & giữ chất lượng suy luận |
Hãy trải nghiệm đồng thời Min-p vs Top-p + FSM JSON Masking và Sparse MoE Router Collapse trong trình mô phỏng tương tác thứ ba:
2.4 Cẩm nang Quyết định Kiến trúc & Phục vụ Sản xuất (2026)#
| Quy mô / Bài toán | Kiến trúc Khuyến nghị (Go) |
Chống mẫu Phải Tránh (No-Go) |
Ngưỡng Ngân sách & SLA Tham chiếu |
|---|---|---|---|
| Embedding / Reranker / NER | Encoder-Only (ModernBERT) + FlashAttention + RoPE |
Dùng LLM Decoder 70B cho phân loại độ trễ thấp | p99 < 15 ms, chi phí rẻ hơn 20×–50× so với LLM |
LLM Dày đặc (7B–70B) |
Pre-Norm RMSNorm + SwiGLU + RoPE/YaRN + GQA 8:1 |
Post-Norm, Sinusoidal PE, MHA ở ngữ cảnh > 16K |
KV-Cache 128K 70B \(\le 43\text{ GB}\) (bf16) hoặc \(\le 22\text{ GB}\) (fp8) |
LLM Quy mô Biên giới (> 100B) |
MLA + Fine-Grained Sparse MoE + FP8 KV-Cache |
Dense 500B+ hoặc MoE không có cân bằng tải router |
Active ratio 5%–25%, load_cv < 0.25, 0 chuyên gia chết |
| Sinh Văn bản Sáng tạo / Hội thoại | Temperature (1.0–1.5) + Min-p (0.05–0.10) |
Top-p (0.95) đơn lẻ ở \(\tau > 1.2\) (rò đuôi nhiễu) |
Rò đuôi xác suất < 1% ở trạng thái tự tin cao |
Trích xuất JSON / Tool Calling |
FSM / xgrammar Logit Masking + trường "reasoning" trước "answer" |
Prompt cầu may + vòng lặp retry parse JSON | Hợp lệ Schema 100.0%, phụ phí mặt nạ < 50 us/token |
| Lưu trữ Trọng số Checkpoint | safetensors (mmap zero-copy, an toàn tuyệt đối) |
torch.save/pickle trên mô hình từ bên thứ ba |
Sai số khôi phục 0.0, cấm mọi deserializer rủi ro trong CI |
2.5 Kiến trúc Chú ý Lai, Bộ nhớ Hồi quy Tuyến tính & Bẫy RoPE Attention Sink (2025–2026) (Principal Industrial Tip #2)#
Góc nhìn Principal Engineer (Hybrid Attention, Linear Recurrence & KV Memory Architecture): Giữ toàn bộ các tầng ở dạng Softmax Attention đầy đủ tại ngữ cảnh 128K–1M+ tạo ra bức tường bộ nhớ KV-Cache và độ phức tạp Prefill bậc hai \(\mathcal{O}(N^2)\). Các kiến trúc LLM biên giới 2025–2026 phá vỡ giới hạn này qua 4 đột phá kiến trúc cốt lõi (còn phần hậu huấn luyện GRPO/RLVR/DPO được chuyên sâu tại Chương 21):
- Kiến trúc Lai
3:1 Gated DeltaNet(Qwen3-Next): Thay vì thay thế 100% Softmax Attention bằng tầng tuyến tính/SSM (vốn suy giảm mạnh ở các tác vụ truy hồi chính xác needle-in-a-haystack hoặc sao chép chuỗi), dòng mô hìnhQwen3-Nextáp dụng tỷ lệ lai3:1 Gated DeltaNet: xen kẽ3tầngGated DeltaNet(cập nhật trạng thái ma trận bộ nhớ cố định \(\mathbf{S}_t\) theo quy tắc Delta kết hợp cổng quên chọn lọc với độ phức tạp tuyến tính \(\mathcal{O}(N)\) và kích thước trạng thái không phình theo độ dài chuỗi) với1tầng Gated Softmax Attention chuyên lo trộn ngữ cảnh toàn cục và truy xuất chính xác — cắt giảm mạnh dấu chânKV-Cachekhi phục vụ ngữ cảnh siêu dài mà giữ nguyên độ sắc nét suy luận. Differential Transformer(Triệt Nhiễu Đầu Chú ý): Softmax Attention chuẩn thường rò rỉ xác suất chú ý đáng kể lên các token nhiễu nền trong tài liệu dài, làm tăng ảo giác và hiện tượng lost-in-the-middle.Differential Transformertính hiệu giữa hai bản đồ Softmax song song (\(\big(\operatorname{softmax}(\mathbf{Q}_1\mathbf{K}_1^\top/\sqrt{d_h}) - \lambda \operatorname{softmax}(\mathbf{Q}_2\mathbf{K}_2^\top/\sqrt{d_h})\big)\mathbf{V}\)) hoạt động như mạch khuếch đại vi sai giúp triệt tiêu nhiễu nền tương quan và tập trung năng lượng chú ý vào đúng bằng chứng liên quan.Titans(Test-Time Neural Memory Module): Khác vớiKV-Cachechỉ lưu thụ động mọi cặp Key/Value quá khứ, kiến trúcTitanstrang bị một mô-đun bộ nhớ nơ-ron sâu cập nhật ngay tại thời điểm suy luận (test-time memorization) dựa trên độ bất ngờ của gradient (surprise signal), cho phép mô hình tự nén thông tin dài hạn vào trọng số bộ nhớ cố định và kết hợp với cửa sổ chú ý ngắn hạn để mở rộng ngữ cảnh hiệu dụng lên hàng triệu token.- Bẫy Trục xuất
KV-Cache&RoPE Attention Sink(StreamingLLM Collapse): Các mô hình LLM chuẩn tập trung một khối lượng chuẩn kích hoạt cực lớn (massive activations) vào1–4token mở đầu (BOS/ dấu câu khởi đầu) làm "bồn xả" (attention sink) để tổng xác suất Softmax luôn cân bằng về1. Trong giải mã luồng dài vô hạn hoặc cơ chế trục xuất KV cửa sổ trượt (sliding-window KV eviction), nếu xóa cứng token neo khởi đầu hoặc áp sai góc xoayRoPE Attention Sinkkhi dịch chuyển lại chỉ số vị trí trong cache, phân phối logit và perplexity sẽ sụp đổ tức thì — trong sản xuất bắt buộc giữ cố định các token neo sink trongKV-Cachevà xoay lạiRoPEnhất quán theo vị trí tương đối bên trong cửa sổ hoạt động!
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 LLM 2026#
- Lõi Mô hình & Lưu trữ:
PyTorch 2.x(torch.nn.functional.scaled_dot_product_attentiongọi tự độngFlashAttention-2/cuDNNtrên GPU, hoặc nhân tường minh trên CPU),safetensors(zero-pickle),Pydantic v2(extra="forbid"). - Hệ thống Phục vụ (
Serving):vLLM/SGLang(PagedAttention,RadixAttention,MLAmatrix absorption,xgrammar/llguidanceFSM structured decoding).
3.2 Ma trận 6 Chống mẫu Kiến trúc LLM & Cổng Kiểm soát Tự động (CI Canary Gates)#
| # | Chống mẫu (Anti-Pattern) |
Triệu chứng Thất bại Thực tế | Cổng Kiểm soát Tự động (WB-Ch19 CI Gate) |
|---|---|---|---|
| 1 | Bỏ qua hệ số \(1/\sqrt{d_k}\) hoặc quên mặt nạ tam giác trên | Softmax bão hòa (entropy sụp 9.2%), rò rỉ token tương lai khi huấn luyện Causal LM |
Khẳng định scaled_var in [0.75, 1.25] và max(abs(triu(attn, k=1))) == 0.0 (Test 03) |
| 2 | Hiện thực hóa Attention \(O(N^2)\) ở ngữ cảnh > 8K |
Đỉnh kích hoạt 137.4 GB tại 32K gây sập OOM tức thì ở pha Prefill |
Kiểm định FlashAttention khớp < 1e-12 và cắt > 70% HBM (Tests 04, 05) |
| 3 | Triển khai MHA ở 128K hoặc lỗi lệch start_pos trong KV-Cache |
Tràn VRAM (343–524 GB), hoặc lệch RoPE giữa prefill và decode sinh văn bản vô nghĩa |
Kiểm thử đối chiếu giải mã tăng dần GQA & MLA khớp full prefill < 1e-5 (Tests 09, 10) |
| 4 | Dùng nội suy tuyến tính PI đồng loạt thay cho YaRN khi mở rộng ngữ cảnh |
Mờ độ phân giải khoảng cách gần, suy giảm điểm truy hồi cục bộ | Khẳng định YaRN giữ tỷ lệ tần số cao 1.000, tần số thấp 1/s và mscale > 1 (Test 08) |
| 5 | Huấn luyện Sparse MoE không cân bằng tải router |
Sụp đổ bộ định tuyến (6/8 chuyên gia chết, CV = 1.73), nghẽn All-to-All |
Buộc dead_experts == 0 và load_cv < 0.35 sau bước cân bằng (Test 11) |
| 6 | Dùng Top-p ở \(\tau > 1.2\), bỏ FSM JSON, hoặc nạp trọng số bằng pickle |
Rò đuôi 11.1%–32%, lỗi parse JSON API và lỗ hổng thực thi mã tùy ý (RCE) |
Kiểm định Min-p, buộc FSM JSON == 100%, safetensors == 0.0 & cổng AST cấm pickle (Tests 12–16) |
3.3 Mã Python Thực thi Đầu-Cuối (Sử dụng Trực tiếp transformer_llm_lab)#
Đoạn mã dưới đây chạy hoàn toàn ngoại tuyến trên .venv (PyTorch 2.15.0+cpu), kiểm chứng đồng thời 5 bất biến quan trọng nhất của Chương 19 (1/sqrt(d_k), FlashAttention khớp 8.88e-16, RoPE bất biến 9.54e-07, GQA/MLA incremental KV-Cache + Sparse MoE + safetensors, và FSM JSON đạt 100% hợp lệ):
from __future__ import annotations
import tempfile
from pathlib import Path
import numpy as np
import torch
from transformer_llm_lab import (
FlashTilingConfig,
ModernLLMConfig,
ModernTransformerLM,
audit_gqa_kv_cache_parity,
audit_mla_latent_cache_compression,
audit_moe_router_collapse_vs_balanced,
audit_rope_invariance_and_yarn,
audit_scaled_dot_product_variance,
benchmark_fsm_json_decoding,
compute_attention_hbm_traffic,
flash_attention_tiled_forward,
load_safetensors_checkpoint,
naive_scaled_dot_product_attention,
save_safetensors_checkpoint,
)
def run_ch19_end_to_end_verification(seed: int = 42) -> None:
"""Chạy kiểm chứng đầu-cuối toàn bộ các bất biến kiến trúc LLM 2026."""
rng = np.random.default_rng(seed)
# 1. Chứng minh phương sai 1/sqrt(d_k) & FlashAttention Online Softmax
var_res = audit_scaled_dot_product_variance()
d128 = [r for r in var_res["by_d_k"] if r["d_k"] == 128][0]
q, k, v = rng.standard_normal((128, 64)), rng.standard_normal((128, 64)), rng.standard_normal((128, 64))
ref_out, _ = naive_scaled_dot_product_attention(q, k, v, causal=True)
flash_out, _ = flash_attention_tiled_forward(q, k, v, block_r=16, block_c=16, causal=True)
hbm_32k = compute_attention_hbm_traffic(
FlashTilingConfig(seq_len=32768, d_head=128, num_heads=32, block_r=128, block_c=64, causal=True)
)
print(f"[1] d_k=128 Var: {d128['unscaled_var']:.1f} -> {d128['scaled_var']:.2f}")
print(f"[2] FlashParity={np.max(np.abs(ref_out - flash_out)):.2e} | 32K HBM cut=-{hbm_32k['hbm_reduction_pct']:.1f}%")
# 2. RoPE + YaRN, GQA KV-Cache, MLA Latent Cache & Sparse MoE
rope = audit_rope_invariance_and_yarn(seed=seed)
gqa = audit_gqa_kv_cache_parity(seed=seed)
mla = audit_mla_latent_cache_compression(seed=seed)
moe = audit_moe_router_collapse_vs_balanced(seed=seed)
print(f"[3] RoPE diff={rope['relative_pos_abs_diff']:.2e} | GQA diff={gqa['max_abs_diff']:.2e} | MLA diff={mla['max_abs_diff']:.2e}")
print(f"[4] MoE CV: {moe['collapsed']['load_cv']:.2f} -> {moe['balanced']['load_cv']:.2f} (active={100*moe['param_accounting']['active_ratio']:.1f}%)")
# 3. ModernTransformerLM + Safetensors round-trip & FSM JSON 100%
torch.manual_seed(seed)
cfg = ModernLLMConfig(vocab_size=64, d_model=64, n_layers=2, n_q_heads=8, n_kv_heads=2, d_ff=176, use_moe=True)
m1, m2 = ModernTransformerLM(cfg).eval(), ModernTransformerLM(cfg).eval()
with tempfile.TemporaryDirectory() as tmp:
p = save_safetensors_checkpoint(m1, Path(tmp) / "lm.safetensors")
load_safetensors_checkpoint(m2, p)
ids = torch.randint(0, 64, (2, 12))
with torch.inference_mode():
st_diff = float((m1(ids)["logits"] - m2(ids)["logits"]).abs().max().item())
fsm = benchmark_fsm_json_decoding(num_trials=60, seed=seed)
print(f"[5] Safetensors diff={st_diff:.1e} | FSM JSON={fsm['fsm_valid_count']}/{fsm['num_trials']} vs Naive={fsm['unconstrained_valid_count']}")
if __name__ == "__main__":
run_ch19_end_to_end_verification()
Trụ cột 4 — Phòng thí nghiệm Hai Tầng (WB-Ch19) & Hợp đồng 16 Kiểm thử#
4.1 Kiến trúc Hai Tầng (labs/ch19-attention-and-modern-llm-workbench/)#
- Tầng 1 (Lõi Giải tích & Giải mã NumPy Thuần):
src/transformer_llm_lab/attention_math_and_flash.py:bahdanau_additive_attention,luong_multiplicative_attention,audit_scaled_dot_product_variance,flash_attention_tiled_forward(Online Safe Softmax Tiling), vàcompute_attention_hbm_traffic.src/transformer_llm_lab/kv_cache_and_decoding.py:compute_kv_cache_memory_bytes,benchmark_kv_cache_scaling(7B/70B/671Btại8K/32K/128K),decode_greedy,decode_beam_search,filter_logits_top_k/top_p/min_p,audit_min_p_vs_top_p_entropy, vàmask_logits_for_json_fsm/benchmark_fsm_json_decoding.
- Tầng 2 (Mô-đun
PyTorch 2.15.0+cpu+Safetensors):src/transformer_llm_lab/modern_llm_blocks.py:RMSNorm,SwiGLU,RotaryEmbedding+compute_yarn_inv_freq,GQAAttention(incremental KV-Cache),MLAAttention(latent cache + decoupled RoPE),SparseMoELayer(Top-k,aux_loss, DeepSeek bias),ModernTransformerLM,save_safetensors_checkpoint/load_safetensors_checkpoint, và trình điều phốirun_full_ch19_wb19_benchmarks.
4.2 Bảng Kết quả Benchmark Đã Xác minh (artifacts/ch19_wb19_results.json, seed=42)#
Thí nghiệm WB-Ch19 |
Cấu hình / Kiến trúc | Số đo Ghi nhận Chính xác | Kết luận Kỹ thuật |
|---|---|---|---|
| Phương sai \(1/\sqrt{d_k}\) | \(d_k = 128, N = 32\) | Var 128.96 -> 1.01; Entropy 9.2% -> 86.8%; Jacobian 0.173 -> 0.926 |
Bắt buộc chia \(\sqrt{d_k}\) để tránh bão hòa Softmax |
FlashAttention Tiling |
\(N=128\) parity / \(N=32\text{K}\) HBM (B_r=128) |
Parity 8.88e-16; HBM 275.95 -> 69.53 GB (-74.8%); Act 137.4 GB -> 4.19 MB |
Chính xác toán học, cắt 3.97× băng thông HBM & O(N) RAM |
RoPE & YaRN 8× |
\(d_h=64, \Delta=43\) / 4K -> 32K |
Bất biến 9.54e-07; YaRN hi=1.000, lo=0.125, mscale=1.208 |
Bảo toàn khoảng cách cục bộ khi mở rộng ngữ cảnh 8× |
KV-Cache 128K bf16 |
70B & 671B (MHA/GQA/MLA) |
70B: 343.6 -> 42.95 GB (8× GQA); 671B: 524.0 -> 9.21 GB (56.9× MLA) |
GQA/MLA là chìa khóa phục vụ ngữ cảnh 128K+ đa lô |
GQA/MLA Cache & MoE |
Incremental Decode + Top-2/8 MoE |
GQA diff=3.58e-07 (2080× FLOP); MLA diff=7.45e-08; MoE CV 1.73 -> 0.16 (0 dead) |
Cache tăng dần chính xác; cân bằng tải cứu toàn bộ 8/8 chuyên gia |
Min-p, FSM JSON & Ctx |
T=1.5, 60 trials, Safetensors |
Min-p: 2 toks (0% leak) vs Top-p: 41 (11.1%); FSM: 60/60 (100%) vs 0/60; CtxCos=0.406; ST=0.0 |
Min-p chặn đuôi nhiễu; FSM bảo chứng 100% Schema JSON |
4.3 Hợp đồng 16 Kiểm thử Tự động (tests/test_transformer_llm_lab.py)#
| STT | Hàm Kiểm thử Pytest |
Bất biến 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à sai chia hết n_q % n_kv trên cả 5 cấu hình |
2 |
test_02_classical_bahdanau_and_luong_attention_convex_weights |
Trọng số Bahdanau và Luong (dot/general) không âm và tổng bằng 1.0 (< 1e-12) |
3 |
test_03_scaled_dot_product_variance_proof_and_causal_mask |
unscaled_var ~ 128, scaled_var ~ 1.0, entropy tăng > 3×, tam giác trên mặt nạ bằng 0.0 |
4 |
test_04_flash_attention_online_softmax_exact_parity |
Khớp tuyệt đối < 1e-12 trên cả N lẻ/chẵn (53, 64, 45) và bỏ qua khối tam giác trên nhân quả |
5 |
test_05_flash_attention_hbm_traffic_and_activation_reduction |
Cắt > 70% HBM (> 3.5×) và giảm kích hoạt đỉnh > 1000× tại N = 32K |
6 |
test_06_kv_cache_exact_accounting_mha_gqa_mqa_mla |
Khớp chính xác 343.6 GB (70B MHA), 8.0× (GQA), 56.89× (671B MLA) & fp8 = bf16 / 2 |
7 |
test_07_rmsnorm_and_swiglu_numerics_and_scale_invariance |
RMSNorm bất biến co giãn dương < 1e-5; SwiGLU truyền ngược gradient hữu hạn |
8 |
test_08_rope_relative_position_invariance_and_yarn_bands |
RoPE bất biến dịch vị trí < 1e-5, bảo toàn chuẩn L2; YaRN 8× giữ hi=1.0, lo=0.125 |
9 |
test_09_gqa_incremental_kv_cache_exact_parity_and_flops_cut |
Giải mã tăng dần GQA và MQA khớp full prefill < 1e-5; cắt FLOPs > 500× ở 2048 ctx |
10 |
test_10_mla_compressed_latent_cache_parity_and_compression |
MLAAttention cache nén (c_kv, k_rope) khớp < 1e-5, nén >= 10×, gradient hữu hạn |
11 |
test_11_sparse_moe_active_params_and_router_collapse_vs_balanced |
Active ~25%; sụp đổ >= 4 dead (CV > 1.2) vs cân bằng 0 dead (CV < 0.35); aux_loss khả vi |
12 |
test_12_decoding_greedy_beam_search_and_min_p_adaptivity |
Beam vượt Greedy; Min-p giảm rò đuôi so với Top-p ở Low-H và mở rộng ở High-H |
13 |
test_13_fsm_grammar_constrained_json_100pct_validity |
Mặt nạ trạng thái 0 chỉ giữ token 0; FSM đạt 40/40 (100%) vs tự do < 15% |
14 |
test_14_modern_transformer_lm_training_step_and_contextual_shift |
ModernTransformerLM (MoE) huấn luyện gradient hữu hạn; ctx_cos < 0.90 vs static_cos = 1.0 |
15 |
test_15_safetensors_checkpoint_roundtrip_zero_pickle |
Lưu/nạp safetensors khớp logit tuyệt đối 0.0 (không dùng pickle) |
16 |
test_16_cli_demo_workbench_json_schema_and_ast_deserialization_guard |
run_lab_demo.py --quick xuất đúng 6 KPI, 4 bar, 4 bảng; AST cấm deserializer 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 & Biên giới (2015–2026)#
- Bahdanau, D., Cho, K., & Bengio, Y. (2015) & Vaswani, A., et al. (2017). Neural Machine Translation by Jointly Learning to Align and Translate (ICLR 2015) & Attention Is All You Need (NeurIPS 2017). (Phá vỡ nút thắt
Seq2Seqvà khai sinh Scaled Dot-Product Self-Attention + Multi-Head Transformer.) - Su, J., et al. (2021/2024) & Peng, B., et al. (2024). RoFormer: Enhanced Transformer with Rotary Position Embedding (
arXiv:2104.09864) & YaRN: Efficient Context Window Extension of Large Language Models (ICLR 2024). (Nền tảng mã hóa vị trí tương đối trực giao và ngoại suy ngữ cảnh dài theo dải bước sóng.) - Dao, T., et al. (2022–2024). FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness (NeurIPS 2022) & FlashAttention-2/3 (ICLR 2024 / NeurIPS 2024). (Thuật toán Online Safe Softmax Tiling loại bỏ nút thắt HBM \(O(N^2)\).)
- Ainslie, J., et al. (2023) & DeepSeek-AI (2024–2025). GQA: Training Generalized Multi-Query Transformer Models (EMNLP 2023) & DeepSeek-V2 / DeepSeek-V3 Technical Report (
arXiv:2412.19437). (Đột phá nén KV-Cache từGQA 8:1tớiMLA56.9×cùngFine-Grained Sparse MoEcân bằng tải không cần aux-loss.) - Fedus, W., et al. (2022) & Jiang, A. Q., et al. (2024). Switch Transformers: Scaling to Trillion Parameter Models (JMLR 2022) & Mixtral of Experts (
arXiv:2401.04088). (Phân tích sụp đổ bộ định tuyến và hàm mất mát phụ trợ \(\mathcal{L}_{\text{aux}} = \alpha E \sum f_e P_e\).) - Nguyen, M., et al. (2025) & Willard, B. T., & Louf, R. (2023) / Dong, Y., et al. (2024). Turning Up the Heat: Min-p Sampling for Creative and Coherent LLM Outputs (ICLR 2025) & Efficient Guided Generation for LLMs (
Outlines/xgrammar). (Cắt ngưỡng xác suất thích ứng và ràng buộc văn phạmFSMbảo chứng100%JSON.)
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(Chứng minh \(1/\sqrt{d_k}\)): Khi \(q_r, k_r\) độc lập phương sai1, \(\operatorname{Var}(\mathbf{q}^\top \mathbf{k}) = d_k\) (128.96tại \(d_k=128\)) khiến Softmax bão hòa (entropy sập còn9.2%, Jacobian0.173); chia \(\sqrt{d_k}\) phục hồi phương sai1.01và giữ86.8%entropy.Q2(Encoder-onlyvsDecoder-only& Đa nghĩa Ngữ cảnh):Decoder-onlydùng mặt nạ nhân quả và mục tiêuNTPdày đặc, còn Self-Attention phân tách biểu diễn ngữ cảnh của cùng một token đa nghĩa (static_cos = 1.000 -> ctx_cos = 0.406).Q3(RoPE&YaRN): Ma trận xoay trực giao \(\mathbf{R}_m^\top \mathbf{R}_n = \mathbf{R}_{n-m}\) đảm bảo tích vô hướng chỉ phụ thuộc \((n-m)\) (sai số9.54e-07);YaRN 8×giữ nguyên tần số cao (1.000) và nội suy tần số thấp (0.125) kèmmscale = 1.208.Q4(KV-Cache:MHAvsGQAvsMLA): Công thức \(2 L n_{\text{kv}} d_h S B b\) cho70B 128K MHA = 343.6 GB\(\to\)GQA 8:1 = 42.95 GB;MLAlưu \(L(d_c + d_R) S B b\) nén671B 128Ktừ524.0 GBxuống9.21 GB(56.9×) nhờ không gian tiềm ẩn hạng thấp +Decoupled RoPE.Q5(FlashAttentionOnline Safe Softmax): Tiling trên SRAM cập nhật \((m_{\text{new}}, \ell_{\text{new}}, \mathbf{O}_{\text{new}})\) cho kết quả chính xác tuyệt đối (8.88e-16), không ghi ma trận \(N \times N\) ra HBM, cắt-74.8%lưu lượng HBM (276 -> 69.5 GB) và đưa RAM đỉnh từ137.4 GBvề4.19 MBở32K.Q6(Sparse MoE& Router Collapse):Top-2/8 MoEchỉ kích hoạt25.2%tham số; khi thiếu cân bằng tải,6/8chuyên gia chết (CV = 1.73); áp dụng \(\mathcal{L}_{\text{aux}}\) hoặc thiên lệch động kiểuDeepSeek-V3đưa vềCV = 0.16và0chuyên gia chết.Q7(Beam Search&Min-pvsTop-p):Beam SearchvượtGreedyvề xác suất toàn cục (-0.844vs-2.018); ởT = 1.5trạng thái tự tin,Min-p (0.10)giữ đúng2token (0.0%rò đuôi) trong khiTop-p (0.95)lọt41token (11.1%rò đuôi).Q8(FSM JSON&Safetensors): Gán mặt nạ cứng \(-\infty\) theo trạng tháiDFAđẩy tỷ lệ hợp lệ JSON Schema từ0/60 (0.0%)lên60/60 (100.0%); lưu trọng số bằngsafetensorsđạt sai lệch0.0và loại bỏ rủi ro thực thi mã củapickle.
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 Phương sai \(1/\sqrt{d_k}\), Mặt nạ Nhân quả & Bahdanau vs. Luong:Chứng minh đại số \(\operatorname{Var}(\mathbf{q}^\top \mathbf{k}) = d_k\), giải thích mối liên hệ với Jacobian Softmax \(\operatorname{diag}(\mathbf{p}) - \mathbf{p}\mathbf{p}^\top\), và kiểm nghiệm trên
bahdanau_additive_attention,luong_multiplicative_attention,audit_scaled_dot_product_variance. -
Bài tập 2 (
20%) — Chứng minh & Cài đặtFlashAttentionOnline Safe Softmax Tiling + Mô hình HBM:Chứng minh công thức tái chuẩn hóa \(e^{m_{\text{old}} - m_{\text{new}}}\ell_{\text{old}}\) khớp chính xác Softmax chuẩn, cài đặt
flash_attention_tiled_forwardxử lý cả \(N\) không chia hết cho \(B_r, B_c\) (max_abs_diff < 1e-12) và phân tích lưu lượng HBM ở8Kvs32K. -
Bài tập 3 (
15%) — Chứng minh Bất biếnRoPE& Thiết kế Dải Tần sốYaRN:Chứng minh đẳng thức khối xoay \(2 \times 2\) cho \(\mathbf{R}_m^\top \mathbf{R}_n = \mathbf{R}_{n-m}\), kiểm chứng bảo toàn chuẩn L2 và sai số
< 1e-5, sau đó tính tay và đối chiếu hàm trộnYaRN(beta_slow=1, beta_fast=32, \(s=8\)) trênaudit_rope_invariance_and_yarn. -
Bài tập 4 (
20%) — Tính Ngân sáchKV-Cache& Triển khai Cache Tăng dầnGQA+MLA:Tính bằng tay dung lượng
KV-Cache(bf16&fp8) cho mô hình7B,70B,671Btại128K, giải thích vì saoMLAphải tách riêng nhánhDecoupled RoPE, và xác minhaudit_gqa_kv_cache_parity+audit_mla_latent_cache_compression(< 1e-5). -
Bài tập 5 (
15%) — TầngSparse MoE, Cân bằng Tải & Chẩn đoán Sụp đổ Bộ định tuyến:Tính tỷ lệ tham số kích hoạt
Active/TotalcủaTop-2/8, chứng minh \(\mathcal{L}_{\text{aux}} = \alpha E \sum f_e P_e \ge \alpha\) bằng Cauchy–Schwarz, và so sánhRouter Collapse(CV = 1.73,6dead) với cân bằng thiên lệch động (CV = 0.16,0dead) quaaudit_moe_router_collapse_vs_balanced. -
Bài tập 6 (
15%) — Động cơ Giải mãMin-p, Mặt nạFSM JSON100%&Safetensors(16/16 Pytest):So sánh phân tích định lượng
Top-k/Top-p/Min-ptrên hai miền entropy thấp/cao ở \(\tau = 1.5\), chứng minh tính tất định văn phạm củamask_logits_for_json_fsm, kiểm thử lưu/nạpsafetensors(diff = 0.0) và vượt trọn bộ16/16 pytest,ruff,mypy,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 & Kiến trúc (Trụ cột 1 & 2) | Tiêu chí Thực nghiệm & Hệ thống (WB-Ch19) |
|---|---|---|
Principal / MSc Distinction (>= 85%) |
Chứng minh trọn vẹn \(\operatorname{Var}(\mathbf{q}^\top\mathbf{k})=d_k\), đẳng thức RoPE \(SO(2)\), đệ quy Online Softmax FlashAttention, công thức KV-Cache MHA/GQA/MLA, bất đẳng thức Cauchy–Schwarz của \(\mathcal{L}_{\text{aux}}\) MoE và cơ chế Min-p/FSM; thiết kế đúng kiến trúc Prefill/Decode |
Đạt 16/16 pytest (0 skips, 0 lỗi ruff/mypy), FlashAttention khớp < 1e-12, RoPE/GQA/MLA khớp < 1e-5, MoE khử sạch chuyên gia chết (0 dead), FSM JSON 100%, safetensors 0.0 và xuất chuẩn artifacts/ch19_wb19_results.json |
Senior / Đạt chuẩn (70% – 84%) |
Nắm vững cơ chế Attention, RoPE, GQA, FlashAttention, MoE và Min-p/FSM, nhưng còn thiếu bước chứng minh toán học YaRN hoặc lý do tách Decoupled RoPE trong MLA |
Chạy thông suốt run_lab_demo.py và qua đa số kiểm thử, nhưng chưa kiểm chứng đủ N không chia hết cho tile FlashAttention hoặc thiếu kiểm thử MLA cache tăng dần |
Cần khắc phục (< 70%) |
Nhầm lẫn FlashAttention là xấp xỉ Attention, nhầm công thức KV-Cache bỏ hệ số 2 (K và V), hoặc đánh đồng Top-p với Min-p / dùng prompt thay cho FSM |
Không khớp parity cache tăng dần, để router MoE sụp đổ, dùng pickle lưu trọng số, hoặc thất bại bộ pytest WB-Ch19 |
70B-Class LLM KV-Cache at 128K Context (bf16 GB, Lower is Better)
Attention HBM Memory Traffic & Peak Act at N=32K (GB, Lower is Better)
Sparse MoE (Top-2/8) Router Load Balance Metrics (Lower is Better)
Confident Regime (T=1.5) Noise-Tail Leakage & Active Tokens
1/sqrt(d_k) Variance Stabilization & Softmax Entropy Preservation
| d_k | Unscaled Var | Scaled Var | Entropy (Raw vs Scaled) |
|---|---|---|---|
| 16 | 16.2 | 1.01 | 1.12 vs 3.02 |
| 64 | 64.2 | 1.00 | 0.50 vs 3.01 |
| 128 | 129.0 | 1.01 | 0.32 vs 3.01 |
| 256 | 254.6 | 0.99 | 0.23 vs 3.02 |
KV-Cache Footprint at 128K Context (bf16 GB): MHA vs GQA vs MQA vs MLA
| Model Class (128K) | MHA (GB) | GQA 8:1 (GB) | MLA bf16 (GB) & Ratio |
|---|---|---|---|
| 7B (L=32, H=32) | 68.72 | 17.18 | 2.68 (25.6x) |
| 70B Llama-3 (L=80, H=64) | 343.60 | 42.95 | 12.08 (28.4x) |
| 671B DeepSeek-V3 (L=61, H=128) | 523.99 | 65.50 | 9.21 (56.9x) |
Numerical Parity: FlashAttention, RoPE, GQA/MLA Cache & Safetensors
| Audit Check | Measured Error | Target Bound | Status |
|---|---|---|---|
| FlashAttention vs Naive O(N^2) | 8.88e-16 | < 1e-5 | EXACT PASS |
| RoPE Relative-Pos Invariance | 9.54e-07 | < 1e-5 | EXACT PASS |
| GQA Incremental KV-Cache | 3.58e-07 | < 1e-5 | EXACT PASS |
| MLA Latent KV-Cache | 7.45e-08 | < 1e-5 | EXACT PASS |
| Safetensors Round-Trip | 0.00e+00 | == 0.0 | EXACT PASS |
Decoding Engine Audit: Beam Search, Min-p Adaptivity & FSM JSON Reliability
| Decoding Mechanism | Observed Outcome | Comparison / Baseline | Verdict |
|---|---|---|---|
| Beam Search (B=3, alpha=0.7) | logp=-0.844 (seq [0, 2, 0]) | Greedy logp=-2.018 (seq [0, 1, 0]) | BEAM WINS GLOBAL |
| Min-p (0.10) Low-Entropy (T=1.5) | 2 active toks | Top-p(0.95): 41 toks | ZERO TAIL LEAK |
| FSM JSON Logit Masking | 60/60 valid (100%) | Naive: 0/60 | 100% SCHEMA SAFE |
| Contextual Embedding Shift | ctx_cos=0.406 | static_cos=1.000 | POLYSEMY RESOLVED |
02-track-1-data-science-and-ai/part-04-nlp-llm-post-training-and-safety/labs/ch19-attention-and-modern-llm-workbench
[build-system]
requires = ["setuptools>=68.0"]
build-backend = "setuptools.build_meta"
[project]
name = "transformer-llm-lab"
version = "0.1.0"
description = "WB-Ch19: Attention, Transformers & Modern 2026 LLM Architecture Workbench (T1-P4-U02)."
readme = "README.md"
requires-python = ">=3.12"
dependencies = [
"numpy>=1.26",
"pydantic>=2.0",
"safetensors>=0.4",
"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
"""WB-Ch19: Attention, Transformers & Modern 2026 LLM Architecture Workbench (`T1-P4-U02`)."""
from transformer_llm_lab.attention_math_and_flash import (
AttentionBenchmarkConfig,
FlashTilingConfig,
audit_scaled_dot_product_variance,
bahdanau_additive_attention,
compute_attention_hbm_traffic,
flash_attention_tiled_forward,
luong_multiplicative_attention,
naive_scaled_dot_product_attention,
)
from transformer_llm_lab.kv_cache_and_decoding import (
JSON_FSM_VOCAB,
DecodingConfig,
KVCacheSpec,
audit_min_p_vs_top_p_entropy,
benchmark_fsm_json_decoding,
benchmark_kv_cache_scaling,
compute_kv_cache_memory_bytes,
decode_beam_search,
decode_greedy,
decode_json_with_fsm,
filter_logits_min_p,
filter_logits_top_k,
filter_logits_top_p,
mask_logits_for_json_fsm,
sample_with_decoding_strategy,
)
from transformer_llm_lab.modern_llm_blocks import (
GQAAttention,
MLAAttention,
ModernLLMConfig,
ModernTransformerBlock,
ModernTransformerLM,
RMSNorm,
RotaryEmbedding,
SparseMoELayer,
SwiGLU,
audit_contextual_embeddings_shift,
audit_gqa_kv_cache_parity,
audit_mla_latent_cache_compression,
audit_moe_router_collapse_vs_balanced,
audit_rope_invariance_and_yarn,
compute_yarn_inv_freq,
load_safetensors_checkpoint,
run_full_ch19_wb19_benchmarks,
save_safetensors_checkpoint,
)
__all__ = [
"AttentionBenchmarkConfig",
"FlashTilingConfig",
"KVCacheSpec",
"DecodingConfig",
"ModernLLMConfig",
"JSON_FSM_VOCAB",
"bahdanau_additive_attention",
"luong_multiplicative_attention",
"naive_scaled_dot_product_attention",
"audit_scaled_dot_product_variance",
"flash_attention_tiled_forward",
"compute_attention_hbm_traffic",
"compute_kv_cache_memory_bytes",
"benchmark_kv_cache_scaling",
"decode_greedy",
"decode_beam_search",
"filter_logits_top_k",
"filter_logits_top_p",
"filter_logits_min_p",
"sample_with_decoding_strategy",
"audit_min_p_vs_top_p_entropy",
"mask_logits_for_json_fsm",
"decode_json_with_fsm",
"benchmark_fsm_json_decoding",
"RMSNorm",
"SwiGLU",
"RotaryEmbedding",
"compute_yarn_inv_freq",
"GQAAttention",
"MLAAttention",
"SparseMoELayer",
"ModernTransformerBlock",
"ModernTransformerLM",
"save_safetensors_checkpoint",
"load_safetensors_checkpoint",
"audit_rope_invariance_and_yarn",
"audit_gqa_kv_cache_parity",
"audit_mla_latent_cache_compression",
"audit_moe_router_collapse_vs_balanced",
"audit_contextual_embeddings_shift",
"run_full_ch19_wb19_benchmarks",
]
"""Tier 1 Analytical Core: Classical Attention, 1/sqrt(d_k) Variance Proof & FlashAttention Tiling."""
from __future__ import annotations
import math
from typing import Any
import numpy as np
from numpy.typing import NDArray
from pydantic import BaseModel, ConfigDict, Field
class AttentionBenchmarkConfig(BaseModel):
"""Strict configuration for Scaled Dot-Product variance & saturation audit."""
model_config = ConfigDict(extra="forbid")
d_k_values: tuple[int, ...] = Field(default=(16, 64, 128, 256))
seq_len: int = Field(default=32, ge=4, le=512)
num_trials: int = Field(default=64, ge=8, le=512)
seed: int = Field(default=42, ge=0)
class FlashTilingConfig(BaseModel):
"""Strict configuration for IO-Aware FlashAttention online safe softmax tiling."""
model_config = ConfigDict(extra="forbid")
seq_len: int = Field(default=128, ge=8, le=131072)
d_head: int = Field(default=64, ge=8, le=256)
num_heads: int = Field(default=32, ge=1, le=256)
batch_size: int = Field(default=1, ge=1, le=128)
block_r: int = Field(default=32, ge=4, le=256)
block_c: int = Field(default=32, ge=4, le=256)
dtype_bytes: int = Field(default=2, ge=1, le=4)
causal: bool = Field(default=True)
def _softmax_rows(x: NDArray[np.float64]) -> NDArray[np.float64]:
"""Numerically stable row-wise softmax handling -inf masked rows safely."""
row_max = np.max(x, axis=-1, keepdims=True)
safe_max = np.where(np.isfinite(row_max), row_max, 0.0)
shifted = x - safe_max
exps = np.exp(shifted)
exps = np.where(np.isfinite(x), exps, 0.0)
denom = np.sum(exps, axis=-1, keepdims=True)
return exps / np.maximum(denom, 1e-30)
def bahdanau_additive_attention(
decoder_state: NDArray[np.float64],
encoder_states: NDArray[np.float64],
w_a: NDArray[np.float64],
u_a: NDArray[np.float64],
v_a: NDArray[np.float64],
) -> tuple[NDArray[np.float64], NDArray[np.float64]]:
"""Compute Bahdanau (2015) additive attention: e_j = v_a^T tanh(W_a s + U_a h_j).
Args:
decoder_state: Shape `(d_dec,)`.
encoder_states: Shape `(T_s, d_enc)`.
w_a: Shape `(d_attn, d_dec)`.
u_a: Shape `(d_attn, d_enc)`.
v_a: Shape `(d_attn,)`.
Returns:
Tuple of `(context_vector [d_enc], attention_weights [T_s])`.
"""
proj_dec = w_a @ decoder_state # (d_attn,)
proj_enc = encoder_states @ u_a.T # (T_s, d_attn)
energies = np.tanh(proj_enc + proj_dec[None, :]) @ v_a # (T_s,)
weights = _softmax_rows(energies[None, :])[0]
context = weights @ encoder_states
return context, weights
def luong_multiplicative_attention(
decoder_state: NDArray[np.float64],
encoder_states: NDArray[np.float64],
w_a: NDArray[np.float64] | None = None,
) -> tuple[NDArray[np.float64], NDArray[np.float64]]:
"""Compute Luong (2015) multiplicative (dot or general bilinear) attention.
Args:
decoder_state: Shape `(d_dec,)`.
encoder_states: Shape `(T_s, d_enc)`.
w_a: Optional bilinear matrix of shape `(d_dec, d_enc)`. If None, uses dot product.
Returns:
Tuple of `(context_vector [d_enc], attention_weights [T_s])`.
"""
if w_a is None:
energies = encoder_states @ decoder_state
else:
energies = encoder_states @ (w_a.T @ decoder_state)
weights = _softmax_rows(energies[None, :])[0]
context = weights @ encoder_states
return context, weights
def naive_scaled_dot_product_attention(
q: NDArray[np.float64],
k: NDArray[np.float64],
v: NDArray[np.float64],
causal: bool = True,
scale: float | None = None,
) -> tuple[NDArray[np.float64], NDArray[np.float64]]:
"""Reference materialized O(N^2) Scaled Dot-Product Attention.
Args:
q: Query matrix `(N, d_k)`.
k: Key matrix `(N, d_k)`.
v: Value matrix `(N, d_v)`.
causal: Whether to apply strict lower-triangular causal mask (`j <= i`).
scale: Multiplicative scale; defaults to `1 / sqrt(d_k)`.
Returns:
Tuple `(output [N, d_v], attn_weights [N, N])`.
"""
n_seq, d_k = q.shape
eff_scale = (1.0 / math.sqrt(d_k)) if scale is None else float(scale)
scores = (q @ k.T) * eff_scale
if causal:
mask = np.triu(np.ones((n_seq, n_seq), dtype=bool), k=1)
scores = np.where(mask, -np.inf, scores)
attn_weights = _softmax_rows(scores)
output = attn_weights @ v
return output, attn_weights
def audit_scaled_dot_product_variance(
cfg: AttentionBenchmarkConfig | None = None,
) -> dict[str, Any]:
"""Empirically verify Var(q^T k) = d_k vs Var(q^T k / sqrt(d_k)) = 1 and softmax saturation."""
config = cfg or AttentionBenchmarkConfig()
rng = np.random.default_rng(config.seed)
records: list[dict[str, float | int]] = []
max_entropy = math.log(config.seq_len)
for d_k in config.d_k_values:
q = rng.standard_normal((config.num_trials, config.seq_len, d_k))
k = rng.standard_normal((config.num_trials, config.seq_len, d_k))
raw_scores = np.einsum("btd,bsd->bts", q, k)
scaled_scores = raw_scores / math.sqrt(d_k)
raw_var = float(np.var(raw_scores))
scaled_var = float(np.var(scaled_scores))
p_raw = _softmax_rows(raw_scores)
p_scaled = _softmax_rows(scaled_scores)
# Entropy H(p) = -sum p log p
h_raw = float(np.mean(-np.sum(p_raw * np.log(np.maximum(p_raw, 1e-30)), axis=-1)))
h_scaled = float(np.mean(-np.sum(p_scaled * np.log(np.maximum(p_scaled, 1e-30)), axis=-1)))
# Softmax Jacobian diagonal p_i * (1 - p_i) peak tracks gradient flow health
max_p_raw = float(np.mean(np.max(p_raw, axis=-1)))
max_p_scaled = float(np.mean(np.max(p_scaled, axis=-1)))
grad_health_raw = float(np.mean(np.sum(p_raw * (1.0 - p_raw), axis=-1)))
grad_health_scaled = float(np.mean(np.sum(p_scaled * (1.0 - p_scaled), axis=-1)))
records.append(
{
"d_k": int(d_k),
"unscaled_var": raw_var,
"scaled_var": scaled_var,
"unscaled_entropy": h_raw,
"scaled_entropy": h_scaled,
"entropy_retention_pct": float(100.0 * h_scaled / max(max_entropy, 1e-12)),
"unscaled_entropy_pct": float(100.0 * h_raw / max(max_entropy, 1e-12)),
"unscaled_max_prob": max_p_raw,
"scaled_max_prob": max_p_scaled,
"unscaled_jacobian_trace": grad_health_raw,
"scaled_jacobian_trace": grad_health_scaled,
}
)
return {
"seq_len": config.seq_len,
"max_uniform_entropy": max_entropy,
"by_d_k": records,
}
def flash_attention_tiled_forward(
q: NDArray[np.float64],
k: NDArray[np.float64],
v: NDArray[np.float64],
block_r: int = 16,
block_c: int = 16,
causal: bool = True,
) -> tuple[NDArray[np.float64], dict[str, Any]]:
"""Exact IO-Aware FlashAttention using Online Safe Softmax tiling (Dao et al., 2022/2023).
Computes exact Scaled Dot-Product Attention without ever materializing the full N x N
attention matrix in HBM. Uses the Milakov & Gimelshein online log-sum-exp recurrence:
m_new = max(m_old, m_tilde)
l_new = exp(m_old - m_new) * l_old + exp(m_tilde - m_new) * l_tilde
O_new = (exp(m_old - m_new) * l_old * O_old + exp(m_tilde - m_new) * P_tilde @ V_j) / l_new
"""
n_seq, d_k = q.shape
d_v = v.shape[1]
scale = 1.0 / math.sqrt(d_k)
out = np.zeros((n_seq, d_v), dtype=np.float64)
lse = np.full((n_seq,), -np.inf, dtype=np.float64)
n_row_blocks = math.ceil(n_seq / block_r)
n_col_blocks = math.ceil(n_seq / block_c)
active_tiles = 0
skipped_causal_tiles = 0
for i_blk in range(n_row_blocks):
r_start = i_blk * block_r
r_end = min(r_start + block_r, n_seq)
b_r = r_end - r_start
q_i = q[r_start:r_end] # (b_r, d_k)
o_i = np.zeros((b_r, d_v), dtype=np.float64)
m_i = np.full((b_r, 1), -np.inf, dtype=np.float64)
l_i = np.zeros((b_r, 1), dtype=np.float64)
for j_blk in range(n_col_blocks):
c_start = j_blk * block_c
c_end = min(c_start + block_c, n_seq)
# Skip strictly upper-triangular causal blocks entirely (FlashAttention-2 2x causal speedup)
if causal and c_start >= r_end:
skipped_causal_tiles += 1
continue
active_tiles += 1
k_j = k[c_start:c_end] # (b_c, d_k)
v_j = v[c_start:c_end] # (b_c, d_v)
s_ij = (q_i @ k_j.T) * scale # (b_r, b_c)
if causal and c_end > r_start:
row_idx = np.arange(r_start, r_end)[:, None]
col_idx = np.arange(c_start, c_end)[None, :]
s_ij = np.where(col_idx > row_idx, -np.inf, s_ij)
m_ij = np.max(s_ij, axis=-1, keepdims=True) # (b_r, 1)
m_new = np.maximum(m_i, m_ij)
# Safe rescaling factors handling initial -inf gracefully
alpha = np.where(np.isfinite(m_i), np.exp(m_i - m_new), 0.0)
beta = np.where(np.isfinite(m_ij), np.exp(m_ij - m_new), 0.0)
safe_m_ij = np.where(np.isfinite(m_ij), m_ij, 0.0)
p_tilde = np.where(np.isfinite(s_ij), np.exp(s_ij - safe_m_ij), 0.0)
l_ij = np.sum(p_tilde, axis=-1, keepdims=True)
l_new = alpha * l_i + beta * l_ij
pv_tile = p_tilde @ v_j # (b_r, d_v)
# Rescale running numerator and divide by l_new
num_new = (alpha * l_i) * o_i + beta * pv_tile
o_i = np.where(l_new > 0.0, num_new / np.maximum(l_new, 1e-30), 0.0)
m_i = m_new
l_i = l_new
out[r_start:r_end] = o_i
lse[r_start:r_end] = (m_i[:, 0] + np.log(np.maximum(l_i[:, 0], 1e-30)))
stats = {
"seq_len": n_seq,
"d_head": d_k,
"block_r": block_r,
"block_c": block_c,
"causal": causal,
"total_tiles": n_row_blocks * n_col_blocks,
"active_tiles": active_tiles,
"skipped_causal_tiles": skipped_causal_tiles,
"peak_sram_elements": int(block_r * d_k + 2 * block_c * d_k + block_r * block_c + block_r * d_v),
"lse_finite": bool(np.all(np.isfinite(lse))),
}
return out, stats
def compute_attention_hbm_traffic(cfg: FlashTilingConfig) -> dict[str, Any]:
"""Compute exact analytical HBM bytes transferred for Naive O(N^2) vs FlashAttention Tiling.
Standard materialized attention (per head):
- Read Q, K (2 N d), Write S (N^2)
- Read S (N^2), Write P (N^2)
- Read P (N^2), Read V (N d), Write O (N d)
=> Total elements = 4 N d + 4 N^2
FlashAttention-2 tiled (per head):
- Outer loop over Q blocks (T_r = ceil(N / B_r)):
Read Q_i once (N d), Write O_i once (N d) + LSE (N)
Inner loop streams K_j, V_j: each block read T_r times (or ~T_r/2 if causal!)
=> Total elements = 2 N d + 2 * active_kv_passes * N d + N
"""
n = cfg.seq_len
d = cfg.d_head
bh = cfg.batch_size * cfg.num_heads
b_bytes = cfg.dtype_bytes
t_r = math.ceil(n / cfg.block_r)
# Under causal masking, row block i only loads K,V blocks up to i -> avg (T_r + 1) / 2 passes
effective_kv_passes = (t_r + 1.0) / 2.0 if cfg.causal else float(t_r)
naive_elems_per_head = 4.0 * n * d + 4.0 * n * n
flash_elems_per_head = 2.0 * n * d + 2.0 * effective_kv_passes * n * d + n
naive_hbm_bytes = naive_elems_per_head * bh * b_bytes
flash_hbm_bytes = flash_elems_per_head * bh * b_bytes
# Peak materialized attention activation memory: Naive stores S & P (2 * B * H * N^2),
# FlashAttention stores only row-wise log-sum-exp (B * H * N in fp32).
naive_peak_act_bytes = float(2 * bh * n * n * b_bytes)
flash_peak_act_bytes = float(bh * n * 4)
# Attention FLOPs: 2 * N^2 * d (QK^T) + 2 * N^2 * d (PV), halved for causal
flops_per_head = (2.0 if cfg.causal else 4.0) * n * n * d
total_flops = flops_per_head * bh
reduction_factor = naive_hbm_bytes / max(flash_hbm_bytes, 1.0)
reduction_pct = 100.0 * (1.0 - flash_hbm_bytes / max(naive_hbm_bytes, 1.0))
return {
"seq_len": n,
"d_head": d,
"num_heads": cfg.num_heads,
"batch_size": cfg.batch_size,
"block_r": cfg.block_r,
"block_c": cfg.block_c,
"causal": cfg.causal,
"naive_hbm_mb": naive_hbm_bytes / 1e6,
"flash_hbm_mb": flash_hbm_bytes / 1e6,
"hbm_reduction_factor": reduction_factor,
"hbm_reduction_pct": reduction_pct,
"naive_peak_act_mb": naive_peak_act_bytes / 1e6,
"flash_peak_act_mb": flash_peak_act_bytes / 1e6,
"naive_arithmetic_intensity": total_flops / max(naive_hbm_bytes, 1.0),
"flash_arithmetic_intensity": total_flops / max(flash_hbm_bytes, 1.0),
}
"""Tier 1 Accounting & Decoding Engine: KV-Cache (MHA/GQA/MQA/MLA), Min-p & FSM JSON Decoding."""
from __future__ import annotations
import json
import math
from collections.abc import Callable
from typing import Any, Literal
import numpy as np
from numpy.typing import NDArray
from pydantic import BaseModel, ConfigDict, Field, model_validator
class KVCacheSpec(BaseModel):
"""Strict specification for KV-Cache memory accounting across attention variants."""
model_config = ConfigDict(extra="forbid")
variant: Literal["mha", "gqa", "mqa", "mla"] = "gqa"
num_layers: int = Field(default=80, ge=1, le=256)
num_q_heads: int = Field(default=64, ge=1, le=256)
num_kv_heads: int = Field(default=8, ge=1, le=256)
d_head: int = Field(default=128, ge=8, le=512)
d_c_latent: int = Field(default=512, ge=16, le=4096)
d_rope_shared: int = Field(default=64, ge=8, le=512)
seq_len: int = Field(default=131072, ge=1, le=4194304)
batch_size: int = Field(default=1, ge=1, le=1024)
dtype_bytes: int = Field(default=2, ge=1, le=4)
@model_validator(mode="after")
def _validate_head_divisibility(self) -> KVCacheSpec:
if self.variant == "mha" and self.num_kv_heads != self.num_q_heads:
raise ValueError("For MHA, num_kv_heads must equal num_q_heads.")
if self.variant == "mqa" and self.num_kv_heads != 1:
raise ValueError("For MQA, num_kv_heads must be 1.")
if self.variant == "gqa" and (self.num_q_heads % self.num_kv_heads != 0):
raise ValueError("For GQA, num_q_heads must be divisible by num_kv_heads.")
return self
class DecodingConfig(BaseModel):
"""Strict configuration for LLM token decoding strategies."""
model_config = ConfigDict(extra="forbid")
strategy: Literal["greedy", "temperature", "top_k", "top_p", "min_p"] = "min_p"
temperature: float = Field(default=1.0, gt=0.0, le=5.0)
top_k: int = Field(default=0, ge=0, le=100000)
top_p: float = Field(default=1.0, gt=0.0, le=1.0)
min_p: float = Field(default=0.1, ge=0.0, lt=1.0)
def compute_kv_cache_memory_bytes(spec: KVCacheSpec) -> dict[str, float | int | str]:
"""Compute exact KV-Cache memory footprint in bytes, GB (10^9) and GiB (2^30).
- MHA/GQA/MQA: 2 * L * n_kv * d_h * S * B * dtype_bytes
- DeepSeek MLA: L * (d_c + d_rope_shared) * S * B * dtype_bytes
"""
if spec.variant == "mla":
elems_per_layer_per_token = spec.d_c_latent + spec.d_rope_shared
else:
elems_per_layer_per_token = 2 * spec.num_kv_heads * spec.d_head
bytes_per_token = spec.num_layers * elems_per_layer_per_token * spec.dtype_bytes
total_bytes = bytes_per_token * spec.seq_len * spec.batch_size
return {
"variant": spec.variant,
"seq_len": spec.seq_len,
"batch_size": spec.batch_size,
"dtype_bytes": spec.dtype_bytes,
"elems_per_layer_per_token": elems_per_layer_per_token,
"bytes_per_token": bytes_per_token,
"total_bytes": total_bytes,
"total_gb": total_bytes / 1e9,
"total_gib": total_bytes / (1024**3),
}
def benchmark_kv_cache_scaling() -> dict[str, Any]:
"""Compare MHA vs GQA (8:1) vs MQA vs DeepSeek MLA across 7B, 70B & 671B LLMs."""
presets: dict[str, dict[str, int]] = {
"7B_class": {
"num_layers": 32,
"num_q_heads": 32,
"num_kv_heads_gqa": 8,
"d_head": 128,
"d_c_latent": 256,
"d_rope_shared": 64,
},
"70B_llama3_class": {
"num_layers": 80,
"num_q_heads": 64,
"num_kv_heads_gqa": 8,
"d_head": 128,
"d_c_latent": 512,
"d_rope_shared": 64,
},
"671B_deepseek_v3_class": {
"num_layers": 61,
"num_q_heads": 128,
"num_kv_heads_gqa": 16,
"d_head": 128,
"d_c_latent": 512,
"d_rope_shared": 64,
},
}
seq_lens = (8192, 32768, 131072)
results: dict[str, Any] = {}
for model_name, p in presets.items():
model_rows: dict[str, Any] = {}
for seq_len in seq_lens:
mha = compute_kv_cache_memory_bytes(
KVCacheSpec(
variant="mha",
num_layers=p["num_layers"],
num_q_heads=p["num_q_heads"],
num_kv_heads=p["num_q_heads"],
d_head=p["d_head"],
seq_len=seq_len,
dtype_bytes=2,
)
)
gqa = compute_kv_cache_memory_bytes(
KVCacheSpec(
variant="gqa",
num_layers=p["num_layers"],
num_q_heads=p["num_q_heads"],
num_kv_heads=p["num_kv_heads_gqa"],
d_head=p["d_head"],
seq_len=seq_len,
dtype_bytes=2,
)
)
mqa = compute_kv_cache_memory_bytes(
KVCacheSpec(
variant="mqa",
num_layers=p["num_layers"],
num_q_heads=p["num_q_heads"],
num_kv_heads=1,
d_head=p["d_head"],
seq_len=seq_len,
dtype_bytes=2,
)
)
mla = compute_kv_cache_memory_bytes(
KVCacheSpec(
variant="mla",
num_layers=p["num_layers"],
num_q_heads=p["num_q_heads"],
num_kv_heads=p["num_kv_heads_gqa"],
d_head=p["d_head"],
d_c_latent=p["d_c_latent"],
d_rope_shared=p["d_rope_shared"],
seq_len=seq_len,
dtype_bytes=2,
)
)
mla_fp8 = compute_kv_cache_memory_bytes(
KVCacheSpec(
variant="mla",
num_layers=p["num_layers"],
num_q_heads=p["num_q_heads"],
num_kv_heads=p["num_kv_heads_gqa"],
d_head=p["d_head"],
d_c_latent=p["d_c_latent"],
d_rope_shared=p["d_rope_shared"],
seq_len=seq_len,
dtype_bytes=1,
)
)
mha_gb = float(mha["total_gb"])
gqa_gb = float(gqa["total_gb"])
mqa_gb = float(mqa["total_gb"])
mla_gb = float(mla["total_gb"])
model_rows[str(seq_len)] = {
"mha_bf16_gb": mha_gb,
"gqa_bf16_gb": gqa_gb,
"mqa_bf16_gb": mqa_gb,
"mla_bf16_gb": mla_gb,
"mla_fp8_gb": float(mla_fp8["total_gb"]),
"gqa_vs_mha_compression": mha_gb / gqa_gb,
"mla_vs_mha_compression": mha_gb / mla_gb,
"mla_vs_gqa_compression": gqa_gb / mla_gb,
"h100_80gb_max_concurrency_gqa": int(60.0 // max(gqa_gb, 1e-9)),
"h100_80gb_max_concurrency_mla": int(60.0 // max(mla_gb, 1e-9)),
}
results[model_name] = model_rows
return results
# ---------------------------------------------------------------------------
# Decoding Engine: Greedy, Beam Search, Temperature, Top-k, Top-p, Min-p
# ---------------------------------------------------------------------------
def softmax_stable(logits: NDArray[np.float64], temperature: float = 1.0) -> NDArray[np.float64]:
"""Temperature-scaled numerically stable softmax preserving -inf masks."""
if temperature <= 0.0:
raise ValueError("temperature must be strictly positive.")
scaled = logits.astype(np.float64) / float(temperature)
finite_mask = np.isfinite(scaled)
if not np.any(finite_mask):
raise ValueError("All logits are -inf; cannot form valid probability distribution.")
max_val = float(np.max(scaled[finite_mask]))
exps = np.where(finite_mask, np.exp(scaled - max_val), 0.0)
return exps / float(np.sum(exps))
def filter_logits_top_k(logits: NDArray[np.float64], k: int) -> NDArray[np.float64]:
"""Keep only top-k highest logits and mask all others to -inf."""
out = logits.astype(np.float64).copy()
if k <= 0 or k >= out.size:
return out
finite_count = int(np.sum(np.isfinite(out)))
eff_k = min(k, max(finite_count, 1))
top_indices = np.argsort(out)[::-1][:eff_k]
masked = np.full_like(out, -np.inf)
masked[top_indices] = out[top_indices]
return masked
def filter_logits_top_p(
logits: NDArray[np.float64], top_p: float, temperature: float = 1.0
) -> NDArray[np.float64]:
"""Nucleus (Top-p) filtering keeping smallest set whose cumulative probability >= top_p."""
out = logits.astype(np.float64).copy()
if top_p >= 1.0:
return out
probs = softmax_stable(out, temperature=temperature)
order = np.argsort(probs)[::-1]
sorted_probs = probs[order]
cum_probs = np.cumsum(sorted_probs)
# Keep first token that crosses top_p as well (standard Holtzman et al. shift)
keep_sorted = (cum_probs - sorted_probs) < top_p
keep_sorted[0] = True
keep_indices = order[keep_sorted & (sorted_probs > 0.0)]
masked = np.full_like(out, -np.inf)
masked[keep_indices] = out[keep_indices]
return masked
def filter_logits_min_p(
logits: NDArray[np.float64], min_p: float, temperature: float = 1.0
) -> NDArray[np.float64]:
"""Min-p filtering (Nguyen et al., 2024): keep tokens with p_i >= min_p * p_max."""
out = logits.astype(np.float64).copy()
if min_p <= 0.0:
return out
probs = softmax_stable(out, temperature=temperature)
p_max = float(np.max(probs))
threshold = float(min_p) * p_max
keep_mask = probs >= threshold
keep_mask[int(np.argmax(probs))] = True
return np.where(keep_mask, out, -np.inf)
def sample_with_decoding_strategy(
logits: NDArray[np.float64],
cfg: DecodingConfig,
rng: np.random.Generator | None = None,
) -> tuple[int, NDArray[np.float64], int, float]:
"""Sample or greedily select a token and return `(token_id, probs, active_count, entropy)`."""
gen = rng or np.random.default_rng(42)
if cfg.strategy == "greedy":
token_id = int(np.argmax(logits))
probs = np.zeros_like(logits, dtype=np.float64)
probs[token_id] = 1.0
return token_id, probs, 1, 0.0
filtered = logits.astype(np.float64).copy()
if cfg.strategy == "top_k":
filtered = filter_logits_top_k(filtered, cfg.top_k)
elif cfg.strategy == "top_p":
filtered = filter_logits_top_p(filtered, cfg.top_p, temperature=cfg.temperature)
elif cfg.strategy == "min_p":
filtered = filter_logits_min_p(filtered, cfg.min_p, temperature=cfg.temperature)
probs = softmax_stable(filtered, temperature=cfg.temperature)
active_count = int(np.sum(probs > 0.0))
entropy = float(-np.sum(probs * np.log(np.maximum(probs, 1e-30))))
token_id = int(gen.choice(probs.size, p=probs))
return token_id, probs, active_count, entropy
def decode_greedy(
step_logits_fn: Callable[[list[int]], NDArray[np.float64]],
start_tokens: list[int],
max_steps: int,
eos_id: int,
) -> tuple[list[int], float]:
"""Autoregressive greedy decoding returning `(sequence, total_log_prob)`."""
seq = list(start_tokens)
total_logp = 0.0
for _ in range(max_steps):
logits = step_logits_fn(seq)
probs = softmax_stable(logits, temperature=1.0)
next_tok = int(np.argmax(probs))
total_logp += math.log(max(float(probs[next_tok]), 1e-30))
seq.append(next_tok)
if next_tok == eos_id:
break
return seq, total_logp
def decode_beam_search(
step_logits_fn: Callable[[list[int]], NDArray[np.float64]],
start_tokens: list[int],
beam_width: int = 3,
max_steps: int = 6,
eos_id: int = 0,
length_penalty: float = 0.7,
) -> tuple[list[int], float, float]:
"""Beam search with Wu et al. (2016) length penalty `((5 + L) / 6)^alpha`.
Returns:
`(best_sequence, raw_log_prob, normalized_score)`.
"""
beams: list[tuple[list[int], float, bool]] = [(list(start_tokens), 0.0, False)]
def _norm_score(seq: list[int], logp: float) -> float:
gen_len = max(1, len(seq) - len(start_tokens))
lp = ((5.0 + gen_len) / 6.0) ** length_penalty
return logp / lp
for _ in range(max_steps):
candidates: list[tuple[list[int], float, bool]] = []
all_done = True
for seq, logp, done in beams:
if done:
candidates.append((seq, logp, True))
continue
all_done = False
logits = step_logits_fn(seq)
probs = softmax_stable(logits, temperature=1.0)
top_ids = np.argsort(probs)[::-1][:beam_width]
for tid in top_ids:
t_int = int(tid)
new_logp = logp + math.log(max(float(probs[t_int]), 1e-30))
candidates.append((seq + [t_int], new_logp, t_int == eos_id))
if all_done:
break
candidates.sort(key=lambda item: _norm_score(item[0], item[1]), reverse=True)
beams = candidates[:beam_width]
best_seq, best_logp, _ = max(beams, key=lambda item: _norm_score(item[0], item[1]))
return best_seq, best_logp, _norm_score(best_seq, best_logp)
def audit_min_p_vs_top_p_entropy(seed: int = 42) -> dict[str, Any]:
"""Compare Top-k, Top-p and Min-p under confident (low-entropy) vs uncertain (high-entropy) logits."""
rng = np.random.default_rng(seed)
vocab_size = 64
# Confident regime: 1 dominant token (logit=6.0) + 1 runner-up (3.2) + 62 low-prob noise tail
confident_logits = rng.normal(-2.5, 0.35, size=vocab_size)
confident_logits[0] = 6.0
confident_logits[1] = 3.2
# Uncertain regime: 6 plausible candidates near logit ~2.6 + 58 tail tokens
uncertain_logits = rng.normal(-1.8, 0.35, size=vocab_size)
uncertain_logits[:6] = np.array([2.85, 2.70, 2.55, 2.40, 2.25, 2.10])
regimes = {"confident_low_entropy": confident_logits, "uncertain_high_entropy": uncertain_logits}
out: dict[str, Any] = {}
temp = 1.5 # Elevated sampling temperature where Top-p leaks noise tail!
for name, logits in regimes.items():
base_probs = softmax_stable(logits, temperature=temp)
p_max = float(np.max(base_probs))
_, p_topk, cnt_topk, h_topk = sample_with_decoding_strategy(
logits, DecodingConfig(strategy="top_k", temperature=temp, top_k=10), rng=rng
)
_, p_topp, cnt_topp, h_topp = sample_with_decoding_strategy(
logits, DecodingConfig(strategy="top_p", temperature=temp, top_p=0.95), rng=rng
)
_, p_minp, cnt_minp, h_minp = sample_with_decoding_strategy(
logits, DecodingConfig(strategy="min_p", temperature=temp, min_p=0.10), rng=rng
)
out[name] = {
"temperature": temp,
"p_max": p_max,
"min_p_threshold": 0.10 * p_max,
"top_k_10_active": cnt_topk,
"top_k_10_tail_leak_prob": float(np.sum(p_topk[6:])),
"top_p_095_active": cnt_topp,
"top_p_095_tail_leak_prob": float(np.sum(p_topp[6:])),
"top_p_095_entropy": h_topp,
"min_p_010_active": cnt_minp,
"min_p_010_tail_leak_prob": float(np.sum(p_minp[6:])),
"min_p_010_entropy": h_minp,
}
return out
# ---------------------------------------------------------------------------
# FSM / Grammar-Constrained Structured JSON Decoding
# Schema enforced: {"status": "<ok|warn|fail>", "score": <0..99>}
# ---------------------------------------------------------------------------
JSON_FSM_VOCAB: tuple[str, ...] = (
'{"status":"', # 0
"ok", # 1
"warn", # 2
"fail", # 3
'","score":', # 4
"1", # 5
"4", # 6
"7", # 7
"9", # 8
"}", # 9
"<EOS>", # 10
# Distractor / syntax-breaking tokens that unconstrained LLMs frequently emit
"```json", # 11
"Sure!", # 12
",", # 13
'":', # 14
"null", # 15
)
# Deterministic Finite Automaton transition table: state -> {token_id: next_state}
_JSON_FSM_TRANSITIONS: dict[int, dict[int, int]] = {
0: {0: 1},
1: {1: 2, 2: 2, 3: 2},
2: {4: 3},
3: {5: 4, 6: 4, 7: 4, 8: 4},
4: {5: 5, 6: 5, 7: 5, 8: 5, 9: 6},
5: {9: 6},
6: {10: 7}, # 7 is accepting terminal state
}
_JSON_FSM_ACCEPT_STATE = 7
def mask_logits_for_json_fsm(logits: NDArray[np.float64], fsm_state: int) -> NDArray[np.float64]:
"""Apply zero-leakage grammar mask: set all invalid token logits to -inf."""
if logits.shape != (len(JSON_FSM_VOCAB),):
raise ValueError(f"Expected logits shape ({len(JSON_FSM_VOCAB)},), got {logits.shape}.")
allowed = _JSON_FSM_TRANSITIONS.get(fsm_state)
if not allowed:
raise ValueError(f"Invalid or terminal FSM state: {fsm_state}")
masked = np.full_like(logits, -np.inf, dtype=np.float64)
for tok_id in allowed:
masked[tok_id] = logits[tok_id]
return masked
def decode_json_with_fsm(
logits_sequence: NDArray[np.float64],
use_fsm: bool = True,
temperature: float = 1.2,
min_p: float = 0.1,
seed: int = 42,
) -> dict[str, Any]:
"""Decode structured JSON from step-wise logits with or without FSM grammar masking."""
rng = np.random.default_rng(seed)
state = 0
tokens: list[str] = []
max_steps = logits_sequence.shape[0]
cfg = DecodingConfig(strategy="min_p", temperature=temperature, min_p=min_p)
for step in range(max_steps):
step_logits = logits_sequence[step]
if use_fsm:
step_logits = mask_logits_for_json_fsm(step_logits, state)
tok_id, _, _, _ = sample_with_decoding_strategy(step_logits, cfg, rng=rng)
if use_fsm:
state = _JSON_FSM_TRANSITIONS[state][tok_id]
if tok_id == 10: # <EOS>
break
tokens.append(JSON_FSM_VOCAB[tok_id])
if use_fsm and state == _JSON_FSM_ACCEPT_STATE:
break
raw_text = "".join(tokens)
parsed: Any = None
is_valid_json = False
is_schema_valid = False
try:
parsed = json.loads(raw_text)
is_valid_json = True
if (
isinstance(parsed, dict)
and set(parsed.keys()) == {"status", "score"}
and parsed["status"] in {"ok", "warn", "fail"}
and isinstance(parsed["score"], int)
and 0 <= parsed["score"] <= 99
):
is_schema_valid = True
except (json.JSONDecodeError, TypeError, ValueError):
pass
return {
"text": raw_text,
"is_valid_json": is_valid_json,
"is_schema_valid": is_schema_valid,
"parsed": parsed,
}
def benchmark_fsm_json_decoding(num_trials: int = 50, seed: int = 42) -> dict[str, Any]:
"""Prove naive noisy sampling fails JSON schema while FSM masking guarantees 100% validity."""
rng = np.random.default_rng(seed)
vocab_n = len(JSON_FSM_VOCAB)
unconstrained_valid = 0
fsm_valid = 0
sample_unconstrained = ""
sample_fsm = ""
for trial in range(num_trials):
# Noisy logits mimicking a slightly uncertain LLM with markdown/chatter distractors
logits_seq = rng.normal(0.0, 1.5, size=(8, vocab_n))
# Slightly boost realistic distractors ("```json", "Sure!") at step 0
logits_seq[0, 11] += 1.4
logits_seq[0, 12] += 1.1
res_free = decode_json_with_fsm(logits_seq, use_fsm=False, seed=seed + trial)
res_fsm = decode_json_with_fsm(logits_seq, use_fsm=True, seed=seed + trial)
if res_free["is_schema_valid"]:
unconstrained_valid += 1
if res_fsm["is_schema_valid"]:
fsm_valid += 1
if trial == 0:
sample_unconstrained = str(res_free["text"])
sample_fsm = str(res_fsm["text"])
return {
"num_trials": num_trials,
"unconstrained_valid_count": unconstrained_valid,
"unconstrained_valid_rate": unconstrained_valid / max(num_trials, 1),
"fsm_valid_count": fsm_valid,
"fsm_valid_rate": fsm_valid / max(num_trials, 1),
"sample_unconstrained_output": sample_unconstrained,
"sample_fsm_output": sample_fsm,
}
"""Tier 2 PyTorch 2.x Modern LLM Anatomy: RMSNorm, SwiGLU, RoPE+YaRN, GQA, MLA, MoE & Safetensors."""
from __future__ import annotations
import math
import tempfile
from pathlib import Path
from typing import Any
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from pydantic import BaseModel, ConfigDict, Field, model_validator
from safetensors.torch import load_file as safetensors_load_file
from safetensors.torch import save_file as safetensors_save_file
from transformer_llm_lab.attention_math_and_flash import (
AttentionBenchmarkConfig,
FlashTilingConfig,
audit_scaled_dot_product_variance,
bahdanau_additive_attention,
compute_attention_hbm_traffic,
flash_attention_tiled_forward,
luong_multiplicative_attention,
naive_scaled_dot_product_attention,
)
from transformer_llm_lab.kv_cache_and_decoding import (
audit_min_p_vs_top_p_entropy,
benchmark_fsm_json_decoding,
benchmark_kv_cache_scaling,
decode_beam_search,
decode_greedy,
)
class ModernLLMConfig(BaseModel):
"""Strict configuration for ModernTransformerLM (Llama-3 / DeepSeek-V3 style)."""
model_config = ConfigDict(extra="forbid")
vocab_size: int = Field(default=128, ge=16, le=256000)
d_model: int = Field(default=64, ge=16, le=8192)
n_layers: int = Field(default=2, ge=1, le=128)
n_q_heads: int = Field(default=8, ge=1, le=128)
n_kv_heads: int = Field(default=2, ge=1, le=128)
d_ff: int = Field(default=176, ge=16, le=32768)
max_seq_len: int = Field(default=128, ge=8, le=131072)
rope_base: float = Field(default=10000.0, ge=100.0)
use_moe: bool = Field(default=False)
num_experts: int = Field(default=8, ge=2, le=256)
top_k_experts: int = Field(default=2, ge=1, le=16)
moe_aux_weight: float = Field(default=0.01, ge=0.0, le=1.0)
@model_validator(mode="after")
def _validate_dims(self) -> ModernLLMConfig:
if self.d_model % self.n_q_heads != 0:
raise ValueError("d_model must be divisible by n_q_heads.")
d_head = self.d_model // self.n_q_heads
if d_head % 2 != 0:
raise ValueError("d_head must be even for RoPE pair rotation.")
if self.n_q_heads % self.n_kv_heads != 0:
raise ValueError("n_q_heads must be divisible by n_kv_heads.")
if self.top_k_experts > self.num_experts:
raise ValueError("top_k_experts cannot exceed num_experts.")
return self
class RMSNorm(nn.Module):
"""Root Mean Square Layer Normalization (Zhang & Sennrich, 2019) with fp32 variance."""
def __init__(self, d_model: int, eps: float = 1e-6) -> None:
super().__init__()
self.eps = eps
self.weight = nn.Parameter(torch.ones(d_model))
def forward(self, x: torch.Tensor) -> torch.Tensor:
orig_dtype = x.dtype
x_fp32 = x.float()
inv_rms = torch.rsqrt(x_fp32.pow(2).mean(dim=-1, keepdim=True) + self.eps)
return (x_fp32 * inv_rms).to(orig_dtype) * self.weight
class SwiGLU(nn.Module):
"""SwiGLU gated feed-forward block (Shazeer, 2020): (SiLU(x W_gate) * (x W_up)) W_down."""
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))
def compute_yarn_inv_freq(
d_head: int,
base: float = 10000.0,
scale: float = 1.0,
original_max_len: int = 4096,
beta_fast: float = 32.0,
beta_slow: float = 1.0,
) -> tuple[torch.Tensor, float]:
"""Compute YaRN wavelength-aware inverse frequencies and attention temperature mscale.
- High-frequency dims (rotations > beta_fast): keep original freq (gamma = 1.0).
- Low-frequency dims (rotations < beta_slow): interpolate by 1/scale (gamma = 0.0).
- Mid-band dims: linear ramp gamma in [0, 1].
"""
half = d_head // 2
dim_idx = torch.arange(0, half, dtype=torch.float64)
base_inv_freq = 1.0 / (base ** (2.0 * dim_idx / d_head))
if scale <= 1.0:
return base_inv_freq.float(), 1.0
wavelengths = (2.0 * math.pi) / base_inv_freq
rotations = original_max_len / wavelengths # r_j = L_train / lambda_j
gamma = torch.clamp((rotations - beta_slow) / max(beta_fast - beta_slow, 1e-6), 0.0, 1.0)
yarn_inv_freq = (1.0 - gamma) * (base_inv_freq / scale) + gamma * base_inv_freq
mscale = 0.1 * math.log(scale) + 1.0
return yarn_inv_freq.float(), float(mscale)
class RotaryEmbedding(nn.Module):
"""Rotary Position Embedding (RoPE, Su et al. 2021) with optional YaRN scaling."""
cos_cached: torch.Tensor
sin_cached: torch.Tensor
def __init__(
self,
d_head: int,
max_seq_len: int = 2048,
base: float = 10000.0,
yarn_scale: float = 1.0,
original_max_len: int = 2048,
) -> None:
super().__init__()
if d_head % 2 != 0:
raise ValueError("RoPE requires even d_head.")
self.d_head = d_head
inv_freq, self.mscale = compute_yarn_inv_freq(
d_head=d_head,
base=base,
scale=yarn_scale,
original_max_len=original_max_len,
)
positions = torch.arange(max_seq_len, dtype=torch.float32)
freqs = torch.outer(positions, inv_freq) # (S, d_head / 2)
self.register_buffer("cos_cached", torch.cos(freqs), persistent=False)
self.register_buffer("sin_cached", torch.sin(freqs), persistent=False)
def apply_rotary(self, x: torch.Tensor, start_pos: int = 0) -> torch.Tensor:
"""Rotate pairs `(x_2j, x_{2j+1})` by position-dependent angle `m * theta_j`.
Args:
x: Tensor of shape `(B, H, S, d_head)`.
start_pos: Starting absolute token index for incremental decoding.
"""
seq_len = x.shape[-2]
cos = self.cos_cached[start_pos : start_pos + seq_len].unsqueeze(0).unsqueeze(0)
sin = self.sin_cached[start_pos : start_pos + seq_len].unsqueeze(0).unsqueeze(0)
x_even = x[..., 0::2]
x_odd = x[..., 1::2]
rot_even = x_even * cos - x_odd * sin
rot_odd = x_even * sin + x_odd * cos
return torch.stack((rot_even, rot_odd), dim=-1).flatten(-2)
class GQAAttention(nn.Module):
"""Grouped-Query Attention (also covering MHA & MQA) with RoPE and real incremental KV-Cache."""
def __init__(
self,
d_model: int,
n_q_heads: int,
n_kv_heads: int,
max_seq_len: int = 256,
rope_base: float = 10000.0,
) -> None:
super().__init__()
if d_model % n_q_heads != 0 or n_q_heads % n_kv_heads != 0:
raise ValueError("Invalid head dimensions for GQAAttention.")
self.d_model = d_model
self.n_q_heads = n_q_heads
self.n_kv_heads = n_kv_heads
self.d_head = d_model // n_q_heads
self.n_rep = n_q_heads // n_kv_heads
self.w_q = nn.Linear(d_model, n_q_heads * self.d_head, bias=False)
self.w_k = nn.Linear(d_model, n_kv_heads * self.d_head, bias=False)
self.w_v = nn.Linear(d_model, n_kv_heads * self.d_head, bias=False)
self.w_o = nn.Linear(n_q_heads * self.d_head, d_model, bias=False)
self.rope = RotaryEmbedding(self.d_head, max_seq_len=max_seq_len, base=rope_base)
def forward(
self,
x: torch.Tensor,
past_kv: tuple[torch.Tensor, torch.Tensor] | None = None,
use_cache: bool = False,
start_pos: int = 0,
) -> tuple[torch.Tensor, tuple[torch.Tensor, torch.Tensor] | None]:
bsz, seq_len, _ = x.shape
q = self.w_q(x).view(bsz, seq_len, self.n_q_heads, self.d_head).transpose(1, 2)
k = self.w_k(x).view(bsz, seq_len, self.n_kv_heads, self.d_head).transpose(1, 2)
v = self.w_v(x).view(bsz, seq_len, self.n_kv_heads, self.d_head).transpose(1, 2)
q = self.rope.apply_rotary(q, start_pos=start_pos)
k = self.rope.apply_rotary(k, start_pos=start_pos)
if past_kv is not None:
past_k, past_v = past_kv
k = torch.cat([past_k, k], dim=2)
v = torch.cat([past_v, v], dim=2)
present_kv = (k, v) if use_cache else None
# Expand KV heads to match Q heads via zero-copy repeat_interleave
k_exp = k.repeat_interleave(self.n_rep, dim=1) if self.n_rep > 1 else k
v_exp = v.repeat_interleave(self.n_rep, dim=1) if self.n_rep > 1 else v
total_len = k.shape[2]
scores = torch.matmul(q, k_exp.transpose(-2, -1)) / math.sqrt(self.d_head)
# Causal mask supporting both prefill (seq_len > 1) and incremental decode (seq_len == 1)
if seq_len > 1:
q_pos = torch.arange(start_pos, start_pos + seq_len, device=x.device)[:, None]
k_pos = torch.arange(total_len, device=x.device)[None, :]
causal_mask = k_pos > q_pos
scores = scores.masked_fill(causal_mask.unsqueeze(0).unsqueeze(0), float("-inf"))
probs = F.softmax(scores, dim=-1)
out = torch.matmul(probs, v_exp)
out = out.transpose(1, 2).contiguous().view(bsz, seq_len, self.d_model)
return self.w_o(out), present_kv
class MLAAttention(nn.Module):
"""DeepSeek-style Multi-head Latent Attention (MLA) with compressed latent KV + decoupled RoPE."""
def __init__(
self,
d_model: int,
n_heads: int,
d_nope: int,
d_rope: int,
d_c_latent: int,
max_seq_len: int = 256,
rope_base: float = 10000.0,
) -> None:
super().__init__()
self.d_model = d_model
self.n_heads = n_heads
self.d_nope = d_nope
self.d_rope = d_rope
self.d_head = d_nope + d_rope
self.d_c_latent = d_c_latent
# Query path split into content (nope) + positional (rope)
self.w_q_nope = nn.Linear(d_model, n_heads * d_nope, bias=False)
self.w_q_rope = nn.Linear(d_model, n_heads * d_rope, bias=False)
# Compressed joint KV latent c_t^{KV} in R^{d_c} + shared decoupled RoPE key k_t^R in R^{d_rope}
self.w_dkv = nn.Linear(d_model, d_c_latent, bias=False)
self.w_uk = nn.Linear(d_c_latent, n_heads * d_nope, bias=False)
self.w_uv = nn.Linear(d_c_latent, n_heads * d_nope, bias=False)
self.w_kr = nn.Linear(d_model, d_rope, bias=False)
self.w_o = nn.Linear(n_heads * d_nope, d_model, bias=False)
self.rope = RotaryEmbedding(d_rope, max_seq_len=max_seq_len, base=rope_base)
def forward(
self,
x: torch.Tensor,
past_latent: tuple[torch.Tensor, torch.Tensor] | None = None,
use_cache: bool = False,
start_pos: int = 0,
) -> tuple[torch.Tensor, tuple[torch.Tensor, torch.Tensor] | None]:
bsz, seq_len, _ = x.shape
q_nope = self.w_q_nope(x).view(bsz, seq_len, self.n_heads, self.d_nope).transpose(1, 2)
q_rope = self.w_q_rope(x).view(bsz, seq_len, self.n_heads, self.d_rope).transpose(1, 2)
q_rope = self.rope.apply_rotary(q_rope, start_pos=start_pos)
# Compress K,V into low-rank latent c_kv (B, S, d_c) and shared RoPE key (B, 1, S, d_rope)
c_kv = self.w_dkv(x)
k_rope = self.w_kr(x).unsqueeze(1) # (B, 1, S, d_rope)
k_rope = self.rope.apply_rotary(k_rope, start_pos=start_pos)
if past_latent is not None:
past_c_kv, past_k_rope = past_latent
c_kv = torch.cat([past_c_kv, c_kv], dim=1)
k_rope = torch.cat([past_k_rope, k_rope], dim=2)
present_latent = (c_kv, k_rope) if use_cache else None
total_len = c_kv.shape[1]
k_nope = self.w_uk(c_kv).view(bsz, total_len, self.n_heads, self.d_nope).transpose(1, 2)
v = self.w_uv(c_kv).view(bsz, total_len, self.n_heads, self.d_nope).transpose(1, 2)
k_rope_exp = k_rope.expand(bsz, self.n_heads, total_len, self.d_rope)
q = torch.cat([q_nope, q_rope], dim=-1)
k = torch.cat([k_nope, k_rope_exp], dim=-1)
scores = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(self.d_head)
if seq_len > 1:
q_pos = torch.arange(start_pos, start_pos + seq_len, device=x.device)[:, None]
k_pos = torch.arange(total_len, device=x.device)[None, :]
scores = scores.masked_fill((k_pos > q_pos).unsqueeze(0).unsqueeze(0), float("-inf"))
probs = F.softmax(scores, dim=-1)
out = torch.matmul(probs, v)
out = out.transpose(1, 2).contiguous().view(bsz, seq_len, self.n_heads * self.d_nope)
return self.w_o(out), present_latent
class SparseMoELayer(nn.Module):
"""Sparse Mixture-of-Experts FFN with Top-k routing, aux load-balancing loss & DeepSeek bias."""
router_bias: torch.Tensor
def __init__(
self,
d_model: int,
d_ff_expert: int,
num_experts: int = 8,
top_k: int = 2,
aux_weight: float = 0.01,
) -> None:
super().__init__()
self.d_model = d_model
self.d_ff_expert = d_ff_expert
self.num_experts = num_experts
self.top_k = top_k
self.aux_weight = aux_weight
self.router = nn.Linear(d_model, num_experts, bias=False)
self.experts = nn.ModuleList([SwiGLU(d_model, d_ff_expert) for _ in range(num_experts)])
self.register_buffer("router_bias", torch.zeros(num_experts))
def parameter_accounting(self) -> dict[str, int | float]:
"""Return exact total vs active parameters per token."""
router_params = sum(p.numel() for p in self.router.parameters())
expert_params_each = sum(p.numel() for p in self.experts[0].parameters())
total_params = router_params + self.num_experts * expert_params_each
active_params = router_params + self.top_k * expert_params_each
return {
"total_params": total_params,
"active_params": active_params,
"active_ratio": active_params / max(total_params, 1),
"num_experts": self.num_experts,
"top_k": self.top_k,
}
def forward(self, x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, dict[str, Any]]:
bsz, seq_len, dim = x.shape
x_flat = x.reshape(-1, dim)
n_tokens = x_flat.shape[0]
raw_logits = self.router(x_flat)
probs = F.softmax(raw_logits, dim=-1) # (T, E)
# DeepSeek-V3 style bias affects Top-k selection without distorting gating weights
selection_scores = probs + self.router_bias.unsqueeze(0)
_, topk_idx = torch.topk(selection_scores, k=self.top_k, dim=-1) # (T, k)
topk_probs = torch.gather(probs, dim=-1, index=topk_idx)
topk_weights = topk_probs / torch.clamp(topk_probs.sum(dim=-1, keepdim=True), min=1e-9)
# Switch / Mixtral load-balancing auxiliary loss: alpha * E * sum(f_e * P_e)
one_hot = F.one_hot(topk_idx, num_classes=self.num_experts).float() # (T, k, E)
expert_counts = one_hot.sum(dim=(0, 1)) # total assignments per expert
f_e = expert_counts / float(max(n_tokens * self.top_k, 1))
p_e = probs.mean(dim=0)
aux_loss = self.aux_weight * float(self.num_experts) * torch.sum(f_e * p_e)
out_flat = torch.zeros_like(x_flat)
for e_idx, expert in enumerate(self.experts):
mask_e = topk_idx == e_idx # (T, k)
if not bool(mask_e.any()):
continue
tok_pos, slot_pos = torch.where(mask_e)
expert_out = expert(x_flat[tok_pos])
w_e = topk_weights[tok_pos, slot_pos].unsqueeze(-1)
out_flat.index_add_(0, tok_pos, expert_out * w_e)
counts_np = expert_counts.detach().cpu().numpy()
mean_cnt = float(np.mean(counts_np))
cv_load = float(np.std(counts_np) / max(mean_cnt, 1e-9))
stats = {
"expert_counts": [int(c) for c in counts_np.tolist()],
"load_cv": cv_load,
"max_expert_share": float(np.max(counts_np) / max(float(np.sum(counts_np)), 1.0)),
"dead_experts": int(np.sum(counts_np == 0)),
"aux_loss_val": float(aux_loss.detach().cpu().item()),
}
return out_flat.view(bsz, seq_len, dim), aux_loss, stats
class ModernTransformerBlock(nn.Module):
"""Pre-Norm Modern Transformer Block: RMSNorm + RoPE GQA + SwiGLU (or Sparse MoE)."""
def __init__(self, cfg: ModernLLMConfig) -> None:
super().__init__()
self.use_moe = cfg.use_moe
self.attn_norm = RMSNorm(cfg.d_model)
self.attn = GQAAttention(
d_model=cfg.d_model,
n_q_heads=cfg.n_q_heads,
n_kv_heads=cfg.n_kv_heads,
max_seq_len=cfg.max_seq_len,
rope_base=cfg.rope_base,
)
self.ffn_norm = RMSNorm(cfg.d_model)
if cfg.use_moe:
self.ffn: nn.Module = SparseMoELayer(
d_model=cfg.d_model,
d_ff_expert=cfg.d_ff,
num_experts=cfg.num_experts,
top_k=cfg.top_k_experts,
aux_weight=cfg.moe_aux_weight,
)
else:
self.ffn = SwiGLU(cfg.d_model, cfg.d_ff)
def forward(
self,
x: torch.Tensor,
past_kv: tuple[torch.Tensor, torch.Tensor] | None = None,
use_cache: bool = False,
start_pos: int = 0,
) -> tuple[torch.Tensor, tuple[torch.Tensor, torch.Tensor] | None, torch.Tensor]:
attn_out, present_kv = self.attn(
self.attn_norm(x), past_kv=past_kv, use_cache=use_cache, start_pos=start_pos
)
h = x + attn_out
if self.use_moe:
assert isinstance(self.ffn, SparseMoELayer)
ffn_out, aux_loss, _ = self.ffn(self.ffn_norm(h))
else:
ffn_out = self.ffn(self.ffn_norm(h))
aux_loss = torch.zeros((), dtype=x.dtype, device=x.device)
return h + ffn_out, present_kv, aux_loss
class ModernTransformerLM(nn.Module):
"""Runnable Modern 2026 Decoder-Only Language Model with KV-Cache & Safetensors I/O."""
def __init__(self, cfg: ModernLLMConfig) -> None:
super().__init__()
self.cfg = cfg
self.tok_emb = nn.Embedding(cfg.vocab_size, cfg.d_model)
self.layers = nn.ModuleList([ModernTransformerBlock(cfg) for _ in range(cfg.n_layers)])
self.final_norm = RMSNorm(cfg.d_model)
self.lm_head = nn.Linear(cfg.d_model, cfg.vocab_size, bias=False)
def forward(
self,
input_ids: torch.Tensor,
past_kvs: list[tuple[torch.Tensor, torch.Tensor]] | None = None,
use_cache: bool = False,
start_pos: int = 0,
return_hidden: bool = False,
) -> dict[str, Any]:
h = self.tok_emb(input_ids)
next_kvs: list[tuple[torch.Tensor, torch.Tensor]] = []
total_aux = torch.zeros((), dtype=h.dtype, device=h.device)
for idx, layer in enumerate(self.layers):
past = past_kvs[idx] if past_kvs is not None else None
h, present, aux = layer(h, past_kv=past, use_cache=use_cache, start_pos=start_pos)
total_aux = total_aux + aux
if use_cache and present is not None:
next_kvs.append(present)
h = self.final_norm(h)
logits = self.lm_head(h)
result: dict[str, Any] = {
"logits": logits,
"aux_loss": total_aux,
"past_kvs": next_kvs if use_cache else None,
}
if return_hidden:
result["hidden_states"] = h
return result
def save_safetensors_checkpoint(model: nn.Module, path: str | Path) -> Path:
"""Persist model tensors safely via safetensors (zero pickle)."""
target = Path(path)
target.parent.mkdir(parents=True, exist_ok=True)
state = {k: v.detach().cpu().contiguous() for k, v in model.state_dict().items()}
safetensors_save_file(state, str(target))
return target
def load_safetensors_checkpoint(model: nn.Module, path: str | Path) -> None:
"""Restore model tensors safely via safetensors."""
loaded = safetensors_load_file(str(path))
model.load_state_dict(loaded, strict=True)
# ---------------------------------------------------------------------------
# Tier 2 Controlled Audits & Full WB-Ch19 Benchmark Suite
# ---------------------------------------------------------------------------
def audit_rope_invariance_and_yarn(seed: int = 42) -> dict[str, Any]:
"""Verify exact RoPE relative-position dot-product invariance and YaRN frequency bands."""
torch.manual_seed(seed)
d_head = 64
rope = RotaryEmbedding(d_head=d_head, max_seq_len=256, base=10000.0)
q = torch.randn(1, 1, 1, d_head)
k = torch.randn(1, 1, 1, d_head)
m, n, delta = 7, 19, 43
q_m = rope.apply_rotary(q, start_pos=m)
k_n = rope.apply_rotary(k, start_pos=n)
q_md = rope.apply_rotary(q, start_pos=m + delta)
k_nd = rope.apply_rotary(k, start_pos=n + delta)
dot_orig = float((q_m * k_n).sum().item())
dot_shifted = float((q_md * k_nd).sum().item())
rel_pos_abs_diff = abs(dot_orig - dot_shifted)
# Verify YaRN 8x extension (4K -> 32K) preserves high-freq and scales low-freq
base_inv, mscale_1 = compute_yarn_inv_freq(d_head=64, base=10000.0, scale=1.0, original_max_len=4096)
yarn_inv, mscale_8 = compute_yarn_inv_freq(d_head=64, base=10000.0, scale=8.0, original_max_len=4096)
high_freq_ratio = float((yarn_inv[0] / base_inv[0]).item())
low_freq_ratio = float((yarn_inv[-1] / base_inv[-1]).item())
return {
"d_head": d_head,
"m": m,
"n": n,
"delta": delta,
"dot_orig": dot_orig,
"dot_shifted": dot_shifted,
"relative_pos_abs_diff": rel_pos_abs_diff,
"yarn_scale": 8.0,
"yarn_high_freq_ratio": high_freq_ratio,
"yarn_low_freq_ratio": low_freq_ratio,
"yarn_mscale_1x": mscale_1,
"yarn_mscale_8x": mscale_8,
}
def audit_gqa_kv_cache_parity(seed: int = 42) -> dict[str, Any]:
"""Verify GQA incremental KV-Cache decode matches full prefill to < 1e-5 and cuts step FLOPs."""
torch.manual_seed(seed)
cfg = ModernLLMConfig(
vocab_size=64,
d_model=64,
n_layers=2,
n_q_heads=8,
n_kv_heads=2,
d_ff=176,
max_seq_len=64,
)
model = ModernTransformerLM(cfg).eval()
total_len = 24
prefill_len = 16
tokens = torch.randint(0, cfg.vocab_size, (1, total_len))
with torch.inference_mode():
full_out = model(tokens, use_cache=False)["logits"]
prefill_res = model(tokens[:, :prefill_len], use_cache=True, start_pos=0)
past_kvs = prefill_res["past_kvs"]
step_logits = [prefill_res["logits"]]
for pos in range(prefill_len, total_len):
step_res = model(tokens[:, pos : pos + 1], past_kvs=past_kvs, use_cache=True, start_pos=pos)
past_kvs = step_res["past_kvs"]
step_logits.append(step_res["logits"])
cached_out = torch.cat(step_logits, dim=1)
max_abs_diff = float((full_out - cached_out).abs().max().item())
# Analytical FLOPs comparison for decoding 64 tokens after 2048-token prompt
prompt_len, gen_steps = 2048, 64
d_m = 4096
uncached_ops = sum(2 * t * d_m * d_m + 2 * t * t * d_m for t in range(prompt_len, prompt_len + gen_steps))
cached_ops = sum(2 * 1 * d_m * d_m + 2 * t * d_m for t in range(prompt_len, prompt_len + gen_steps))
return {
"total_len": total_len,
"prefill_len": prefill_len,
"decode_steps": total_len - prefill_len,
"max_abs_diff": max_abs_diff,
"cached_kv_shape": list(past_kvs[0][0].shape),
"decode_flops_speedup_2048_ctx": float(uncached_ops / max(cached_ops, 1)),
}
def audit_mla_latent_cache_compression(seed: int = 42) -> dict[str, Any]:
"""Verify MLAAttention incremental compressed latent cache parity and byte compression."""
torch.manual_seed(seed)
d_model, n_heads, d_nope, d_rope, d_c = 128, 8, 16, 8, 24
mla = MLAAttention(
d_model=d_model,
n_heads=n_heads,
d_nope=d_nope,
d_rope=d_rope,
d_c_latent=d_c,
max_seq_len=64,
).eval()
x = torch.randn(1, 20, d_model)
with torch.inference_mode():
full_out, _ = mla(x, use_cache=False, start_pos=0)
pre_out, latent = mla(x[:, :12], use_cache=True, start_pos=0)
parts = [pre_out]
for pos in range(12, 20):
s_out, latent = mla(x[:, pos : pos + 1], past_latent=latent, use_cache=True, start_pos=pos)
parts.append(s_out)
cached_out = torch.cat(parts, dim=1)
assert latent is not None
max_abs_diff = float((full_out - cached_out).abs().max().item())
mha_elems_per_tok = 2 * n_heads * (d_nope + d_rope)
mla_elems_per_tok = d_c + d_rope
return {
"max_abs_diff": max_abs_diff,
"mha_elems_per_tok": mha_elems_per_tok,
"mla_elems_per_tok": mla_elems_per_tok,
"toy_compression_ratio": float(mha_elems_per_tok / mla_elems_per_tok),
"latent_cache_shape": list(latent[0].shape),
"rope_cache_shape": list(latent[1].shape),
}
def audit_moe_router_collapse_vs_balanced(seed: int = 42) -> dict[str, Any]:
"""Demonstrate Sparse MoE router collapse vs balanced routing + active param ratio."""
torch.manual_seed(seed)
moe = SparseMoELayer(d_model=64, d_ff_expert=128, num_experts=8, top_k=2, aux_weight=0.01)
x = torch.randn(4, 32, 64) # 128 tokens
# 1. Collapsed router: strong logit skew toward expert 0 and 1
with torch.no_grad():
moe.router.weight.zero_()
moe.router.weight[0] = 0.8
moe.router.weight[1] = 0.4
moe.router_bias.zero_()
moe.router_bias[0] = 6.0
moe.router_bias[1] = 5.5
_, _, collapsed_stats = moe(x)
# 2. Balanced router (orthogonal random init + DeepSeek auxiliary-loss-free bias update loop)
torch.manual_seed(seed + 1)
nn.init.normal_(moe.router.weight, mean=0.0, std=0.2)
with torch.no_grad():
moe.router_bias.zero_()
# 12 lightweight DeepSeek-V3 bias-update iterations balancing load without distorting weights
for _ in range(12):
_, _, st = moe(x)
counts = torch.tensor(st["expert_counts"], dtype=torch.float32)
target = counts.mean()
moe.router_bias += 0.05 * torch.sign(target - counts)
_, _, balanced_stats = moe(x)
acct = moe.parameter_accounting()
return {
"param_accounting": acct,
"collapsed": collapsed_stats,
"balanced": balanced_stats,
}
def audit_contextual_embeddings_shift(seed: int = 42) -> dict[str, Any]:
"""Show static embedding cosine = 1.0 vs contextual hidden-state separation across contexts."""
torch.manual_seed(seed)
cfg = ModernLLMConfig(vocab_size=64, d_model=64, n_layers=4, n_q_heads=8, n_kv_heads=2, d_ff=176)
model = ModernTransformerLM(cfg).eval()
# Realistic LLM embedding scale (std=0.25) so attention mixes context into residual stream
nn.init.normal_(model.tok_emb.weight, mean=0.0, std=0.25)
# Same target token id `7` ("bank") placed in two contrasting 8-token contexts (river vs finance)
ctx_a = torch.tensor([[2, 5, 9, 14, 18, 21, 25, 29, 7]], dtype=torch.long)
ctx_b = torch.tensor([[31, 35, 42, 46, 50, 53, 57, 60, 7]], dtype=torch.long)
with torch.inference_mode():
static_a = model.tok_emb(ctx_a)[0, -1]
static_b = model.tok_emb(ctx_b)[0, -1]
h_a = model(ctx_a, return_hidden=True)["hidden_states"][0, -1]
h_b = model(ctx_b, return_hidden=True)["hidden_states"][0, -1]
static_cos = float(F.cosine_similarity(static_a.unsqueeze(0), static_b.unsqueeze(0)).item())
ctx_cos = float(F.cosine_similarity(h_a.unsqueeze(0), h_b.unsqueeze(0)).item())
return {
"target_token_id": 7,
"static_embedding_cosine": static_cos,
"contextual_hidden_cosine": ctx_cos,
"contextual_shift_delta": static_cos - ctx_cos,
}
def run_full_ch19_wb19_benchmarks(seed: int = 42, quick: bool = False) -> dict[str, Any]:
"""Execute full Tier 1 + Tier 2 WB-Ch19 benchmark suite and emit `workbench_panels`."""
rng = np.random.default_rng(seed)
# 1. Classical Attention + 1/sqrt(d_k) Variance Audit
var_cfg = AttentionBenchmarkConfig(
d_k_values=(16, 64, 128, 256),
seq_len=32,
num_trials=24 if quick else 64,
seed=seed,
)
var_audit = audit_scaled_dot_product_variance(var_cfg)
d128 = [r for r in var_audit["by_d_k"] if r["d_k"] == 128][0]
# Classical Bahdanau vs Luong sanity check
enc_h = rng.standard_normal((12, 16))
dec_s = rng.standard_normal((16,))
_, w_bah = bahdanau_additive_attention(
dec_s, enc_h, rng.standard_normal((12, 16)), rng.standard_normal((12, 16)), rng.standard_normal((12,))
)
_, w_luo = luong_multiplicative_attention(dec_s, enc_h)
# 2. FlashAttention Exact Parity & HBM Traffic Scaling
n_flash = 64 if quick else 128
q_f = rng.standard_normal((n_flash, 64))
k_f = rng.standard_normal((n_flash, 64))
v_f = rng.standard_normal((n_flash, 64))
naive_out, _ = naive_scaled_dot_product_attention(q_f, k_f, v_f, causal=True)
flash_out, flash_stats = flash_attention_tiled_forward(q_f, k_f, v_f, block_r=16, block_c=16, causal=True)
flash_max_diff = float(np.max(np.abs(naive_out - flash_out)))
hbm_8k = compute_attention_hbm_traffic(
FlashTilingConfig(seq_len=8192, d_head=128, num_heads=32, block_r=128, block_c=64, causal=True)
)
hbm_32k = compute_attention_hbm_traffic(
FlashTilingConfig(seq_len=32768, d_head=128, num_heads=32, block_r=128, block_c=64, causal=True)
)
# 3. KV-Cache Scaling (MHA vs GQA vs MQA vs MLA)
kv_scaling = benchmark_kv_cache_scaling()
kv_70b_128k = kv_scaling["70B_llama3_class"]["131072"]
kv_671b_128k = kv_scaling["671B_deepseek_v3_class"]["131072"]
# 4. Decoding (Beam vs Greedy, Min-p vs Top-p, FSM JSON 100% Validity)
def _toy_branching_logits(seq: list[int]) -> np.ndarray:
# Step 1 prefers token 1 slightly (0.55) over token 2 (0.45),
# but after token 2, token 3 has prob ~0.95 whereas after token 1 all tokens are flat -> Beam wins!
if len(seq) == 1:
return np.array([-3.0, 1.1, 0.9, -2.0])
if seq[-1] == 1:
return np.array([0.1, 0.1, 0.1, 0.1])
return np.array([3.5, -2.0, -2.0, -2.0])
greedy_seq, greedy_lp = decode_greedy(_toy_branching_logits, [0], max_steps=2, eos_id=0)
beam_seq, beam_lp, beam_score = decode_beam_search(
_toy_branching_logits, [0], beam_width=3, max_steps=2, eos_id=0, length_penalty=0.7
)
minp_audit = audit_min_p_vs_top_p_entropy(seed=seed)
fsm_audit = benchmark_fsm_json_decoding(num_trials=30 if quick else 60, seed=seed)
# 5. Tier 2 PyTorch Audits: RoPE+YaRN, GQA/MLA Cache, Sparse MoE, Contextual, Safetensors
rope_audit = audit_rope_invariance_and_yarn(seed=seed)
gqa_parity = audit_gqa_kv_cache_parity(seed=seed)
mla_parity = audit_mla_latent_cache_compression(seed=seed)
moe_audit = audit_moe_router_collapse_vs_balanced(seed=seed)
ctx_audit = audit_contextual_embeddings_shift(seed=seed)
# ModernTransformerLM + Safetensors round-trip check
torch.manual_seed(seed)
lm_cfg = ModernLLMConfig(
vocab_size=64, d_model=64, n_layers=2, n_q_heads=8, n_kv_heads=2, d_ff=176, use_moe=True
)
lm_a = ModernTransformerLM(lm_cfg).eval()
lm_b = ModernTransformerLM(lm_cfg).eval()
sample_ids = torch.randint(0, 64, (2, 12))
with tempfile.TemporaryDirectory() as tmpdir:
ckpt_path = Path(tmpdir) / "modern_lm.safetensors"
save_safetensors_checkpoint(lm_a, ckpt_path)
load_safetensors_checkpoint(lm_b, ckpt_path)
with torch.inference_mode():
st_diff = float((lm_a(sample_ids)["logits"] - lm_b(sample_ids)["logits"]).abs().max().item())
# Pre-formatted strings keeping line lengths clean
moe_active_pct = 100.0 * moe_audit["param_accounting"]["active_ratio"]
col_cv = moe_audit["collapsed"]["load_cv"]
bal_cv = moe_audit["balanced"]["load_cv"]
col_dead = moe_audit["collapsed"]["dead_experts"]
bal_dead = moe_audit["balanced"]["dead_experts"]
col_share = 100.0 * moe_audit["collapsed"]["max_expert_share"]
bal_share = 100.0 * moe_audit["balanced"]["max_expert_share"]
mp_low = minp_audit["confident_low_entropy"]
mp_high = minp_audit["uncertain_high_entropy"]
kv_7b_128k = kv_scaling["7B_class"]["131072"]
# 6. Standardized Workbench Panels (6 KPIs, 4 Bars, 4 Tables)
workbench_panels = {
"kpis": [
{
"id": "kpi_scaled_attn_variance",
"label": "Scaled Dot-Product (d_k=128) Var & Entropy",
"value": f"{d128['scaled_var']:.2f}",
"unit": f"(unscaled {d128['unscaled_var']:.1f})",
"status": "ok",
"detail": (
f"1/sqrt(d_k) restores Var ~1.0 and keeps {d128['entropy_retention_pct']:.1f}% "
f"entropy vs {d128['unscaled_entropy_pct']:.1f}% unscaled collapse."
),
},
{
"id": "kpi_rope_yarn_invariance",
"label": "RoPE Relative-Pos Error & YaRN 8x",
"value": f"{rope_audit['relative_pos_abs_diff']:.2e}",
"unit": f"(mscale {rope_audit['yarn_mscale_8x']:.2f})",
"status": "ok",
"detail": (
"Exact rotation invariance <q_m, k_n> = <q_(m+d), k_(n+d)>; "
f"YaRN keeps high-freq={rope_audit['yarn_high_freq_ratio']:.2f} "
f"and scales low-freq={rope_audit['yarn_low_freq_ratio']:.3f}."
),
},
{
"id": "kpi_flash_attention_parity",
"label": "FlashAttention Parity & 32K HBM Cut",
"value": f"{flash_max_diff:.2e}",
"unit": f"(-{hbm_32k['hbm_reduction_pct']:.1f}% HBM)",
"status": "ok",
"detail": (
f"Online Safe Softmax matches naive O(N^2) to {flash_max_diff:.2e}; "
f"32K HBM drops {hbm_32k['naive_hbm_mb']:.0f}MB -> {hbm_32k['flash_hbm_mb']:.0f}MB "
f"({hbm_32k['hbm_reduction_factor']:.1f}x)."
),
},
{
"id": "kpi_kv_cache_mla_compression",
"label": "KV-Cache Compression (671B @ 128K bf16)",
"value": f"{kv_671b_128k['mla_bf16_gb']:.2f} GB",
"unit": f"({kv_671b_128k['mla_vs_mha_compression']:.1f}x vs MHA)",
"status": "ok",
"detail": (
f"DeepSeek MLA cuts 671B 128K KV from {kv_671b_128k['mha_bf16_gb']:.0f} GB "
f"to {kv_671b_128k['mla_bf16_gb']:.2f} GB; GQA 8:1 cuts 70B 128K "
f"{kv_70b_128k['mha_bf16_gb']:.1f} -> {kv_70b_128k['gqa_bf16_gb']:.1f} GB."
),
},
{
"id": "kpi_sparse_moe_balance",
"label": "Sparse MoE Load CV & Active Params",
"value": f"CV {bal_cv:.2f}",
"unit": f"(collapsed {col_cv:.2f})",
"status": "ok",
"detail": (
f"Top-2/8 MoE activates {moe_active_pct:.1f}% params; "
f"bias balancing cuts dead experts {col_dead} -> {bal_dead}."
),
},
{
"id": "kpi_fsm_json_validity",
"label": "FSM Grammar-Constrained JSON Validity",
"value": f"{100.0 * fsm_audit['fsm_valid_rate']:.1f}%",
"unit": f"(naive {100.0 * fsm_audit['unconstrained_valid_rate']:.1f}%)",
"status": "ok",
"detail": (
f"Logit masking (-inf) yields {fsm_audit['fsm_valid_count']}/"
f"{fsm_audit['num_trials']} schema-valid JSON vs "
f"{fsm_audit['unconstrained_valid_count']} unconstrained."
),
},
],
"bars": [
{
"id": "bar_kv_cache_70b_128k",
"title": "70B-Class LLM KV-Cache at 128K Context (bf16 GB, Lower is Better)",
"metric_label": "VRAM (GB)",
"items": [
{
"label": "MHA (64 kv)",
"value": kv_70b_128k["mha_bf16_gb"],
"display": f"{kv_70b_128k['mha_bf16_gb']:.1f} GB (OOM 4x H100)",
"css_class": "is-slow",
},
{
"label": "GQA 8:1 (Llama-3)",
"value": kv_70b_128k["gqa_bf16_gb"],
"display": f"{kv_70b_128k['gqa_bf16_gb']:.2f} GB (8.0x cut)",
"css_class": "is-mid",
},
{
"label": "MLA (bf16)",
"value": kv_70b_128k["mla_bf16_gb"],
"display": (
f"{kv_70b_128k['mla_bf16_gb']:.2f} GB "
f"({kv_70b_128k['mla_vs_mha_compression']:.1f}x)"
),
"css_class": "is-fast",
},
{
"label": "MLA (fp8)",
"value": kv_70b_128k["mla_fp8_gb"],
"display": f"{kv_70b_128k['mla_fp8_gb']:.2f} GB (half bf16)",
"css_class": "is-fast",
},
],
},
{
"id": "bar_flash_hbm_traffic_32k",
"title": "Attention HBM Memory Traffic & Peak Act at N=32K (GB, Lower is Better)",
"metric_label": "Memory (GB)",
"items": [
{
"label": "Naive HBM Traffic",
"value": hbm_32k["naive_hbm_mb"] / 1000.0,
"display": f"{hbm_32k['naive_hbm_mb'] / 1000.0:.1f} GB (O(N^2))",
"css_class": "is-slow",
},
{
"label": "FlashAttn HBM Traffic",
"value": hbm_32k["flash_hbm_mb"] / 1000.0,
"display": (
f"{hbm_32k['flash_hbm_mb'] / 1000.0:.2f} GB "
f"(-{hbm_32k['hbm_reduction_pct']:.1f}%)"
),
"css_class": "is-fast",
},
{
"label": "Naive Peak S+P Act",
"value": hbm_32k["naive_peak_act_mb"] / 1000.0,
"display": f"{hbm_32k['naive_peak_act_mb'] / 1000.0:.1f} GB",
"css_class": "is-slow",
},
{
"label": "Flash Peak LSE Act",
"value": hbm_32k["flash_peak_act_mb"] / 1000.0,
"display": f"{hbm_32k['flash_peak_act_mb']:.1f} MB (O(N))",
"css_class": "is-fast",
},
],
},
{
"id": "bar_moe_router_balance",
"title": "Sparse MoE (Top-2/8) Router Load Balance Metrics (Lower is Better)",
"metric_label": "Imbalance / Share",
"items": [
{
"label": "Collapsed CV",
"value": col_cv,
"display": f"CV={col_cv:.2f} ({col_dead} dead)",
"css_class": "is-slow",
},
{
"label": "Balanced CV",
"value": bal_cv,
"display": f"CV={bal_cv:.2f} ({bal_dead} dead)",
"css_class": "is-fast",
},
{
"label": "Collapsed Max Share",
"value": moe_audit["collapsed"]["max_expert_share"],
"display": f"{col_share:.1f}% single expert",
"css_class": "is-slow",
},
{
"label": "Balanced Max Share",
"value": moe_audit["balanced"]["max_expert_share"],
"display": f"{bal_share:.1f}% (ideal 12.5%)",
"css_class": "is-fast",
},
],
},
{
"id": "bar_minp_vs_topp_tail_leak",
"title": "Confident Regime (T=1.5) Noise-Tail Leakage & Active Tokens",
"metric_label": "Active Tokens",
"items": [
{
"label": "Top-k (k=10)",
"value": float(mp_low["top_k_10_active"]),
"display": (
f"{mp_low['top_k_10_active']} toks "
f"(leak {100.0 * mp_low['top_k_10_tail_leak_prob']:.1f}%)"
),
"css_class": "is-mid",
},
{
"label": "Top-p (p=0.95)",
"value": float(mp_low["top_p_095_active"]),
"display": (
f"{mp_low['top_p_095_active']} toks "
f"(leak {100.0 * mp_low['top_p_095_tail_leak_prob']:.1f}%)"
),
"css_class": "is-slow",
},
{
"label": "Min-p (0.10) Low-H",
"value": float(mp_low["min_p_010_active"]),
"display": (
f"{mp_low['min_p_010_active']} toks "
f"(leak {100.0 * mp_low['min_p_010_tail_leak_prob']:.1f}%)"
),
"css_class": "is-fast",
},
{
"label": "Min-p (0.10) High-H",
"value": float(mp_high["min_p_010_active"]),
"display": f"{mp_high['min_p_010_active']} toks (adaptive)",
"css_class": "is-fast",
},
],
},
],
"tables": [
{
"id": "tbl_scaled_dot_product_variance",
"title": "1/sqrt(d_k) Variance Stabilization & Softmax Entropy Preservation",
"columns": ["d_k", "Unscaled Var", "Scaled Var", "Entropy (Raw vs Scaled)"],
"rows": [
[
str(r["d_k"]),
f"{r['unscaled_var']:.1f}",
f"{r['scaled_var']:.2f}",
f"{r['unscaled_entropy']:.2f} vs {r['scaled_entropy']:.2f}",
]
for r in var_audit["by_d_k"]
],
},
{
"id": "tbl_kv_cache_architecture_matrix",
"title": "KV-Cache Footprint at 128K Context (bf16 GB): MHA vs GQA vs MQA vs MLA",
"columns": ["Model Class (128K)", "MHA (GB)", "GQA 8:1 (GB)", "MLA bf16 (GB) & Ratio"],
"rows": [
[
"7B (L=32, H=32)",
f"{kv_7b_128k['mha_bf16_gb']:.2f}",
f"{kv_7b_128k['gqa_bf16_gb']:.2f}",
f"{kv_7b_128k['mla_bf16_gb']:.2f} ({kv_7b_128k['mla_vs_mha_compression']:.1f}x)",
],
[
"70B Llama-3 (L=80, H=64)",
f"{kv_70b_128k['mha_bf16_gb']:.2f}",
f"{kv_70b_128k['gqa_bf16_gb']:.2f}",
f"{kv_70b_128k['mla_bf16_gb']:.2f} ({kv_70b_128k['mla_vs_mha_compression']:.1f}x)",
],
[
"671B DeepSeek-V3 (L=61, H=128)",
f"{kv_671b_128k['mha_bf16_gb']:.2f}",
f"{kv_671b_128k['gqa_bf16_gb']:.2f}",
f"{kv_671b_128k['mla_bf16_gb']:.2f} ({kv_671b_128k['mla_vs_mha_compression']:.1f}x)",
],
],
},
{
"id": "tbl_flash_and_pytorch_parity",
"title": "Numerical Parity: FlashAttention, RoPE, GQA/MLA Cache & Safetensors",
"columns": ["Audit Check", "Measured Error", "Target Bound", "Status"],
"rows": [
["FlashAttention vs Naive O(N^2)", f"{flash_max_diff:.2e}", "< 1e-5", "EXACT PASS"],
[
"RoPE Relative-Pos Invariance",
f"{rope_audit['relative_pos_abs_diff']:.2e}",
"< 1e-5",
"EXACT PASS",
],
[
"GQA Incremental KV-Cache",
f"{gqa_parity['max_abs_diff']:.2e}",
"< 1e-5",
"EXACT PASS",
],
[
"MLA Latent KV-Cache",
f"{mla_parity['max_abs_diff']:.2e}",
"< 1e-5",
"EXACT PASS",
],
["Safetensors Round-Trip", f"{st_diff:.2e}", "== 0.0", "EXACT PASS"],
],
},
{
"id": "tbl_decoding_and_fsm_audit",
"title": "Decoding Engine Audit: Beam Search, Min-p Adaptivity & FSM JSON Reliability",
"columns": ["Decoding Mechanism", "Observed Outcome", "Comparison / Baseline", "Verdict"],
"rows": [
[
"Beam Search (B=3, alpha=0.7)",
f"logp={beam_lp:.3f} (seq {beam_seq})",
f"Greedy logp={greedy_lp:.3f} (seq {greedy_seq})",
"BEAM WINS GLOBAL",
],
[
"Min-p (0.10) Low-Entropy (T=1.5)",
f"{mp_low['min_p_010_active']} active toks",
f"Top-p(0.95): {mp_low['top_p_095_active']} toks",
"ZERO TAIL LEAK",
],
[
"FSM JSON Logit Masking",
f"{fsm_audit['fsm_valid_count']}/{fsm_audit['num_trials']} valid (100%)",
f"Naive: {fsm_audit['unconstrained_valid_count']}/{fsm_audit['num_trials']}",
"100% SCHEMA SAFE",
],
[
"Contextual Embedding Shift",
f"ctx_cos={ctx_audit['contextual_hidden_cosine']:.3f}",
f"static_cos={ctx_audit['static_embedding_cosine']:.3f}",
"POLYSEMY RESOLVED",
],
],
},
],
}
return {
"config": {
"seed": seed,
"quick": quick,
"torch_version": torch.__version__,
"device": "cpu",
"output": "artifacts/ch19_wb19_results.json",
},
"workbench_panels": workbench_panels,
"attention_and_flash": {
"classical_attention_weight_sums": {
"bahdanau_sum": float(np.sum(w_bah)),
"luong_sum": float(np.sum(w_luo)),
},
"scaled_dot_product_variance": var_audit,
"flash_attention_parity": {
"max_abs_diff": flash_max_diff,
"stats": flash_stats,
},
"hbm_traffic_8k": hbm_8k,
"hbm_traffic_32k": hbm_32k,
},
"kv_cache_and_decoding": {
"kv_cache_scaling": kv_scaling,
"beam_vs_greedy": {
"greedy_seq": greedy_seq,
"greedy_log_prob": greedy_lp,
"beam_seq": beam_seq,
"beam_log_prob": beam_lp,
"beam_norm_score": beam_score,
},
"min_p_vs_top_p": minp_audit,
"fsm_json_decoding": fsm_audit,
},
"modern_llm_anatomy": {
"rope_and_yarn": rope_audit,
"gqa_kv_cache_parity": gqa_parity,
"mla_latent_cache_parity": mla_parity,
"sparse_moe_audit": moe_audit,
"contextual_embedding_shift": ctx_audit,
"safetensors_roundtrip_max_diff": st_diff,
},
}
"""End-to-end CLI benchmark runner for WB-Ch19: Attention, Transformers & Modern 2026 LLM Anatomy."""
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 transformer_llm_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 transformer_llm_lab.modern_llm_blocks import run_full_ch19_wb19_benchmarks # noqa: E402
def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
"""Parse CLI arguments for WB-Ch19 benchmark execution."""
parser = argparse.ArgumentParser(
description=(
"Run WB-Ch19: Scaled Attention, FlashAttention Tiling, RoPE+YaRN, "
"GQA/MLA KV-Cache, Sparse MoE, Min-p & FSM JSON Decoding."
)
)
parser.add_argument("--seed", type=int, default=42, help="Deterministic RNG seed.")
parser.add_argument(
"--quick",
action="store_true",
help="Run lighter sample counts for fast CI verification (<4s CPU).",
)
parser.add_argument(
"--output",
type=str,
default="artifacts/ch19_wb19_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 WB-Ch19 benchmarks, print telemetry summary, and write JSON artifact."""
args = parse_args(argv)
payload = run_full_ch19_wb19_benchmarks(seed=args.seed, quick=args.quick)
payload["config"]["output"] = args.output
af = payload["attention_and_flash"]
d128 = [r for r in af["scaled_dot_product_variance"]["by_d_k"] if r["d_k"] == 128][0]
hbm32 = af["hbm_traffic_32k"]
kd = payload["kv_cache_and_decoding"]
kv70 = kd["kv_cache_scaling"]["70B_llama3_class"]["131072"]
kv671 = kd["kv_cache_scaling"]["671B_deepseek_v3_class"]["131072"]
fsm = kd["fsm_json_decoding"]
mp_low = kd["min_p_vs_top_p"]["confident_low_entropy"]
llm = payload["modern_llm_anatomy"]
rope = llm["rope_and_yarn"]
gqa = llm["gqa_kv_cache_parity"]
mla = llm["mla_latent_cache_parity"]
moe = llm["sparse_moe_audit"]
ctx = llm["contextual_embedding_shift"]
print("=== Ch 19 + WB-Ch19: Attention, Transformers & Modern 2026 LLM Architecture ===")
print(
f"[1] 1/sqrt(d_k) Proof & FlashAttention Tiling: "
f"d_k=128 Var(unscaled={d128['unscaled_var']:.1f} -> scaled={d128['scaled_var']:.2f}, "
f"H_ret={d128['entropy_retention_pct']:.1f}% vs {d128['unscaled_entropy_pct']:.1f}%) | "
f"FlashParity={af['flash_attention_parity']['max_abs_diff']:.2e} | "
f"32K HBM: {hbm32['naive_hbm_mb']:.0f}MB -> {hbm32['flash_hbm_mb']:.0f}MB "
f"(-{hbm32['hbm_reduction_pct']:.1f}%, {hbm32['hbm_reduction_factor']:.1f}x)"
)
print(
f"[2] KV-Cache Compression (128K bf16) & RoPE+YaRN: "
f"70B(MHA={kv70['mha_bf16_gb']:.1f}GB -> GQA={kv70['gqa_bf16_gb']:.2f}GB [8x]) | "
f"671B(MHA={kv671['mha_bf16_gb']:.1f}GB -> MLA={kv671['mla_bf16_gb']:.2f}GB "
f"[{kv671['mla_vs_mha_compression']:.1f}x]) | "
f"RoPE rel_diff={rope['relative_pos_abs_diff']:.2e}, "
f"YaRN 8x(hi={rope['yarn_high_freq_ratio']:.2f}, lo={rope['yarn_low_freq_ratio']:.3f})"
)
print(
"[3] PyTorch GQA/MLA Cache Parity, Sparse MoE & Contextual Shift: "
f"GQA_diff={gqa['max_abs_diff']:.2e} "
f"(decode_speedup={gqa['decode_flops_speedup_2048_ctx']:.0f}x) | "
f"MLA_diff={mla['max_abs_diff']:.2e} | "
f"MoE(CV={moe['collapsed']['load_cv']:.2f}->{moe['balanced']['load_cv']:.2f}, "
f"active={100.0 * moe['param_accounting']['active_ratio']:.1f}%) | "
f"CtxCos={ctx['contextual_hidden_cosine']:.3f} "
f"vs Static={ctx['static_embedding_cosine']:.3f} | "
f"Safetensors={llm['safetensors_roundtrip_max_diff']:.1e}"
)
print(
f"[4] Decoding (Min-p vs Top-p & FSM JSON): "
f"LowH(T=1.5) active(Top-p={mp_low['top_p_095_active']} vs Min-p={mp_low['min_p_010_active']}) | "
f"FSM JSON valid={fsm['fsm_valid_count']}/{fsm['num_trials']} ({100.0 * fsm['fsm_valid_rate']:.1f}%) "
f"vs Naive={fsm['unconstrained_valid_count']}/{fsm['num_trials']} "
f"({100.0 * fsm['unconstrained_valid_rate']:.1f}%)"
)
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())
"""Automated 16-test verification suite for WB-Ch19 (`transformer_llm_lab`, T1-P4-U02)."""
from __future__ import annotations
import ast
import json
import subprocess
import sys
from pathlib import Path
import numpy as np
import pytest
import torch
from pydantic import ValidationError
from transformer_llm_lab import (
JSON_FSM_VOCAB,
AttentionBenchmarkConfig,
DecodingConfig,
FlashTilingConfig,
GQAAttention,
KVCacheSpec,
MLAAttention,
ModernLLMConfig,
ModernTransformerLM,
RMSNorm,
RotaryEmbedding,
SparseMoELayer,
SwiGLU,
audit_contextual_embeddings_shift,
audit_gqa_kv_cache_parity,
audit_min_p_vs_top_p_entropy,
audit_mla_latent_cache_compression,
audit_moe_router_collapse_vs_balanced,
audit_rope_invariance_and_yarn,
audit_scaled_dot_product_variance,
bahdanau_additive_attention,
benchmark_fsm_json_decoding,
benchmark_kv_cache_scaling,
compute_attention_hbm_traffic,
compute_kv_cache_memory_bytes,
compute_yarn_inv_freq,
decode_beam_search,
decode_greedy,
flash_attention_tiled_forward,
load_safetensors_checkpoint,
luong_multiplicative_attention,
mask_logits_for_json_fsm,
naive_scaled_dot_product_attention,
sample_with_decoding_strategy,
save_safetensors_checkpoint,
)
LAB_ROOT = Path(__file__).resolve().parents[1]
FORBIDDEN_DESERIALIZERS = {"pickle", "joblib", "cloudpickle", "dill", "shelve", "marshal"}
def test_01_pydantic_configs_strict_forbid() -> None:
"""All Pydantic v2 configs reject unknown fields and invalid head divisibility."""
with pytest.raises(ValidationError):
AttentionBenchmarkConfig(unknown_flag=True) # type: ignore[call-arg]
with pytest.raises(ValidationError):
FlashTilingConfig(extra_field=1) # type: ignore[call-arg]
with pytest.raises(ValidationError):
KVCacheSpec(variant="gqa", num_q_heads=32, num_kv_heads=7)
with pytest.raises(ValidationError):
KVCacheSpec(variant="mqa", num_q_heads=32, num_kv_heads=4)
with pytest.raises(ValidationError):
DecodingConfig(temperature=0.0)
with pytest.raises(ValidationError):
ModernLLMConfig(d_model=64, n_q_heads=8, n_kv_heads=3)
def test_02_classical_bahdanau_and_luong_attention_convex_weights() -> None:
"""Bahdanau additive and Luong multiplicative attention produce valid convex combinations."""
rng = np.random.default_rng(7)
enc = rng.standard_normal((10, 12))
dec = rng.standard_normal((12,))
ctx_b, w_b = bahdanau_additive_attention(
dec, enc, rng.standard_normal((8, 12)), rng.standard_normal((8, 12)), rng.standard_normal((8,))
)
ctx_l, w_l = luong_multiplicative_attention(dec, enc)
ctx_lg, w_lg = luong_multiplicative_attention(dec, enc, w_a=rng.standard_normal((12, 12)))
for ctx, w in [(ctx_b, w_b), (ctx_l, w_l), (ctx_lg, w_lg)]:
assert ctx.shape == (12,)
assert w.shape == (10,)
assert np.all(w >= 0.0)
assert np.isclose(np.sum(w), 1.0, atol=1e-12)
def test_03_scaled_dot_product_variance_proof_and_causal_mask() -> None:
"""Unscaled QK^T variance scales as d_k and saturates softmax; 1/sqrt(d_k) restores Var ~1."""
res = audit_scaled_dot_product_variance(
AttentionBenchmarkConfig(d_k_values=(16, 128), seq_len=32, num_trials=48, seed=42)
)
r128 = [r for r in res["by_d_k"] if r["d_k"] == 128][0]
assert 95.0 < float(r128["unscaled_var"]) < 165.0
assert 0.75 < float(r128["scaled_var"]) < 1.25
assert float(r128["scaled_entropy"]) > 3.0 * float(r128["unscaled_entropy"])
assert float(r128["scaled_jacobian_trace"]) > 3.0 * float(r128["unscaled_jacobian_trace"])
# Strict causal mask check: upper triangle weights must be identically zero
rng = np.random.default_rng(11)
q, k, v = rng.standard_normal((12, 16)), rng.standard_normal((12, 16)), rng.standard_normal((12, 16))
_, attn = naive_scaled_dot_product_attention(q, k, v, causal=True)
upper = np.triu(attn, k=1)
assert float(np.max(np.abs(upper))) == 0.0
assert np.allclose(np.sum(attn, axis=-1), 1.0, atol=1e-12)
def test_04_flash_attention_online_softmax_exact_parity() -> None:
"""Tiled Online Safe Softmax FlashAttention matches naive O(N^2) to < 1e-5 for odd/even N."""
rng = np.random.default_rng(42)
for n_seq, causal in [(53, True), (64, True), (45, False)]:
q = rng.standard_normal((n_seq, 32))
k = rng.standard_normal((n_seq, 32))
v = rng.standard_normal((n_seq, 32))
ref, _ = naive_scaled_dot_product_attention(q, k, v, causal=causal)
flash, stats = flash_attention_tiled_forward(q, k, v, block_r=16, block_c=12, causal=causal)
assert float(np.max(np.abs(ref - flash))) < 1e-12
assert stats["lse_finite"] is True
if causal:
assert stats["skipped_causal_tiles"] > 0
def test_05_flash_attention_hbm_traffic_and_activation_reduction() -> None:
"""FlashAttention cuts HBM traffic drastically and eliminates O(N^2) activation memory."""
hbm = compute_attention_hbm_traffic(
FlashTilingConfig(seq_len=32768, d_head=128, num_heads=32, block_r=128, block_c=64, causal=True)
)
assert hbm["hbm_reduction_pct"] > 70.0
assert hbm["hbm_reduction_factor"] > 3.5
assert hbm["flash_peak_act_mb"] < hbm["naive_peak_act_mb"] / 1000.0
assert hbm["flash_arithmetic_intensity"] > 3.5 * hbm["naive_arithmetic_intensity"]
def test_06_kv_cache_exact_accounting_mha_gqa_mqa_mla() -> None:
"""Exact KV-Cache bytes match 2*L*n_kv*d_h*S*B*b and DeepSeek MLA L*(d_c+d_R)*S*B*b."""
scaling = benchmark_kv_cache_scaling()
r70 = scaling["70B_llama3_class"]["131072"]
# 70B MHA: 2 * 80 * 64 * 128 * 131072 * 2 = 343.597 GB; GQA 8:1 = 42.950 GB
assert np.isclose(r70["mha_bf16_gb"], 343.59738368, rtol=1e-6)
assert np.isclose(r70["gqa_vs_mha_compression"], 8.0, atol=1e-9)
r671 = scaling["671B_deepseek_v3_class"]["131072"]
# 671B MLA: (2*128*128)/(512+64) = 32768 / 576 = 56.8889x compression!
assert np.isclose(r671["mla_vs_mha_compression"], 32768.0 / 576.0, rtol=1e-6)
assert r671["mla_fp8_gb"] == pytest.approx(r671["mla_bf16_gb"] / 2.0)
spec_single = KVCacheSpec(
variant="mla",
num_layers=10,
num_q_heads=16,
num_kv_heads=4,
d_head=64,
d_c_latent=128,
d_rope_shared=32,
seq_len=100,
batch_size=2,
dtype_bytes=2,
)
mem = compute_kv_cache_memory_bytes(spec_single)
assert mem["total_bytes"] == 10 * (128 + 32) * 100 * 2 * 2
def test_07_rmsnorm_and_swiglu_numerics_and_scale_invariance() -> None:
"""RMSNorm preserves positive scale invariance and SwiGLU matches exact shape & finite grads."""
torch.manual_seed(42)
norm = RMSNorm(64)
x = torch.randn(4, 16, 64)
y1 = norm(x)
y2 = norm(3.7 * x)
assert float((y1 - y2).abs().max().item()) < 1e-5
swiglu = SwiGLU(64, 176)
out = swiglu(y1)
assert out.shape == (4, 16, 64)
out.sum().backward()
assert swiglu.w_gate.weight.grad is not None
assert bool(torch.isfinite(swiglu.w_gate.weight.grad).all().item())
def test_08_rope_relative_position_invariance_and_yarn_bands() -> None:
"""RoPE inner product depends strictly on (n - m) and YaRN protects high-frequency bands."""
res = audit_rope_invariance_and_yarn(seed=42)
assert res["relative_pos_abs_diff"] < 1e-5
assert np.isclose(res["yarn_high_freq_ratio"], 1.0, atol=1e-4)
assert np.isclose(res["yarn_low_freq_ratio"], 1.0 / 8.0, atol=1e-4)
assert res["yarn_mscale_8x"] > 1.2
# Direct norm preservation check: RoPE is an orthogonal rotation
rope = RotaryEmbedding(d_head=32, max_seq_len=64)
v = torch.randn(2, 4, 10, 32)
v_rot = rope.apply_rotary(v, start_pos=5)
assert float((v.norm(dim=-1) - v_rot.norm(dim=-1)).abs().max().item()) < 1e-5
inv_1, m_1 = compute_yarn_inv_freq(32, scale=1.0)
assert inv_1.shape == (16,) and m_1 == 1.0
def test_09_gqa_incremental_kv_cache_exact_parity_and_flops_cut() -> None:
"""Incremental GQA KV-Cache decoding matches full prefill logits to < 1e-5."""
res = audit_gqa_kv_cache_parity(seed=42)
assert res["max_abs_diff"] < 1e-5
assert res["cached_kv_shape"] == [1, 2, 24, 8]
assert res["decode_flops_speedup_2048_ctx"] > 500.0
# Also verify MQA (n_kv_heads=1) cache parity directly
torch.manual_seed(9)
mqa = GQAAttention(d_model=32, n_q_heads=4, n_kv_heads=1, max_seq_len=32).eval()
x = torch.randn(1, 10, 32)
with torch.inference_mode():
y_full, _ = mqa(x, use_cache=False)
y_pre, kv = mqa(x[:, :6], use_cache=True, start_pos=0)
ys = [y_pre]
for t in range(6, 10):
yt, kv = mqa(x[:, t : t + 1], past_kv=kv, use_cache=True, start_pos=t)
ys.append(yt)
y_inc = torch.cat(ys, dim=1)
assert float((y_full - y_inc).abs().max().item()) < 1e-5
def test_10_mla_compressed_latent_cache_parity_and_compression() -> None:
"""DeepSeek MLAAttention compressed latent cache matches full forward to < 1e-5."""
res = audit_mla_latent_cache_compression(seed=42)
assert res["max_abs_diff"] < 1e-5
assert res["mla_elems_per_tok"] < res["mha_elems_per_tok"]
assert res["toy_compression_ratio"] >= 10.0
# Verify MLAAttention backward gradients are finite
mla = MLAAttention(d_model=64, n_heads=4, d_nope=16, d_rope=8, d_c_latent=16, max_seq_len=32)
x = torch.randn(2, 8, 64, requires_grad=True)
y, _ = mla(x)
y.pow(2).mean().backward()
assert x.grad is not None and bool(torch.isfinite(x.grad).all().item())
def test_11_sparse_moe_active_params_and_router_collapse_vs_balanced() -> None:
"""Sparse MoE activates ~Top-k/E params and bias balancing eliminates router collapse."""
res = audit_moe_router_collapse_vs_balanced(seed=42)
acct = res["param_accounting"]
assert 0.24 < acct["active_ratio"] < 0.27 # Top-2 of 8 experts
assert res["collapsed"]["dead_experts"] >= 4
assert res["collapsed"]["load_cv"] > 1.2
assert res["balanced"]["dead_experts"] == 0
assert res["balanced"]["load_cv"] < 0.35
# Verify aux_loss is differentiable w.r.t. router weights
moe = SparseMoELayer(d_model=32, d_ff_expert=64, num_experts=4, top_k=2, aux_weight=0.05)
x = torch.randn(2, 8, 32)
out, aux_loss, _ = moe(x)
(out.pow(2).mean() + aux_loss).backward()
assert moe.router.weight.grad is not None
assert float(moe.router.weight.grad.abs().sum().item()) > 0.0
def test_12_decoding_greedy_beam_search_and_min_p_adaptivity() -> None:
"""Beam search beats greedy on global log-prob; Min-p cuts tail leaks adaptively."""
def step_fn(seq: list[int]) -> np.ndarray:
if len(seq) == 1:
return np.array([-3.0, 1.1, 0.9, -2.0])
if seq[-1] == 1:
return np.array([0.1, 0.1, 0.1, 0.1])
return np.array([3.5, -2.0, -2.0, -2.0])
g_seq, g_lp = decode_greedy(step_fn, [0], max_steps=2, eos_id=0)
b_seq, b_lp, _ = decode_beam_search(step_fn, [0], beam_width=3, max_steps=2, eos_id=0)
assert g_seq == [0, 1, 0]
assert b_seq == [0, 2, 0]
assert b_lp > g_lp
# Min-p vs Top-p adaptivity under high temperature T=1.5
mp = audit_min_p_vs_top_p_entropy(seed=42)
low_h = mp["confident_low_entropy"]
high_h = mp["uncertain_high_entropy"]
assert low_h["min_p_010_active"] < low_h["top_p_095_active"]
assert low_h["min_p_010_tail_leak_prob"] < low_h["top_p_095_tail_leak_prob"]
assert high_h["min_p_010_active"] > low_h["min_p_010_active"]
# Probability normalization invariant across all decoding strategies
logits = np.array([3.0, 2.0, 1.0, 0.0, -1.0, -2.0])
for cfg in [
DecodingConfig(strategy="greedy"),
DecodingConfig(strategy="temperature", temperature=0.8),
DecodingConfig(strategy="top_k", top_k=3),
DecodingConfig(strategy="top_p", top_p=0.8),
DecodingConfig(strategy="min_p", min_p=0.15),
]:
_, probs, active, _ = sample_with_decoding_strategy(logits, cfg, rng=np.random.default_rng(1))
assert np.isclose(np.sum(probs), 1.0, atol=1e-12)
assert active >= 1
def test_13_fsm_grammar_constrained_json_100pct_validity() -> None:
"""FSM logit masking guarantees 100% schema-valid JSON even on noisy LLM logits."""
# Direct logit mask check at state 0: only token 0 ('{"status":"') may remain finite
raw = np.ones(len(JSON_FSM_VOCAB), dtype=np.float64)
masked = mask_logits_for_json_fsm(raw, fsm_state=0)
assert np.isfinite(masked[0])
assert bool(np.all(np.isneginf(masked[1:])))
bench = benchmark_fsm_json_decoding(num_trials=40, seed=42)
assert bench["fsm_valid_rate"] == 1.0
assert bench["fsm_valid_count"] == 40
assert bench["unconstrained_valid_rate"] < 0.15
def test_14_modern_transformer_lm_training_step_and_contextual_shift() -> None:
"""ModernTransformerLM trains cleanly (finite grads) and separates polysemous contexts."""
torch.manual_seed(42)
cfg = ModernLLMConfig(
vocab_size=64, d_model=64, n_layers=2, n_q_heads=8, n_kv_heads=2, d_ff=176, use_moe=True
)
model = ModernTransformerLM(cfg)
x = torch.randint(0, 64, (2, 16))
y = torch.randint(0, 64, (2, 16))
out = model(x)
loss = torch.nn.functional.cross_entropy(out["logits"].view(-1, 64), y.view(-1)) + out["aux_loss"]
loss.backward()
assert bool(torch.isfinite(loss).item())
assert model.tok_emb.weight.grad is not None
assert bool(torch.isfinite(model.tok_emb.weight.grad).all().item())
ctx = audit_contextual_embeddings_shift(seed=42)
assert np.isclose(ctx["static_embedding_cosine"], 1.0, atol=1e-6)
assert ctx["contextual_hidden_cosine"] < 0.90
def test_15_safetensors_checkpoint_roundtrip_zero_pickle(tmp_path: Path) -> None:
"""Safetensors save/load round-trips ModernTransformerLM with exact 0.0 logit diff."""
torch.manual_seed(123)
cfg = ModernLLMConfig(vocab_size=48, d_model=32, n_layers=2, n_q_heads=4, n_kv_heads=2, d_ff=96)
m1 = ModernTransformerLM(cfg).eval()
m2 = ModernTransformerLM(cfg).eval()
ckpt = tmp_path / "wb_ch19_lm.safetensors"
save_safetensors_checkpoint(m1, ckpt)
load_safetensors_checkpoint(m2, ckpt)
ids = torch.randint(0, 48, (2, 10))
with torch.inference_mode():
diff = float((m1(ids)["logits"] - m2(ids)["logits"]).abs().max().item())
assert diff == 0.0
def test_16_cli_demo_workbench_json_schema_and_ast_deserialization_guard(tmp_path: Path) -> None:
"""CLI emits valid workbench_panels (6 KPIs, 4 bars, 4 tables) and AST bans unsafe deserializers."""
out_json = tmp_path / "ch19_wb19_quick.json"
proc = subprocess.run(
[sys.executable, str(LAB_ROOT / "scripts" / "run_lab_demo.py"), "--quick", "--output", str(out_json)],
capture_output=True,
text=True,
check=True,
)
assert "Ch 19 + WB-Ch19" in proc.stdout
data = json.loads(out_json.read_text(encoding="utf-8"))
panels = data["workbench_panels"]
assert len(panels["kpis"]) == 6
assert len(panels["bars"]) == 4
assert len(panels["tables"]) == 4
# AST security guard across all Python source & script files (ban unsafe deserializers only)
py_files = list((LAB_ROOT / "src").rglob("*.py")) + list((LAB_ROOT / "scripts").rglob("*.py"))
assert len(py_files) >= 4
for py_file in py_files:
tree = ast.parse(py_file.read_text(encoding="utf-8"), filename=str(py_file))
for node in ast.walk(tree):
if isinstance(node, ast.Import):
for alias in node.names:
assert alias.name.split(".")[0] not in FORBIDDEN_DESERIALIZERS
elif isinstance(node, ast.ImportFrom) and node.module:
assert node.module.split(".")[0] not in FORBIDDEN_DESERIALIZERS
0 và phương sai 1, vì sao Scaled Dot-Product Attention bắt buộc phải chia tích vô hướng \(\mathbf{q}^\top\mathbf{k}\) cho \(\sqrt{d_k}\) (đã kiểm chứng tại WB-Ch19, Test 03)?1 có phương sai đúng bằng \(d_k\). Trong WB-Ch19, chia \(\sqrt{128}\) đưa phương sai từ 128.96 về 1.01, giữ 86.8% entropy và bảo toàn dòng gradient qua Jacobian Softmax.
Encoder-only, Encoder-Decoder, Decoder-only) và cơ chế biểu diễn ngữ cảnh (WB-Ch19, Test 14), nhận định nào ĐÚNG?WB-Ch19 (Test 14), cùng token_id = 7 có static_embedding_cosine = 1.000 nhưng sau 4 tầng Self-Attention trên hai tiền tố khác nhau, contextual_hidden_cosine giảm mạnh xuống 0.406 (độ dịch 0.594).
RoPE và kỹ thuật kéo dài cửa sổ ngữ cảnh YaRN (8x: 4K -> 32K) trong WB-Ch19 (Test 08), phát biểu nào CHÍNH XÁC?9.54e-07). YaRN trộn theo số chu kỳ quay \(r_j\) giữa \(\beta_{\text{slow}}=1\) và \(\beta_{\text{fast}}=32\) để không phá vỡ phân giải token cục bộ.
KV-Cache và thực nghiệm ở ngữ cảnh 128K (bf16, B=1) của WB-Ch19 (Tests 06, 09, 10), kết luận nào ĐÚNG?RoPE không giao hoán với ma trận chiếu lên \(\mathbf{W}^{UK}\), MLA tách riêng nhánh nội dung (nope, có thể hấp thụ ma trận) và nhánh vị trí dùng chung (d_R=64), đạt tỷ lệ nén 32768 / 576 = 56.89x trên lớp 671B.
FlashAttention tăng tốc và giảm mạnh bộ nhớ trên GPU ở ngữ cảnh dài (WB-Ch19, Tests 04, 05)?FlashAttention vẫn thực hiện cùng số FLOPs \(\mathcal{O}(N^2 d)\) (bỏ khối tam giác trên khi causal) nhưng loại bỏ hoàn toàn việc đọc/ghi ma trận \(N\times N\) qua băng thông HBM, tăng cường độ số học Roofline từ 31.9 lên 126.5 FLOP/B.
SparseMoELayer (Top-2 trên 8 chuyên gia) của WB-Ch19 (Test 11), hiện tượng Sụp đổ Bộ định tuyến (Router Collapse) và cách khắc phục chuẩn 2026 hoạt động như thế nào?~0.01). Thiên lệch động của DeepSeek-V3 chỉ tham gia vào phép chọn TopK, giữ nguyên trọng số trộn \(p_e\) sạch.
Beam Search với Greedy và Min-p (0.10) với Top-p (0.95) ở nhiệt độ cao T = 1.5 (WB-Ch19, Test 12), phát biểu nào ĐÚNG?Min-p (Nguyen et al., ICLR 2025) tự động siết chặt khi mô hình chắc chắn và nới rộng khi nhiều lựa chọn cùng hợp lý — loại bỏ điểm yếu cố hữu của cả Top-k lẫn Top-p.
FSM) và lưu trữ trọng số mô hình (WB-Ch19, Tests 13, 15, 16), kết luận kỹ thuật nào CHÍNH XÁC?Outlines/xgrammar chỉ tốn < 50 us/token nhưng đảm bảo xác suất sinh token sai văn phạm bằng đúng 0.0. safetensors chỉ chứa tiêu đề JSON + buffer tensor thuần, cấm tuyệt đối mã thực thi.
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 Phương sai 1/sqrt(d_k), Mặt nạ Nhân quả & Bahdanau vs. Luong 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Dùng tính độc lập và kỳ vọng 0 để chứng minh \(\operatorname{Var}(\sum_{r=1}^{d_k} q_r k_r) = d_k\), sau đó viết Jacobian Softmax \(\operatorname{diag}(\mathbf{p}) - \mathbf{p}\mathbf{p}^\top\) giải thích vì sao \(\max p_i \to 1\) làm triệt tiêu gradient.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Đối chiếu thực nghiệm trên bahdanau_additive_attention, luong_multiplicative_attention và audit_scaled_dot_product_variance (Tests 02, 03).
Tiêu chí Đáp án & Số đối chứng
Tại \(d_k = 128\), phương sai chưa chia đạt 128.96 làm entropy sụp còn 9.2% và Jacobian trace tụt còn 0.173; chia \(\sqrt{128}\) khôi phục phương sai 1.01, giữ 86.8% entropy (trace = 0.926), và tam giác trên mặt nạ nhân quả bằng chính xác 0.0.
Bài tập 2 — Chứng minh & Cài đặt FlashAttention Online Safe Softmax Tiling + Mô hình HBM 20%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Biến đổi trực tiếp tử số và mẫu số tổng Softmax trên hợp hai khối \(S_1 \cup S_2\) theo \(m_{\text{new}} = \max(m_1, m_2)\) để chứng minh hệ số điều chỉnh \(e^{m_1 - m_{\text{new}}}\) bảo toàn đẳng thức tuyệt đối.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Kiểm tra hàm flash_attention_tiled_forward trên độ dài chuỗi lẻ (N=53, 45) không chia hết cho (B_r, B_c) và phân tích lưu lượng HBM qua compute_attention_hbm_traffic (Tests 04, 05).
Tiêu chí Đáp án & Số đối chứng
flash_attention_tiled_forward khớp Attention vật liệu hóa tới 8.88e-16 (< 1e-12), bỏ qua 28/64 khối nhân quả; tại N=32K (B_r=128), lưu lượng HBM giảm 275.95 -> 69.53 GB (-74.8%, 3.97x) và kích hoạt đỉnh hạ từ 137.4 GB còn 4.19 MB.
Bài tập 3 — Chứng minh Bất biến RoPE SO(2) & Thiết kế Dải Tần số Ngoại suy YaRN 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Nhân hai khối xoay \(2\times 2\) \(\mathbf{R}_j(m)^\top \mathbf{R}_j(n)\) dùng công thức lượng giác hiệu góc để suy ra \(\mathbf{R}_j(n - m)\) và bất biến chuẩn L2.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Tính số chu kỳ quay \(r_j = L_{\text{train}}\theta_j / (2\pi)\) và hàm trộn \(\gamma_j\) giữa \(\beta_{\text{slow}}=1, \beta_{\text{fast}}=32\) rồi kiểm chứng trên audit_rope_invariance_and_yarn (Test 08).
Tiêu chí Đáp án & Số đối chứng
RoPE đạt sai khác bất biến vị trí tương đối 9.54e-07 (< 1e-5) khi dịch đồng thời +43; YaRN 8x giữ nguyên tỷ lệ tần số cao 1.000, nội suy tần số thấp 0.125 (1/8) và điều chỉnh nhiệt độ mscale = 1.208.
Bài tập 4 — Tính Ngân sách KV-Cache (MHA/GQA/MQA/MLA) & Cache Tăng dần PyTorch 20%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Áp dụng \(2 L n_{\text{kv}} d_h S B b\) cho MHA/GQA/MQA và \(L(d_c + d_R) S B b\) cho MLA ở S=131,072; giải thích vì sao RoPE không giao hoán với \(\mathbf{W}^{UK}\) buộc MLA tách nhánh Decoupled RoPE.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Kiểm chứng giải mã tăng dần 1-token khớp prefill toàn phần trên audit_gqa_kv_cache_parity và audit_mla_latent_cache_compression (Tests 06, 09, 10).
Tiêu chí Đáp án & Số đối chứng
Tại 128K bf16, 70B MHA = 343.60 GB -> GQA 8:1 = 42.95 GB (8.0x); 671B MHA = 523.99 GB -> MLA = 9.21 GB (56.9x, 4.61 GB ở fp8). Giải mã tăng dần khớp toàn phần ở mức 3.58e-07 (GQA, cắt 2,080x FLOP) và 7.45e-08 (MLA).
Bài tập 5 — Tầng Sparse MoE, Bất đẳng thức Aux-Loss & Chẩn đoán Router Collapse 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Dùng Cauchy–Schwarz (hoặc đẳng thức Jensen trên phân phối đều) để phân tích cực tiểu của \(\mathcal{L}_{\text{aux}} = \alpha E \sum f_e P_e\) khi \(f_e = P_e = 1/E\), đồng thời phân biệt với cập nhật thiên lệch chọn b_e của DeepSeek-V3.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy audit_moe_router_collapse_vs_balanced kiểm tra tỷ lệ Active/Total, số chuyên gia chết và chỉ số biến thiên tải load_cv (Test 11).
Tiêu chí Đáp án & Số đối chứng
Top-2/8 MoE kích hoạt 25.2% tham số (49,664 / 197,120). Trạng thái sụp đổ có CV = 1.73, 6/8 chuyên gia chết (max_share = 50%); sau cân bằng thiên lệch động, CV giảm xuống 0.16 với 0 chuyên gia chết (aux_loss = 0.0099).
Bài tập 6 — Động cơ Giải mã Min-p, Mặt nạ FSM JSON 100% & Safetensors (16/16 Pytest) 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
So sánh điều kiện cắt của Min-p (\(p_i \ge p_{\text{base}}\cdot p_{\max}\)) với tổng tích lũy của Top-p khi tăng nhiệt độ T = 1.5, và thiết kế bảng chuyển trạng thái DFA cho lược đồ JSON {"status", "score"}.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy trọn bộ audit_min_p_vs_top_p_entropy, benchmark_fsm_json_decoding, save_safetensors_checkpoint, ruff, mypy, pytest -p no:cacheprovider -v và scripts/run_lab_demo.py --seed 42.
Tiêu chí Đáp án & Số đối chứng
Min-p (0.10) ở Low-H (T=1.5) giữ 2 token (0.0% rò đuôi) vs Top-p (0.95) 41 token (11.1% rò đuôi); FSM JSON đạt 60/60 (100.0%) vs 0/60 tự do; safetensors đạt sai số 0.0; vượt trọn vẹn 16/16 pytest, 0 lỗi ruff/mypy.