Chương 21 — Ngân sách Độ trễ Phục vụ LLM (TTFT/TPOT), Đồng thiết kế Mô hình, Bộ nhớ KV-Cache & Đo kiểm SLO Goodput
Chuyên đề #18, #19, #22, #30: Phân rã Roofline H100 (Prefill 1941 FLOP/B vs Decode 1.06 FLOP/B, ridge 295.22), co-design Shallow-Wide giảm 33.24% TPOT, MoE 8x7B 8.61ms (3.08x vs Dense 47B) & 32B FP8 đạt SLO, ngân sách KV 128k–1M (MLA 4.50 GiB nén 14.22x MHA 64.0 GiB OOM) & lật tẩy ảo ảnh 5,752 tok/s khi SLO Goodput sụp về 0.0 req/s (Admission Control giữ 100.0% SLA tại 6.50 req/s).
Unit ID:
T2-P4-U02
Track & Part: Track 2 (EDAI) — Part 4: Production ML & LLM Serving Systems Engineering (part-04-ml-and-llm-serving-systems)
Cầu nối Từ Chương 20 & Hướng Tới Chương 22: Chương 20 thiết lập các mẫu phục vụML(Online/Batch/Cached, hàng đợi bất đồng bộRabbitMQ, tầng nối tiếp và chưng cất mô hình dưới lưu lượng đột biến). Chương 21 bước thẳng vào vật lý tính toán và kinh tế hạ tầng của suy luậnLLMtự hồi quy: phân rãTTFT,TPOT/ITLvàE2Etrên đường máiH100/B200, đồng thiết kế tham số/độ sâu/FFN/từ vựng theo ngân sách phục vụ, giải phương trình bộ nhớKV-CachequaMHA/MQA/GQA/MLA/Hybrid SWAtới ngữ cảnh1Mtoken, và phơi bày ảo ảnhtokens/stổng hợp bằngSLO Goodput— làm bệ phóng cho tối ưu nhân động cơ suy luận (Continuous Batching,PagedAttention, tách phaP/D,Speculative Decoding, lượng tử hóa ởCh 22).
Truy xuất Giáo trình Gốc (R42— Dive into LLM-serving & 4 Chuyên đề Sâu): KV cache; LLM serving challenges and solutions trong 02-track-edai-raw-curriculum.md và 02-track-2-edai-sota-syllabus.md, tích hợp trọn vẹn Chuyên đề#18,#19,#22và#30.
Xưởng Thực hành Song hành (WB-Ch21): labs/ch21-llm-serving-slo-goodput-workbench/README.md (llm_slo_goodput_lab)
Tình huống Mở đầu: Bốn Cú Sốc Vật lý Khi Đưa LLM Ra Sản xuất#
Một mô hình ngôn ngữ lớn đạt điểm benchmark học thuật rất cao vẫn có thể phá sản về chi phí hoặc gây bão lỗi timeout ngay tuần đầu vận hành nếu kỹ sư bỏ qua bốn giới hạn vật lý sau:
- Ảo tưởng "Lọt VRAM Là Chạy Được" Trên
32B BF16(#18): Thấy mô hìnhQwen-32B BF16chiếm61.02 GiBtrọng số (vẫn lọt vừa80 GiBH100 SXM), đội ngũ triển khai cam kếtTPOT <= 25 ms. Phân tích mô hình đường mái giải tích Roofline trongWB-Ch21(Exp 1) cho thấy: ngay ởB = 1, mỗi bước decode buộc phải đọc lại toàn bộ tham số hoạt động qua băng thôngHBM3(3.35 TB/s, hiệu dụng2.613 TB/s) trong khi chỉ còn2.98 GiBchoKV-cache(sau16.0 GiBdự trữ hệ thống), đẩyTPOT = 27.58 ms(vi phạm trần25 ms). Lượng tử hóaFP8cắt đôi băng thông đọc trọng số, kéoTPOTxuống15.23 ms(33.49 GiBKV headroom) vàTTFTtừ252.92 msxuống132.84 ms— đạt chuẩn cả hai SLO trên cùng một GPU! - Bẫy Sâu–Hẹp (
L=64, d=4096), Từ vựng256k& Nhầm lẫn Embedding vs LM Head +MoE(#19): Ở cùng ngân sách ~10Btham số trên2x H100 TP2, kiến trúc Sâu–Hẹp (L=64, d=4096) tạo ra128rào đồng bộ AllReduce và ngốn256 KiB/tokKV-cache, khiếnTPOT = 11.16 ms. Thiết kế lại thành Nông–Rộng (L=32, d=5120) giảm33.24%TPOT(7.45 ms) và cắt2.0xbộ nhớKV-cache(128 KiB/tok). Tương tự, nâng từ vựng từ32k tiedlên256k untiedlàm tổng tham số lưu VRAM phình lên2.097B(23.11%) dù bước decode 1 token chỉ đọc1hàng nhúng đầu vào (\(O(d)\)) và chỉ chạy GEMV quaLM Head(\(V \times d\)). Ngoài ra, dùngMoE(Mixtral-8x7B,46.70Btổng nhưng chỉ12.75Btham số hoạt động/token) cắtTPOTởB=1xuống8.61 ms(3.08xnhanh hơnDense-47Bcùng VRAM26.53 ms)! - Thảm họa Nổ
OOMỞ Ngữ cảnh128kVì DùngMHA(#30): Với đầu8B(L=32, n_h=32, d_h=128) chạy trênH100 80 GiB(chừa48.0 GiBheadroomKV-cachesau~16 GiBtrọng số và16.0 GiBdự trữ hệ thống thống nhất), phương trình bộ nhớ chính xác chứng minhMHA BF16(512 KiB/tok) ngốn tới64.00 GiBcho MỘT chuỗi128k— nổOOMngay lập tức (0chuỗi chạy được)! Chuyển sangMLA(d_c=512 + d_R=64,36 KiB/tok) nén14.22xxuống4.50 GiB/chuỗi(10chuỗi đồng thời), vàFP8 KVnhân tiếp lên21chuỗi ở128kvà chạy mượt2chuỗi ở1Mtoken trên đúng 1 GPU! - Cái Bẫy
5,752 tokens/sĐỉnh cao Trong KhiSLO GoodputĐã Rơi Về0.000 req/s(#22): Khi tăng tốc độ tải \(\lambda\) từ6.0lên11.0 req/strên hàng đợiFIFO, bảng giám sát báoraw_total_tokens_per_sectăng lên đỉnh5,751.7 tok/s. Nhưng bên trong hàng đợi,p99 TTFTđã nổ tung từ358.69 mslên63,880.32 ms, khiếnSLO Goodput(đạt cảTTFT <= 500 ms&TPOT <= 35 ms) sụp đổ từ5.535 req/sxuống đúng0.000 req/s! Với traffic đột biến (Bursty CV^2 = 4.0), chỉ kiểm soát nạp bảo toàn thời hạn (SLO-Aware Admission Control) mới giữ được6.496 req/sGoodput (100.0%tuân thủ SLO).
Mục tiêu Học tập (Learning Objectives)#
Sau Chương 21 và xưởng thực hành llm_slo_goodput_lab (WB-Ch21), kỹ sư Hệ thống ML/LLM nắm vững:
- Phân rã Ngân sách Độ trễ & Đường mái Phần cứng (
#18): Tính toán chính xácTTFT,TPOT/ITL,E2E, xác định điểm gãy cường độ số học (Ridge Point) trênH100 SXM(295.22 FLOP/BBF16) vàB200 SXM(281.25 FLOP/B), giải thích pha compute-bound prefill đối lập HBM-bandwidth-bound decode, và định vị khớp gối batch size (arithmetic-intensity knee). - Đồng thiết kế Mô hình Theo Ngân sách Phục vụ (
#19): Đánh giá tác động vật lý của kích thước tham số & lượng tử hóa (8B/32B/70B,BF16vsFP8), đánh đổi Độ sâu vs Độ rộng (L=64, d=4096vsL=32, d=5120), tỷ lệ FFNSwiGLU 8/3vs4.0, và chi phí bộ nhớ + bước decode của từ vựng lớn (32k tiedvs128k/256k untied). - Phương trình Bộ nhớ
KV-CacheNgữ cảnh Dài32k–1M(#30): Dẫn xuất chính xác công thứcbytes/token,GiB/chuỗivà năng lực lô đồng thời tối đa qua5kiến trúc chú ýMHA,GQA-8,MQA,MLA (d_c=512 + d_R=64)vàHybrid SWA (W=4096, 3:1)trên cảBF16vàFP8 KV. - Đo kiểm
SLO GoodputĐúng chuẩn (#22): Phân biệt rạch ròi ảo ảnhraw tokens/svớiSLO Goodput, phân tích nguyên nhân dòng Bursty (CV^2 = 4.0) sụp đổ sớm hơn Poisson, và triển khai kiểm soát nạp nhận thức SLO kèm theo dõiOpenTelemetry.
Bảng Truy xuất Giáo trình Gốc sang Chuẩn SOTA 2026 (Unit T2-P4-U02, R42 + #18, #19, #22, #30)#
| Chuyên đề & Giáo trình Gốc | Nâng cấp Chuẩn SOTA 2026 (ch-21) |
Mục trong Chương 21 | Tạo tác & Kiểm thử (llm_slo_goodput_lab) |
|---|---|---|---|
1. LLM serving challenges (R42) + #18 |
Đường mái giải tích H100 (295.22 FLOP/B) & B200 (180 GiB khả dụng / 192 GiB vật lý); tách Embed Lookup khỏi LM Head GEMV; Batch AI knee (B=1..768) |
Trụ cột 1 (§1.1: 4 phần) + Mermaid 1 + Widget 1 | kv_attention_codesign.py, Tests 03–05, 16, 21, 24 |
2. #19 Model-System Co-Design |
8B/32B/70B BF16 vs FP8, MoE 8x7B (46.7B/12.75B vs Dense 47B: 3.08x B1), Depth vs Width (-33.24% TPOT, 2.0x KV), SwiGLU 8/3, Vocab 32k..256k |
Trụ cột 1 (§1.2: 4 phần) + Mermaid 1 + Widget 1 | evaluate_model_codesign_suite, Tests 04, 06–07, 25 |
3. KV cache (R42) + #30 |
Phương trình KV chính xác 4k–1M (thống nhất 16.0 GiB dự trữ): MHA (64 GiB OOM), GQA-8, MQA, MLA (4.50 GiB, 14.22x), Hybrid SWA (4.375 GiB, 3:1) + FP8 KV (21 seqs) |
Trụ cột 1 (§1.3: 4 phần) + Mermaid 2 + Widget 2 | analyze_kv_cache_landscape, Tests 08–10, 20, 22 |
4. #22 SLO Goodput Benchmarking |
Mô phỏng DES 180s (seed=42) đối chiếu Poisson FIFO, Bursty Gamma FIFO (CV^2=4.0), Bursty + Admission Control + 5 OTel spans |
Trụ cột 1 (§1.4: 4 phần) + Mermaid 3 + Widget 3 | slo_goodput_benchmark.py, Tests 12–15, 17–19 |
Bảng Ký hiệu Thống nhất Xuyên suốt Chương 21 (Unified Notation)#
| Ký hiệu | Miền / Đơn vị | Định nghĩa Chính xác Trong Chương 21 & llm_slo_goodput_lab |
Giá trị Mô hình WB-Ch21 (seed=42) |
|---|---|---|---|
| \(\text{TTFT}, \text{TPOT}\) | \(\text{ms}\) | Thời gian tới token đầu tiên và thời gian trung bình mỗi token đầu ra (Roofline) | 8B-BF16: 66.02 ms / 7.29 ms; 32B-BF16: 252.92 ms / 27.58 ms (FAIL) |
| \(\text{E2E}\) | \(\text{ms}\) | Tổng độ trễ đầu-cuối yêu cầu: \(\text{TTFT} + (S_{\text{out}} - 1)\cdot\text{TPOT}\) | 8B-BF16 (256 out): 1,925.80 ms; 8B-FP8: 1,152.20 ms |
| \(I, I^*, P_{\text{act}}\) | \(\text{FLOP/B}, B\) | Cường độ số học, điểm gãy phần cứng & tham số GEMV hoạt động (!= VRAM nếu untied/MoE) |
H100 BF16: 295.22 (eff=208.17); MoE 8x7B: 12.748B active / 46.701B total (8.61 ms TPOT) |
| \(L, d, d_c, d_R, W\) | Số nguyên | Số tầng, chiều ẩn, chiều nén MLA (512+64), cửa sổ cục bộ SWA (4096) |
MHA 128k BF16: 64.0 GiB (OOM trên 48 GiB) vs MLA: 4.50 GiB (10 / 21 seqs) |
| \(\lambda, G_{\text{SLO}}\) | \(\text{req/s}\) | Tốc độ yêu cầu đến và SLO Goodput thỏa đồng thời TTFT<=500ms & TPOT<=35ms |
Poisson đỉnh 5.535 \(\to\) 0.000 (11 req/s); Admission Control giữ 6.496 req/s |
Trụ cột 1 — Nguyên lý Gốc: Đường mái TTFT/TPOT, Đồng thiết kế Mô hình, KV-Cache & SLO Goodput#
1.1 Phân rã Độ trễ Phục vụ LLM (TTFT, TPOT, E2E) & Đường mái H100/B200 (#18)#
Lưu ý Chuẩn Khoa học (
Analytical Roofline Model): Mọi số liệu ở §1.1–§1.3 là kết quả tính trực tiếp từ phương trình đường mái Roofline giải tích và phương trình dung lượng KV-cache chính xác trên thông số phần cứng chuẩn — KHÔNG phải phép đo đồng hồ tường trên GPU vật lý.
1) Cơ chế Gốc & Tình huống Lỗi (#18)#
Hai pha suy luận LLM tự hồi quy có bản chất vật lý đối lập hoàn toàn: Prefill xử lý song song toàn bộ \(S_{\text{in}}\) token của prompt nên cực kỳ giàu tính toán (compute-bound), còn Decode tại B = 1 chỉ sinh 1 token mỗi bước nhưng phải quét lại toàn bộ ma trận trọng số hoạt động + toàn bộ KV-cache qua băng thông HBM (HBM-bandwidth-bound). Sai lầm kinh điển là cam kết SLO chỉ dựa vào tiêu chí "trọng số lọt vừa VRAM GPU" hoặc đánh đồng giữa bộ nhớ lưu trữ VRAM (total_params) với tham số tham gia GEMV trong decode (active_gemv_params): khi tied_embeddings=False, bảng nhúng đầu vào (\(V \times d\)) thực chất chỉ thực hiện tra cứu 1 hàng/token (\(O(d)\) byte) chứ KHÔNG nhân ma trận trên toàn bộ từ vựng \(V\), chỉ riêng LM Head (\(V \times d\)) chạy phép nhân GEMV dày đặc!
2) Mô hình Toán học Đường mái & Dự trữ VRAM Thống nhất (#18)#
-
Ba Phương trình Ngân sách Độ trễ:
-
TTFT(Time-to-First-Token):\[\text{TTFT} = t_{\text{queue}} + t_{\text{tokenize}} + \max\!\left(\frac{\text{FLOPs}_{\text{prefill}}}{\text{Peak}_{\text{eff}}}, \frac{\text{Bytes}_{\text{prefill}}}{\text{BW}_{\text{eff}}}\right) + t_{\text{TP\_comm}} + t_{\text{launch}}\]với \(\text{FLOPs}_{\text{prefill}} = 2 P_{\text{active,non-emb}} S_{\text{in}} + 2 L (n_h d_h) S_{\text{in}}^2 + 2 V d\) — số hạng bậc hai \(S_{\text{in}}^2\) phản ánh phép chú ý \(QK^T\) và \(AV\).
-
TPOT(Time-Per-Output-Token) &E2E:\[\text{FLOPs}_{\text{decode}}(B) = B \cdot \big(2 P_{\text{active\_gemv}} + 4 L (n_h d_h) S_{\text{ctx}}\big), \qquad P_{\text{active\_gemv}} = P_{\text{active,non-emb}} + V d\]\[\text{E2E} = \text{TTFT} + (S_{\text{out}} - 1) \cdot \text{TPOT}, \qquad \text{KV Headroom/GPU} = V_{\text{usable}} - \frac{W_{\text{bytes}}}{\text{TP} \cdot \text{GiB}} - V_{\text{reserve}}\]trong đó toàn chương và
WB-Ch21thống nhất dùng một hằng số dự trữ hệ thống \(V_{\text{reserve}} = 16.0\text{ GiB}\) (cho ngữ cảnh CUDA, tensor kích hoạt trung gian, bộ đệmNCCLvà đồ thị thực thi) ở cảExp 1lẫnExp 2.
-
-
Thông số Phần cứng Chuẩn & HBM Khả dụng (
H100vsB200):- NVIDIA H100 SXM (
80 GiB): ĐỉnhBF16989.0 TFLOP/s(FP8:1,979.0 TFLOP/s), băng thông HBM33.35 TB/s. Điểm gãy lý thuyết \(I^*_{\text{BF16}} = 989 / 3.35 = \mathbf{295.22\text{ FLOP/B}}\) (FP8:590.75); nhân hệ số hiệu dụng (MFU = 55%,HBM BW = 78%\(\implies 2.613\text{ TB/s}\)) cho điểm gãy hiệu dụng208.17 FLOP/B. - HGX NVIDIA B200 SXM (
180 GiBHBM3e khả dụng /192 GiBvật lý): ĐỉnhBF162,250 TFLOP/s(FP8:4,500 TFLOP/s), băng thông HBM3e8.00 TB/s, điểm gãy281.25 FLOP/B. Sau khi trừ chi phí firmware/ECC/quản trị phần cứng, bộ nhớ HBM3e khả dụng thực tế cho workload là180 GiB(dù thanh HBM vật lý danh định192 GiB).
- NVIDIA H100 SXM (
3) Thí nghiệm Kiểm chứng Đường mái (WB-Ch21 Exp 1a & 1b)#
- Pha Prefill (
S_in = 2048trênLlama3-8B-BF16):7.505Btham số hoạt động (8.030Blưu VRAM), cường độ số học1,941.08 FLOP/B\(\gg 295.22\): hoàn toàncompute_bound(54.58 mstính toán vs5.85 msbộ nhớ \(\implies\)TTFT = 66.02 ms). - Pha Decode (
B = 1): Cường độ số học tụt xuống1.06 FLOP/B(< 1%công suất Tensor Core \(\implies\)memory_bound:5.85 msđọc HBM vs0.03 mstính toán \(\implies\)TPOT = 7.29 ms,e2e = 1,925.80 ms, headroom KV =49.04 GiB). - Khớp Gối Cường độ Số học Theo Kích thước Lô (
Batch AI Knee,B = 1..768,S_ctx = 128):B = 1:AI = 1.00 FLOP/B,TPOT = 7.19 ms,139.1 tok/s(memory_bound).B = 16:AI = 15.79 FLOP/B,TPOT = 7.29 ms, thông lượng vọt lên2,195.7 tok/s(15.8x).B = 256:AI = 199.91 FLOP/B,TPOT = 8.83 ms,28,996.7 tok/s(tiệm cận điểm gãy hiệu dụng208.17).B = 384(Điểm chuyển pha):AI = 269.84 FLOP/Bvượt ngưỡng hiệu dụng sangcompute_bound, thông lượng gần như bão hòa (31,779.8 -> 32,755.7 -> 33,793.4 tok/stạiB = 768) trong khiTPOTtăng dựng đứng từ8.83 mslên12.08 -> 15.63 -> 22.73 ms!
4) Quy tắc Ra quyết định Sản xuất (#18 Playbook)#
- Kiểm soát Kích thước Lô Quanh Điểm Gối: Đặt
max_num_seqsdưới điểm gốicompute_boundhiệu dụng (ví dụ quanh128–256tùy độ dài ngữ cảnh \(S_{\text{ctx}}\)) để nhân thông lượng mà không làm vỡ ngân sáchTPOT. - Không Bao giờ Lập Dự toán Từ VRAM Danh định: Dùng
V_usable(80 GiBH100,180 GiBB200) trừ thẳng16.0 GiBdự trữ hệ thống rồi mới tính số chuỗi KV tối đa.
1.2 Đồng thiết kế Kiến trúc LLM Cho Ngân sách Phục vụ: FP8, MoE, Depth/Width & Vocab (#19)#
1) Cơ chế Gốc & Tình huống Lỗi (#19)#
Cùng một tổng số tham số và dung lượng VRAM, hai kiến trúc mạng khác nhau có thể chênh lệch 2x–3x độ trễ TPOT. Ba cái bẫy đồng thiết kế thường gặp nhất là: (i) chồng quá nhiều tầng mảnh (Sâu–Hẹp) làm nhân đôi số rào AllReduce và KV-cache; (ii) dùng mạng Dense ở ngưỡng 32B–70B BF16 thay vì FP8 hoặc MoE thưa; và (iii) phình FFN 4.0x trên SwiGLU hoặc mở rộng bảng từ vựng 256k untied không cần thiết.
2) Mô hình Toán học Co-Design (MoE, Depth/Width, SwiGLU, Untied Vocab)#
- Hàm kích hoạt
SwiGLU(3ma trậngate, up, down): Để giữ nguyên tổng tham số \(8d^2\) của FFN GELU chuẩn (\(2 \times d \times 4d\)), kích thước ẩn phải thỏa \(3 d \cdot d_{\text{ffn}} = 8 d^2 \implies d_{\text{ffn}} = \mathbf{\frac{8}{3} d}\). - Mô hình Thưa
MoE(Echuyên gia, chọnkmỗi token): Mỗi token chỉ kích hoạt \(k/E\) FFN ởB = 1(P_active << P_total), nhưng khi kích thước lô decodeBtăng lên, số chuyên gia bị chạm đồng thời trong một bước tuân theo định luật chiếm chỗ:\[\phi_{\text{routed}}(B) = 1 - \left(1 - \frac{k}{E}\right)^B\]ỞB = 1: \(\phi_{\text{routed}}(1) = k/E\) (tiết kiệm tối đa băng thông HBM). KhiB = 128trên8x7B (k=2, E=8): \(\phi_{\text{routed}}(128) \approx 1.0\), nghĩa là mọi chuyên gia đều phải tải vào SRAM/Tensor Core, làm mất lợi thế băng thông củaMoEvà chuyển hẳn sang cuộc chơiAI/ tính toán!
3) Thí nghiệm Kiểm chứng Có Đối chứng (WB-Ch21 Exp 1a, 1c, 1d)#
- Kích thước Mô hình & Lượng tử hóa Trọng số (
8B/32B/70B,BF16vsFP8vsB200):Llama3-8B-BF16(1x H100,14.96 GiB,49.04 GiBKV headroom):TTFT = 66.02 ms,TPOT = 7.29 ms(PASS). BảnFP8(7.48 GiB,56.52 GiBKV) đạt38.72 ms/4.37 ms.Qwen-32B-BF16(1x H100,61.02 GiB, chỉ còn2.98 GiBKV): Quét trọng số HBM đẩyTPOT = 27.58 ms— THẤT BẠI SLO<= 25 ms. Lượng tử hóa thành32B-FP8(30.51 GiB,33.49 GiBKV) kéoTTFT = 132.84 msvàTPOT = 15.23 ms(PASS); hoặc chuyển sangB200 SXM(180 GiBusable,8.0 TB/s) đưa32B-BF16vềTTFT = 118.39 ms/TPOT = 13.22 ms(102.98 GiBKV, PASS).Llama3-70B-BF16(2x H100 TP2,65.71 GiB/GPU): Quá tải cảTPOT = 35.93 ms,TTFT = 305.18 ms, và tràn ngưỡng dự trữ VRAM16 GiB(0.0 GiBKV!).70B-FP8 TP2(32.85 GiB/GPU,31.15 GiBKV) giải cứu thành công:TTFT = 173.72 ms,TPOT = 22.57 ms(PASS).
MoE(Mixtral-8x7B,46.701Btổng /12.748Bhoạt động) vsDense-47BCùng VRAM (46.635B,TP2):- Chiếm VRAM gần như y hệt (
43.49vs43.43 GiB/GPU), nhưng ởB = 1MoE 8x7BđạtTPOT = 8.61 ms(PASS) — nhanh hơn3.08xso vớiDense-47B(26.53 ms,FAIL)! Nhưng khi nâng lô lênB = 128, xác suất chạm gần hết8/8chuyên gia đẩyAI = 26.30 FLOP/BvàTPOT = 28.49 ms(> 25 ms), minh họa chính xác vùng hợp lý củaMoEdưới tải batch lớn.
- Chiếm VRAM gần như y hệt (
- Độ sâu vs Độ rộng (
Deep-Narrow L=64, d=4096vsShallow-Wide L=32, d=5120,TP2):Shallow-Wide (L=32, d=5120)cắt một nửa số rào đồng bộTP AllReducevà nhân khởi chạy CUDA \(\implies\)TTFT:56.65 msvs74.22 ms,TPOT:7.45 msvs11.16 ms(-33.24%), đồng thời cắt đúng2.0xdung lượngKV-cache(128.0vs256.0 KiB/tok).
- Tỷ lệ
SwiGLU& Bảng Từ vựng (32k tiedvs128k/256k untied):SwiGLU 8/3(6.688B,TPOT = 6.27 ms) thắngSwiGLU 4.0bị phình (8.835B,TPOT = 7.91 ms).- Sau khi sửa đúng mô hình (
input embeddingchỉ đọc 1 hàng \(O(d)\), chỉLM Headchạy GEMV \(V \times d\)):32k tied(0.131B,13.24 GiB,LM-head = 0.100 ms,TPOT = 6.99 ms),128k untied(1.051Btrong VRAM,14.96 GiB,0.402 ms,7.29 ms), và256k untied(2.097Btrong VRAM =23.11%,16.91 GiB,0.803 ms,TPOT = 7.69 ms). Việc tách bạch chứng minh từ vựng lớn tốn nặng VRAM khi untied (+3.67 GiBso với32k tied) nhưng ở bước decode chỉ tốn thêm băng thông 1 lần ma trận LM Head (+0.70 ms), không phải2x!
4) Quy tắc Ra quyết định Sản xuất (#19 Playbook)#
- Ưu tiên
FP8+Shallow-Widecho Suy luận Độ trễ Thấp: Đưa các mô hình dense sát ngưỡng băng thông (32B,70B) sangFP8để giải phóng50%băng thông HBM và gấp đôi headroom KV. - Khai thác
MoEỞ Ngưỡng Lô Nhỏ–Trung (B <= 32–64) hoặc BậtEPRộng (Ch 23): Không áp dụng kỳ vọngTPOTởB=1củaMoEchoB >= 128trên cùng số GPU nếu không có Expert Parallelism (EP) giảm số chuyên gia mỗi GPU. - Giữ Tỷ lệ
SwiGLU 8/3& Gắn Nhúng Hợp lý: Chỉ mở rộng từ vựng>= 128kkhi độ nén token đa ngôn ngữ/code bù được+2–4 GiBVRAM và+0.3–0.7 msởLM Head.
1.3 Chọn Kiến trúc Chú ý Cho Ngân sách Ngữ cảnh Dài 32k–1M (#30)#
1) Cơ chế Gốc & Tình huống Lỗi (#30)#
Trên một yêu cầu 128k hay 1M token, kẻ ngốn bộ nhớ HBM không còn là trọng số mô hình (15–30 GiB) mà là KV-cache tăng tuyến tính theo \(S \times B\). Dùng nguyên MHA cổ điển ở 128k biến cả H100 80 GiB thành máy chủ chỉ phục vụ được 0 yêu cầu vì nổ OOM ngay từ người dùng đầu tiên!
2) Mô hình Toán học Dung lượng KV-Cache Trên 5 Kiến trúc Chú ý#
Với \(L = 32, n_h = 32, d_h = 128\) chạy trên H100 80 GiB (chừa đồng nhất 48.0 GiB headroom KV-cache = 80.0 - 16.0 trọng số 8B - 16.0 GiB dự trữ hệ thống thống nhất), phương trình chính xác (b_kv = 2 cho BF16, 1 cho FP8):
MHA(\(n_{\text{kv}} = n_h = 32\)): \(\text{Bytes/tok}_{\text{MHA}} = 2 \cdot L \cdot n_h \cdot d_h \cdot b_{\text{kv}}\).GQA-8(\(n_{\text{kv}} = 8\)): \(\text{Bytes/tok}_{\text{GQA}} = 2 \cdot L \cdot n_{\text{kv}} \cdot d_h \cdot b_{\text{kv}}\).MQA(\(n_{\text{kv}} = 1\)): Giảm \(n_h\times\) bằng một đầu KV dùng chung.MLA(DeepSeek-V2/V3, \(d_c = 512, d_R = 64\)): Lưu vector nén ẩn \(c_t^{KV} \in \mathbb{R}^{512}\) cộng vector RoPE tách rời \(k_t^R \in \mathbb{R}^{64}\) và hấp thụ ma trận giải nén \(W_{UK}, W_{UV}\) vào \(W_Q, W_O\) khi suy luận:\[\text{Bytes/tok}_{\text{MLA}} = L \cdot (d_c + d_R) \cdot b_{\text{kv}}\]Hybrid SWA(\(W = 4096\), tỷ lệ cục bộ:toàn cục3:1trênGQA-8):\[\text{KV}_{\text{Hybrid}}(S) = \left(L_{\text{global}} \cdot S + L_{\text{local}} \cdot \min(S, W)\right) \cdot \left(2 \cdot n_{\text{kv}} \cdot d_h \cdot b_{\text{kv}}\right)\]
3) Thí nghiệm Kiểm chứng Phương trình 4k–1M (WB-Ch21 Exp 2)#
MHA BF16(512.0 KiB/tok):128ktốn64.00 GiB/chuỗi\(\implies\) NổOOM(0chuỗi đồng thời!);1Mđòi512.0 GiB/chuỗi.GQA-8 BF16(128.0 KiB/tok):16.00 GiBtại128k(3chuỗiBF16/6chuỗiFP8), nhưng tại1Mvẫn OOM (128 GiBBF16 /64 GiBFP8).MQA BF16(16.0 KiB/tok):2.00 GiBtại128k(24chuỗiBF16/48chuỗiFP8), nhưng đánh đổi độ biểu diễn chú ý.MLA BF16(36.0 KiB/tok): Nhỏ hơn14.22xso vớiMHA, chỉ4.50 GiB/chuỗiở128k(10chuỗiBF16,21chuỗiFP8 KV) và giữ toàn bộ biểu diễn32đầu tới1Mtoken (18.0 GiB/chuỗiởFP8\(\implies\)2chuỗi đồng thời)!Hybrid SWA BF16(24tầng cục bộW=4096+8tầng toàn cục): Tại128kchỉ tốn4.375 GiB/chuỗi(10chuỗiBF16/21chuỗiFP8), tại1M(FP8) chỉ tốn16.19 GiB/chuỗi(2chuỗi)! Trên32B TP2(L=64, n_h=40,96 GiBKV headroom),MHA 128k BF16đòi160.0 GiB(OOM) cònMLA(9.0 GiB) vàHybrid SWA(8.75 GiB) vẫn phục vụ10chuỗi đồng thời.
4) Quy tắc Ra quyết định Sản xuất (#30 Playbook)#
- Ngữ cảnh
>= 64k–1MNhiều Người dùng: Chọn kiến trúc hỗ trợMLA(DeepSeek) hoặcHybrid SWA(Gemma/Command), tuyệt đối tránhMHAcho cửa sổ>= 128ktrên cụm đơn/cặp GPU. - Nhân Đôi Mật độ Batch Bằng
FP8 KV-Cache: Bậtkv_cache_dtype="fp8"(kết hợp tách thang đoK/Vbất đối xứng ởCh 22) để giảm đúng2.0xdung lượng KV-cache mỗi token.
1.4 Ảo ảnh tokens/s Tổng hợp vs SLO Goodput Dưới Tải Poisson & Đột biến (#22)#
1) Cơ chế Gốc & Tình huống Lỗi (#22)#
Nhiều bảng điều khiển hiệu năng chỉ vẽ raw aggregate tokens/s, tạo ra ảo giác hệ thống càng quá tải thì càng đạt năng suất kỷ lục (5,751.7 tok/s), trong khi hàng đợi bên trong đã khiến mọi yêu cầu chờ tới 63.88 giây (TTFT) và người dùng thật đã hủy phiên từ lâu!
2) Mô hình Toán học SLO Goodput & Hàng đợi Đột biến (CV^2)#
SLO Goodput (\(G_{\text{SLO}}\)) chỉ đếm tốc độ hoàn thành của những yêu cầu thỏa ĐỒNG THỜI mọi hợp đồng chất lượng trong cửa sổ đo:
Theo công thức Pollaczek–Khinchine (\(W_q \propto \frac{1 + CV^2}{2}\)), phương sai khoảng cách đến giữa các yêu cầu làm trễ đuôi tăng theo cụm: tải Bursty Gamma (CV^2 = 4.0) chịu thành phần dao động \((1 + 4)/2 = 2.5\times\) so với Poisson (CV^2 = 1.0), khiến hàng đợi tích tụ và sụp đổ Goodput ở \(\lambda\) thấp hơn nhiều!
3) Thí nghiệm Kiểm chứng Mô phỏng 180s (WB-Ch21 Exp 3, seed=42)#
Quét tải \(\lambda \in [1.0, 11.0]\text{ req/s}\) trong bộ mô phỏng gom lô liên tục:
- Vùng ổn định (\(\lambda = 1.0 \to 5.0\text{ req/s}\)):
Poisson FIFOđạt1.023 -> 4.802 req/s(100.0%tuân thủ SLO,p99 TTFT <= 176.55 ms), trong khiBursty FIFO (CV^2=4.0)đã nhảyp99 TTFTlên gấp2.63x(464.31 mstại5.0 req/s). - Đỉnh năng lực (\(\lambda = 6.0\text{ req/s}\)):
Poissonchạm đỉnh5.535 req/s(93.78%,p99 TTFT = 358.69 ms,raw = 4,245.7 tok/s), cònBurstytụt đỉnh sớm tại4.728 req/s(83.93%). - Sụp đổ Khi Quá tải (\(\lambda = 7.5 \to 9.0 \to 11.0\text{ req/s}\)):
raw_total_tokens_per_sectiếp tục tăng tới đỉnh5,751.7 tok/s, nhưng hàng đợi FIFO vô hạn làmp99 TTFTnổ lên2,185.79 -> 20,355.01 -> 63,880.32 ms, kéoSLO Goodputrơi thẳng xuống0.000 req/s(0.035 req/strên Bursty)! - Cứu nguy Bằng
SLO-Aware Admission Control(admission_batch_cap=30,max_wait=300ms): Cổng nạp từ chối nhanh839trên2,029yêu cầu vượt ngưỡng ở11.0 req/s. Kết quả:100.0%yêu cầu tiếp nhận đạt cả hai SLO (p99 TTFT = 403.29 ms <= 500,p99 TPOT = 32.33 ms <= 35), giữ vữngSLO Goodput = 6.496 req/s!
4) Quy tắc Ra quyết định Sản xuất (#22 Playbook)#
- Nghiệm thu Hệ thống Bằng
SLO Goodput+ TảiBursty(CV^2 >= 4): Không bao giờ dùngraw tokens/sở một điểm quá tải hoặc tải Poisson đồng đều giả định để ký SLA với khách hàng. - Chặn Tắc Nghẽn Tại Cổng Nạp: Ước lượng thời gian chờ hàng đợi prefill trước khi nhận request; chủ động trả
HTTP 429hoặc điều hướng sang cụm tràn (spillover) để bảo vệ100%Goodput cho những yêu cầu đã nhận.
Trụ cột 2 — Kiến trúc Hệ thống & Cẩm nang Quyết định Sản xuất (Production Decision Playbook)#
Bài toán Thiết kế Phục vụ LLM |
Phương án Ngây thơ (Gây Sự cố / OOM / Vỡ SLO) | Phương án Chuẩn SOTA 2026 (Ch 21 + WB-Ch21) |
Liên thông Chặng Tiếp theo (Ch 22–Ch 23) |
|---|---|---|---|
Chọn Kích thước & Độ chính xác (#18) |
Triển khai 32B BF16 lên 1x H100 (TPOT = 27.58 ms > 25 ms) hoặc 70B BF16 TP2 (TTFT = 305.18 ms) |
Lượng tử hóa FP8 (32B-FP8: 15.23 ms TPOT; 70B-FP8 TP2: 22.57 ms) hoặc B200 (180 GiB usable, 8.0 TB/s) |
Kết hợp lượng tử hóa W4A16 AWQ/Marlin & FP8 (Ch 22) |
Đồng thiết kế Cấu trúc Khối (#19) |
Chọn Deep-Narrow (L=64, d=4096) + SwiGLU 4.0 + Dense 47B (26.53 ms TPOT) |
Chọn Shallow-Wide (L=32, d=5120) (-33.24% TPOT, 2x KV) + MoE 8x7B (8.61 ms, 3.08x ở B1) + SwiGLU 8/3 |
Bố trí TP/PP/EP theo rào AllReduce & EPLB (Ch 23) |
Chú ý Cho Ngữ cảnh 128k–1M (#30) |
Giữ MHA BF16 (64.0 GiB/chuỗi tại 128k \(\implies\) OOM 0 chuỗi trên 48 GiB) |
Chọn MLA (d_c=512+d_R=64) (4.50 GiB, 10/21 seqs) hoặc Hybrid SWA 3:1 (4.375 GiB) + FP8 KV |
Tối ưu khối nhớ với PagedAttention & RadixCache (Ch 22) |
Đo kiểm & Bảo vệ Quá tải (#22) |
Nghiệm thu theo raw tokens/s (5,752 tok/s) và để hàng đợi FIFO không giới hạn |
Đo đường cong SLO Goodput (TTFT & TPOT) qua cả Poisson & Bursty + bật Admission Control |
Giảm nhiễu P/D bằng Chunked Prefill & tách pha P/D (Ch 22) |
Trụ cột 3 — Công nghệ 2026 & Mã nguồn Python Độc lập (100% Khả thi Trong .venv)#
Đoạn mã dưới đây chạy độc lập hoàn toàn trong .venv (chỉ dùng numpy, pydantic và thư viện chuẩn Python), kiểm chứng trực tiếp ba bất biến cốt lõi của Chương 21: (1) Đường mái H100 BF16 (ridge = 295.22) chứng minh 32B BF16 vi phạm TPOT <= 25 ms trong khi 32B FP8 đạt chuẩn; (2) Phương trình bộ nhớ KV-Cache ở 128k chứng minh MHA BF16 nổ OOM (64.0 GiB > 48.0 GiB) trong khi MLA (4.50 GiB, nén 14.22x) và Hybrid SWA (4.375 GiB) mở khóa 10–21 chuỗi đồng thời; và (3) Mô phỏng rời rạc seed=42 chứng minh ảo ảnh raw tokens/s đối lập sụp đổ SLO Goodput -> 0 khi quá tải và vai trò giải cứu của Admission Control.
from __future__ import annotations
import numpy as np
from pydantic import BaseModel, ConfigDict, Field, ValidationError
GIB = 1024**3
class ServingBudgetAudit(BaseModel):
model_config = ConfigDict(extra="forbid")
h100_bf16_tflops: float = Field(default=989.0, gt=0.0)
h100_fp8_tflops: float = Field(default=1979.0, gt=0.0)
h100_bw_tb_s: float = Field(default=3.35, gt=0.0)
kv_headroom_gib: float = Field(default=48.0, gt=0.0)
ttft_slo_ms: float = Field(default=500.0, gt=0.0)
tpot_slo_ms: float = Field(default=35.0, gt=0.0)
def kv_cache_gib(kind: str, ctx: int, b_kv: int = 2) -> float:
n_layers, n_heads, n_kv, d_head = 32, 32, 8, 128
if kind == "mha":
total = ctx * (2 * n_layers * n_heads * d_head * b_kv)
elif kind == "gqa8":
total = ctx * (2 * n_layers * n_kv * d_head * b_kv)
elif kind == "mla":
total = ctx * (n_layers * (512 + 64) * b_kv)
else:
per_layer = 2 * n_kv * d_head * b_kv
total = (8 * ctx + 24 * min(ctx, 4096)) * per_layer
return total / GIB
def simulate_goodput_point(
lam: float, pattern: str, admission: bool, seed: int = 42
) -> tuple[float, float, float]:
rng = np.random.default_rng(seed)
horizon_s, k_shape = 180.0, 0.25
reqs: list[tuple[float, int, int]] = []
t = 0.0
while t < horizon_s:
gap = (
float(rng.exponential(1.0 / lam))
if pattern == "poisson"
else float(rng.gamma(k_shape, 1.0 / (lam * k_shape)))
)
t += gap
if t < horizon_s:
reqs.append((t, int(rng.integers(384, 769)), int(rng.integers(96, 193))))
idx, n_req, now_s, q_pref, rej = 0, len(reqs), 0.0, 0, 0
wait: list[tuple[float, int, int]] = []
active: list[list[float]] = []
done: list[tuple[float, float]] = []
toks = 0
def ingest(up_to: float) -> None:
nonlocal idx, q_pref, rej
while idx < n_req and reqs[idx][0] <= up_to:
arr, pt, ot = reqs[idx]
idx += 1
if admission:
est_w = (q_pref / 12_000.0) * 1000.0 + (pt / 12_000.0) * 1000.0
if est_w > 300.0 or len(active) >= 30:
rej += 1
continue
q_pref += pt
wait.append((arr, pt, ot))
while idx < n_req or wait or active:
ingest(now_s)
if not wait and not active:
now_s = reqs[idx][0]
ingest(now_s)
if wait and len(active) < 48:
arr, pt, ot = wait.pop(0)
q_pref -= pt
now_s += pt / 12_000.0
ingest(now_s)
toks += pt + 1
active.append([arr, float(ot), now_s, 1.0])
if active:
now_s += (12.0 + 0.28 * len(active)) / 1000.0
ingest(now_s)
toks += len(active)
nxt_active: list[list[float]] = []
for item in active:
item[3] += 1.0
if item[3] >= item[1]:
ttft = (item[2] - item[0]) * 1000.0
tpot = ((now_s - item[2]) * 1000.0) / max(1.0, item[1] - 1.0)
done.append((ttft, tpot))
else:
nxt_active.append(item)
active = nxt_active
span = max(horizon_s, now_s)
good = sum(1 for tt, tp in done if tt <= 500.0 and tp <= 35.0)
p99_ttft = float(np.percentile([tt for tt, _ in done], 99))
return round(good / span, 3), round(toks / span, 1), round(p99_ttft, 2)
def run_pillar3_llm_slo_demo() -> None:
cfg = ServingBudgetAudit()
ridge_bf16 = round(cfg.h100_bf16_tflops / cfg.h100_bw_tb_s, 2)
assert ridge_bf16 == 295.22
eff_bw = cfg.h100_bw_tb_s * 1e12 * 0.78
# Decode active GEMV params on 32B (non_emb + single LM head V*d, NOT 2*V*d!)
active_32b = 31.984e9
tpot_32b_bf16 = ((active_32b * 2) / eff_bw) * 1000.0 + 64 * 0.045
tpot_32b_fp8 = ((active_32b * 1) / eff_bw) * 1000.0 + 64 * 0.045
assert tpot_32b_bf16 > 25.0 and tpot_32b_fp8 < 25.0
print(f"[1. Roofline] H100 ridge={ridge_bf16} FLOP/B | 32B-BF16~{tpot_32b_bf16:.2f}ms (>25ms) vs FP8~{tpot_32b_fp8:.2f}ms")
mha_128k, mla_128k, swa_128k = kv_cache_gib("mha", 131_072), kv_cache_gib("mla", 131_072), kv_cache_gib("swa", 131_072)
assert mha_128k == 64.0 and mla_128k == 4.5 and swa_128k == 4.375
assert mha_128k > cfg.kv_headroom_gib and int(cfg.kv_headroom_gib // mla_128k) == 10
print(f"[2. KV 128k BF16] MHA={mha_128k} GiB (OOM) | MLA={mla_128k} GiB (10 seqs) | SWA={swa_128k} GiB (10 seqs)")
g_peak, raw_peak, _ = simulate_goodput_point(6.0, "poisson", False, seed=42)
g_ov, raw_ov, p99_ov = simulate_goodput_point(11.0, "poisson", False, seed=42)
g_adm, _, p99_adm = simulate_goodput_point(11.0, "bursty", True, seed=42)
assert g_peak > 5.0 and g_ov == 0.0 and raw_ov > raw_peak and g_adm > 5.5 and p99_adm < 500.0
print(f"[3. Goodput Mirage] Peak={g_peak} -> Overload={g_ov} req/s (Raw={raw_ov} tok/s, p99={p99_ov}ms) | Admission={g_adm} req/s (p99={p99_adm}ms)")
blocked = False
try:
ServingBudgetAudit.model_validate({"unknown_key": 1})
except ValidationError:
blocked = True
assert blocked is True
if __name__ == "__main__":
run_pillar3_llm_slo_demo()
print("Pillar 3 LLM Serving SLOs, Co-Design & Goodput Verification PASSED!")
Trụ cột 4 — Thực hành Công nghiệp (WB-Ch21: llm_slo_goodput_lab) & Kết quả Thực nghiệm#
4.1 Kiến trúc Hai Mô-đun WB-Ch21 (labs/ch21-llm-serving-slo-goodput-workbench/)#
src/llm_slo_goodput_lab/kv_attention_codesign.py:- Thực nghiệm 1 (
evaluate_model_codesign_suite, mô hình Roofline giải tích): Mô hình hóaTTFT,TPOT,E2EtrênH100 SXM(989 TFLOP/s BF16,3.35 TB/s, ridge295.22) vàB200 SXM(180 GiBusable /192 GiBvật lý,2,250 TFLOP/s,8.0 TB/s); táchEmbed Lookup1 hàng khỏiLM Head GEMV; thống nhất16.0 GiBdự trữ VRAM; kiểm chứng8B/32B/70B BF16 vs FP8,MoE 8x7BvsDense-47B,B = 1..768,Deep-NarrowvsShallow-Wide,SwiGLU 8/3vs4.0, vàVocab 32k..256k. - Thực nghiệm 2 (
analyze_kv_cache_landscape, phương trình KV chính xác): Giải chính xác dung lượngKV-cachechoMHA,GQA-8,MLA (d_c=512+d_R=64),Hybrid SWA (W=4096, 3:1)vàMQAtừ4ktới1Mtoken ở cảBF16vàFP8 KVtrên headroom48.0 GiB(H100 80 GiBvới16 GiBreserve) và96.0 GiB(32B TP2).
- Thực nghiệm 1 (
src/llm_slo_goodput_lab/slo_goodput_benchmark.py:- Thực nghiệm 3 (
run_goodput_mirage_comparison): Mô phỏng hàng đợi gom lô liên tục (180s,seed=42) quét \(\lambda \in \{1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.5, 9.0, 11.0\}\text{ req/s}\) quaPoisson FIFO,Bursty Gamma FIFO (CV^2=4.0), vàBursty + SLO-Aware Admission Control, kèmBoundedInMemorySpanExporter(maxlen=256)ghi5spanOpenTelemetrysạch bí mật.
- Thực nghiệm 3 (
4.2 Tóm tắt Kết quả Mô hình & Thực nghiệm (artifacts/t2_ch21_wb21_results.json, seed=42)#
Thực nghiệm (llm_slo_goodput_lab) |
Thông số Từ Mô hình Giải tích / DES (seed=42) |
Bất biến Kỹ thuật Được Chứng minh |
|---|---|---|
Exp 1a — Roofline Sizing, FP8 & MoE |
8B-BF16: TTFT=66.02ms, TPOT=7.29ms (PASS); 32B-BF16: TPOT=27.58ms (FAIL) vs 32B-FP8: 15.23ms (PASS); 70B-BF16 TP2: 305.18ms/35.93ms (FAIL) vs 70B-FP8: 173.72ms/22.57ms; MoE 8x7B (46.7B/12.75B): 8.61ms (3.08x vs Dense-47B 26.53ms); Shallow-Wide: -33.24% TPOT (7.45 vs 11.16ms) |
FP8 nhân đôi tốc độ decode memory-bound; MoE + Shallow-Wide cắt mạnh TPOT ở B=1 |
Exp 1b — Khớp Gối Batch AI (8B-BF16) |
B=1: 1.00 FLOP/B (7.19ms, 139.1 tok/s) \(\to\) B=256: 199.91 FLOP/B (8.83ms, 28,996.7 tok/s) \(\to\) B=384: 269.84 FLOP/B (compute_bound, 12.08ms) \(\to\) B=768: 22.73ms (33,793.4 tok/s) |
Gom lô dưới điểm gối tăng thông lượng gần tuyến tính mà hầu như không tăng TPOT |
Exp 2 — Phương trình KV-Cache (48 GiB) |
128k BF16: MHA = 64.0 GiB (OOM: 0 seqs), GQA-8 = 16.0 GiB (3), MLA = 4.50 GiB (10, 14.22x), Hybrid SWA = 4.375 GiB (10), MQA = 2.0 GiB (24); bật FP8 KV: MLA/SWA đạt 21 seqs ở 128k & 2 seqs ở 1M |
MHA bất khả thi ở ngữ cảnh dài; MLA và Hybrid SWA + FP8 mở khóa đa người dùng 128k–1M |
Exp 3 — Raw tokens/s vs SLO Goodput (DES) |
Poisson: đỉnh 5.535 req/s (6.0) \(\to\) 0.000 req/s (11.0, p99=63,880ms) dù Raw = 5,751.7 tok/s; Bursty: đỉnh 4.728 req/s (5.0 p99 gấp 2.63x Poisson); Bursty + Admission: 100.0% đạt SLO, 6.496 req/s (11.0), 5 OTel spans |
tokens/s tổng hợp che giấu thảm họa đuôi; cần SLO Goodput + Admission Control |
4.3 Quy trình Kiểm định Tự động (25/25 Test Cases Pass, 0 Skipped, 0 # type: ignore)#
cd 03-track-2-data-and-ai-engineering/part-04-ml-and-llm-serving-systems/labs/ch21-llm-serving-slo-goodput-workbench
PYTHONPATH=src python scripts/run_lab_demo.py --seed 42 --output artifacts/t2_ch21_wb21_results.json
ruff check src tests scripts
mypy --strict src tests
pytest -p no:cacheprovider -v
uv lock --check
Trụ cột 5 — Danh mục Tài liệu SOTA (7 Tài liệu) & Bài tập Chuyên sâu#
5.1 Tài liệu Đọc Kinh điển & Frontier 2024–2026#
- Williams, S., Waterman, A., & Patterson, D. (2009). Roofline: An Insightful Visual Performance Model for Multicore Architectures (
CACM). — Nền tảng toán học cho giới hạn compute-bound vs memory-bandwidth-bound và cường độ số học \(I^*\). - Pope, R. et al. (2023). Efficiently Scaling Transformer Inference (
MLSys). — Phân tích chính xác độ trễ decode, KV-cache, Batch AI knee và đánh đổi song song hóa tensor (TP). - Ainslie, J. et al. (2023). GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints (
EMNLP). — Thu hẹp \(n_{\text{kv}}\) để cắt bộ nhớ KV mà giữ chất lượng gầnMHA. - DeepSeek-AI (2024–2025). DeepSeek-V2 & DeepSeek-V3 Technical Reports: Multi-head Latent Attention (
MLA). — Nén vector KV ẩn \(d_c + d_R\) kết hợp hấp thụ ma trận suy luận. - Beltagy, I., Peters, M. E., & Cohan, A. (2020) & Google DeepMind (2025). Longformer / Gemma-2 & Gemma-3 Hybrid Sliding Window Attention (
Local:Global). — Khóa trần bộ nhớ KV trên đa số tầng cục bộ cho ngữ cảnh128k–1M. - Zhong, Y. et al. (2024). DistServe: Disaggregating Prefill and Decoding for Goodput-optimized Large Language Model Serving (
OSDI). — Định nghĩa chuẩn hóa SLO Goodput theo hai ràng buộc độc lậpTTFT&TPOT. - Agrawal, A. et al. (2024). Taming Throughput-Latency Tradeoff in LLM Inference with Sarathi-Serve (
OSDI). — Đo kiểmGoodputdưới vết tải thực tế và tránh nghẽn stall giữa prefill và decode.
5.2 Sáu Bài tập Tự luận & Thực hành (ex1 – ex6) Kèm Thang điểm (Grading Rubric)#
-
Bài tập 1 (
ex1, 15%) — Đường máiH100/B200(180 GiBUsable) & Khớp Gối Batch Size: Tính điểm gãy lý thuyết \(I^*_{\text{BF16}} = 295.22\) (eff = 208.17) củaH100 SXM, giải thích vì sao8B-BF16prefill (S_in=2048) cóAI = 1,941.08(compute_bound,TTFT=66.02ms) trong khi decodeB=1cóAI = 1.06(memory_bound,TPOT=7.29ms), giải thích điểm chuyển pha ởB=384(269.84 FLOP/B), và táchEmbed Lookup1 hàng khỏiLM Head GEMV(Tests 03, 05, 21, 24).Thang điểm: Đúng toán học ridge point & tách Embed/LM Head (
5%), đúng phân tích chuyển pha batchB=1..768(5%), passTests 03, 05, 21, 24(5%). -
Bài tập 2 (
ex2, 15%) — Đồng thiết kế Kích thước,FP8,MoE, Độ sâu vs Độ rộng & Từ vựng: Giải thích vì sao32B-BF16(27.58ms) và70B-BF16 TP2(35.93ms) trượtTPOT <= 25msvà được giải cứu bởiFP8(15.23msvà22.57ms) hayB200(180 GiBusable,13.22ms); chứng minh lợi thếMoE 8x7B(8.61msvsDense-47B26.53ms=3.08xở B1) vàShallow-Wide (L=32, d=5120)(-33.24%TPOT,2xít KV) cùngSwiGLU 8/3(Tests 04, 06–07, 25).Thang điểm: Đúng định lượng
32B/70B FP8&MoE(5%), đúng cơ chếTP AllReduce&SwiGLU 8/3(5%), passTests 04, 06–07, 25(5%). -
Bài tập 3 (
ex3, 20%) — Phương trìnhKV-CacheNgữ cảnh Dài4k–1M(MHA/GQA/MQA/MLA/Hybrid SWA): Viết tường minh cả 5 phương trình bộ nhớ KV, chứng minhMHA 128k BF16đòi64.0 GiB(nổOOMtrên headroom48 GiB), trong khiMLA(4.50 GiB,14.22x) vàHybrid SWA 3:1(4.375 GiB) phục vụ10chuỗiBF16/21chuỗiFP8tại128kvà2chuỗi ở1M(Tests 08–10, 20, 22).Thang điểm: Dẫn xuất đúng 5 phương trình (
7%), tính đúng dung lượng & ngưỡng OOM4k–1M(7%), passTests 08–10, 20, 22(6%). -
Bài tập 4 (
ex4, 20%) — Chứng minh Ảo ảnhtokens/s& Sụp đổSLO GoodputDưới Tải Quá ngưỡng: Phân tích kết quả quét \(\lambda = 1.0..11.0\text{ req/s}\) (seed=42): giải thích cơ chế khiếnraw_total_tokens_per_sectiếp tục tăng lên5,751.7 tok/strong khiPoisson SLO Goodputsụp đổ từ đỉnh5.535 req/svề0.000 req/s(p99 TTFT = 63,880 ms) (Tests 12, 15).Thang điểm: Đúng cơ chế tích tụ hàng đợi
M/G/1(7%), phân tích đúng nghịch lýraw tok/svsGoodput(7%), passTests 12, 15(6%). -
Bài tập 5 (
ex5, 15%) — So sánhPoissonvsBursty (CV^2 = 4.0)& Thiết kếAdmission Control: Dựa trên định lý Pollaczek–Khinchine, giải thích vì sao traffic đột biến cóp99 TTFTcao gấp2.63xở5.0 req/svà sụp đỉnh sớm hơn (4.728vs5.535 req/s), đồng thời chứng minh cơ chếdeadline sheddingbảo toàn100%tuân thủ SLO và giữGoodput = 6.496 req/sở tải11.0 req/s(Tests 13–14).Thang điểm: Đúng phân tích phương sai đột biến
CV^2(6%), đúng thiết kế cổng kiểm soát nạp (5%), passTests 13–14(4%). -
Bài tập 6 (
ex6, 15%) — Kiểm định Kỹ nghệ Phần mềm,Bounded OTel& Tính Tái lậpWB-Ch21: Kiểm tra toàn diện hợp đồng AST (0# type: ignore,0time.sleep,0pickle), cấu hìnhPydantic extra="forbid",5spanOpenTelemetrysạch bí mật, schemaworkbench_panels(6KPI,4bar,4table),ruff,mypy --strict,uv lock --checkvà25/25pytest pass (Tests 01–02, 17–19, 23–25).Thang điểm: Sạch kiểm định tĩnh & AST (
6%), đúng cấu trúc telemetry & artifact (5%), passTests 01–02, 17–19, 23–25(4%).
5.3 Tám Câu hỏi Trắc nghiệm Khái niệm (q1 – q8, Đồng bộ quiz_and_hints.json)#
- (
q1— Đường máiH100:Compute-Bound PrefillvsHBM-Bound Decode): TrênNVIDIA H100 SXM(989 TFLOP/s BF16,3.35 TB/s HBM3, ridge295.22 FLOP/B), vì sao pha prefillS_in = 2048củaLlama3-8B-BF16và pha decodeB = 1lại rơi vào hai miền hoàn toàn đối lập? - (
q2— Khớp Gối Batch SizeB=1..768): Khi tăng kích thước lô decodeBtrên8B-BF16(H100,S_ctx=128), điều gì xảy ra vớiTPOTvà thông lượngtokens/strước và sau điểm chuyển phacompute_boundtạiB = 384? - (
q3— Đồng thiết kế Kích thước Mô hình & Cứu nguyFP8): Vì saoQwen-32B-BF16(61.02 GiB) lọt gọn vào80 GiBVRAM của1x H100nhưng vẫn thất bại SLOTPOT <= 25 ms, và32B-FP8khắc phục thế nào? - (
q4—Depth vs Width,SwiGLU 8/3& Thuế Từ vựng): Ở cùng quy mô ~10Btham số trênTP2, vì saoShallow-Wide (L=32, d=5120)lại nhanh hơn và tiết kiệmKV-cachehơnDeep-Narrow (L=64, d=4096)? - (
q5— Phương trìnhKV-CacheỞ Ngữ cảnh128kTrên48 GiBHeadroom): Tại128ktoken (BF16 KV,L=32, n_h=32, d_h=128), sự khác biệt về dung lượngKV-cachemỗi chuỗi và số chuỗi đồng thời tối đa giữaMHAvàMLA (d_c=512+d_R=64)là gì? - (
q6—Hybrid SWA (W=4096, 3:1)& Lượng tử hóaFP8 KVĐến1MToken): Cơ chế nào giúpHybrid SWA (3:1)vàMLAkết hợpFP8 KVchạy được ngữ cảnh128k–1Mtrên đúng1x H100 (48 GiB KV)? - (
q7— Ảo ảnhtokens/sTổng hợp vsSLO Goodput): Trong mô phỏngWB-Ch21(Exp 3,seed=42) khi đẩy tảiPoisson FIFOlên11.0 req/s, vì saoraw_total_tokens_per_secđạt mức cao nhất (5,751.7 tok/s) trong khiSLO Goodputlại bằng0.000 req/s? - (
q8— Tải Đột biếnBursty (CV^2=4.0)&SLO-Aware Admission Control): So với dòngPoisson, dòngBurstyảnh hưởng ra sao đếnp99 TTFTvàGoodput, và kiểm soát nạp nhận thức SLO thay đổi kết cục ở tải11.0 req/snhư thế nào?
Exp 1 — Decode TPOT (ms) vs 25ms Budget Across Sizing & Precision
Exp 2 — KV-Cache Footprint per 128k Sequence (GiB, BF16 KV vs 48 GiB Budget)
Exp 2b — Max Concurrent 128k Sequences Inside 48 GiB Headroom (FP8 KV-Cache)
Exp 3 — Goodput Collapse at 11.0 req/s Overload vs Peak Capacity (req/s)
Exp 1a (Analytical Roofline) — Sizing, Precision, MoE & Co-Design
| model_config | weights_and_kv | ttft_and_tpot | slo_verdict |
|---|---|---|---|
| Llama3-8B-BF16 (1x H100) | 14.96 GiB/GPU (active 7.505B) | 128.0 KiB/tok | TTFT=66.02ms | TPOT=7.29ms | PASS |
| Llama3-8B-FP8 (1x H100) | 7.48 GiB/GPU (active 7.505B) | 64.0 KiB/tok | TTFT=38.72ms | TPOT=4.37ms | PASS |
| Qwen-32B-BF16 (1x H100) | 61.02 GiB/GPU (active 31.984B) | 256.0 KiB/tok | TTFT=252.92ms | TPOT=27.58ms | FAIL (Budget Breach) |
| Qwen-32B-FP8 (1x H100) | 30.51 GiB/GPU (active 31.984B) | 128.0 KiB/tok | TTFT=132.84ms | TPOT=15.23ms | PASS |
| Llama3-70B-BF16 (2x H100 TP2) | 65.71 GiB/GPU (active 69.502B) | 320.0 KiB/tok | TTFT=305.18ms | TPOT=35.93ms | FAIL (Budget Breach) |
| Llama3-70B-FP8 (2x H100 TP2) | 32.85 GiB/GPU (active 69.502B) | 160.0 KiB/tok | TTFT=173.72ms | TPOT=22.57ms | PASS |
| CoDesign-Deep-Narrow (L=64, d=4096, TP2) | 9.48 GiB/GPU (active 9.652B) | 256.0 KiB/tok | TTFT=74.22ms | TPOT=11.16ms | PASS |
| CoDesign-Shallow-Wide (L=32, d=5120, TP2) | 9.66 GiB/GPU (active 9.716B) | 128.0 KiB/tok | TTFT=56.65ms | TPOT=7.45ms | PASS |
| Mixtral-8x7B-MoE-BF16 (2x H100 TP2) | 43.49 GiB/GPU (active 12.748B) | 128.0 KiB/tok | TTFT=71.47ms | TPOT=8.61ms | PASS |
| Dense-47B-MatchedVRAM-BF16 (2x H100 TP2) | 43.43 GiB/GPU (active 46.439B) | 300.0 KiB/tok | TTFT=218.03ms | TPOT=26.53ms | FAIL (Budget Breach) |
Exp 1b — Decode Batch Arithmetic-Intensity Knee (8B-BF16, Ridge=295.22)
| batch_size | arithmetic_intensity | roofline_regime | tpot_and_throughput |
|---|---|---|---|
| B = 1 | 1.0 FLOP/B | memory_bound | 7.19 ms | 139.1 tok/s |
| B = 16 | 15.79 FLOP/B | memory_bound | 7.29 ms | 2,195.7 tok/s |
| B = 64 | 59.99 FLOP/B | memory_bound | 7.6 ms | 8,426.4 tok/s |
| B = 128 | 112.47 FLOP/B | memory_bound | 8.01 ms | 15,987.3 tok/s |
| B = 256 | 199.91 FLOP/B | memory_bound | 8.83 ms | 28,996.7 tok/s |
| B = 384 | 269.84 FLOP/B | compute_bound | 12.08 ms | 31,779.8 tok/s |
| B = 512 | 327.03 FLOP/B | compute_bound | 15.63 ms | 32,755.7 tok/s |
| B = 768 | 415.0 FLOP/B | compute_bound | 22.73 ms | 33,793.4 tok/s |
Exp 2 — Long-Context KV-Cache Equations (BF16 KV, 48 GiB Headroom)
| attention_arch | bytes_per_tok | gb_per_seq_128k_1m | max_batch_128k_bf16_fp8 |
|---|---|---|---|
| MHA (32 KV Heads) | 512.0 KiB/tok | 128k=64.0 GiB | 1M=512.0 GiB | BF16=0 | FP8=1 seqs |
| GQA-8 (8 KV Heads) | 128.0 KiB/tok | 128k=16.0 GiB | 1M=128.0 GiB | BF16=3 | FP8=6 seqs |
| MLA (d_c=512 + d_R=64) | 36.0 KiB/tok | 128k=4.5 GiB | 1M=36.0 GiB | BF16=10 | FP8=21 seqs |
| Hybrid SWA (W=4096, 3:1 GQA-8) | 35.0 KiB/tok | 128k=4.375 GiB | 1M=32.375 GiB | BF16=10 | FP8=21 seqs |
| MQA (1 KV Head) | 16.0 KiB/tok | 128k=2.0 GiB | 1M=16.0 GiB | BF16=24 | FP8=48 seqs |
Exp 3 — Raw Tokens/s Mirage vs SLO Goodput (500ms TTFT, 35ms TPOT)
| lambda_rps | poisson_goodput_and_p99 | bursty_goodput_and_p99 | admission_goodput_and_raw_tps |
|---|---|---|---|
| 1.0 req/s | 1.023 req/s (p99=89ms) | 0.877 req/s (p99=387ms) | 0.871 req/s | Raw=742 tok/s |
| 2.0 req/s | 1.956 req/s (p99=131ms) | 1.743 req/s (p99=396ms) | 1.737 req/s | Raw=1,415 tok/s |
| 3.0 req/s | 2.926 req/s (p99=145ms) | 2.715 req/s (p99=428ms) | 2.699 req/s | Raw=2,105 tok/s |
| 4.0 req/s | 3.875 req/s (p99=159ms) | 3.656 req/s (p99=435ms) | 3.623 req/s | Raw=2,782 tok/s |
| 5.0 req/s | 4.802 req/s (p99=177ms) | 4.573 req/s (p99=464ms) | 4.409 req/s | Raw=3,443 tok/s |
| 6.0 req/s | 5.535 req/s (p99=359ms) | 4.728 req/s (p99=1278ms) | 4.993 req/s | Raw=4,246 tok/s |
| 7.5 req/s | 3.092 req/s (p99=2186ms) | 2.898 req/s (p99=2805ms) | 5.742 req/s | Raw=5,306 tok/s |
| 9.0 req/s | 0.010 req/s (p99=20355ms) | 0.058 req/s (p99=23182ms) | 6.199 req/s | Raw=5,736 tok/s |
| 11.0 req/s | 0.000 req/s (p99=63880ms) | 0.035 req/s (p99=69764ms) | 6.496 req/s | Raw=5,752 tok/s |
03-track-2-data-and-ai-engineering/part-04-ml-and-llm-serving-systems/labs/ch21-llm-serving-slo-goodput-workbench
[build-system]
requires = ["setuptools>=68.0"]
build-backend = "setuptools.build_meta"
[project]
name = "llm-slo-goodput-lab"
version = "0.1.0"
description = "WB-Ch21: LLM Serving Latency Budgets (TTFT/TPOT Roofline), Model-System Co-Design, Long-Context KV-Cache Equations (MHA/MQA/GQA/MLA/Hybrid SWA), and Poisson vs Bursty SLO Goodput Benchmarking for T2-P4-U02."
readme = "README.md"
requires-python = ">=3.12"
dependencies = [
"numpy>=1.26",
"opentelemetry-sdk>=1.28",
"pydantic>=2.0",
]
[project.optional-dependencies]
dev = [
"hypothesis>=6.100",
"mypy>=1.11",
"pytest>=8.0",
"ruff>=0.6",
]
[project.scripts]
fsds-wb-ch21-slo-goodput = "llm_slo_goodput_lab.slo_goodput_benchmark:main"
[tool.setuptools]
package-dir = {"" = "src"}
[tool.setuptools.packages.find]
where = ["src"]
[tool.ruff]
target-version = "py312"
line-length = 105
[tool.ruff.lint]
select = ["E", "F", "I", "UP", "B", "RUF"]
[tool.mypy]
python_version = "3.12"
strict = true
warn_return_any = true
warn_unused_configs = true
disallow_untyped_defs = true
[[tool.mypy.overrides]]
module = [
"hypothesis",
"hypothesis.*",
]
ignore_missing_imports = true
[tool.pytest.ini_options]
testpaths = ["tests"]
pythonpath = ["src", "."]
addopts = "-v"
"""WB-Ch21: LLM Serving SLOs, Model-System Co-Design, KV-Cache & Goodput Workbench."""
from __future__ import annotations
from llm_slo_goodput_lab.kv_attention_codesign import (
AttentionSpec,
HardwareProfile,
ModelArchitectureSpec,
ServingBudgetSpec,
analyze_kv_cache_landscape,
compute_kv_cache_sequence_metrics,
evaluate_model_codesign_suite,
profile_prefill_and_decode_roofline,
)
from llm_slo_goodput_lab.slo_goodput_benchmark import (
BoundedInMemorySpanExporter,
GoodputSimConfig,
create_in_memory_telemetry,
run_goodput_mirage_comparison,
simulate_serving_queue_at_rate,
summarize_finished_spans,
)
__all__ = [
"AttentionSpec",
"BoundedInMemorySpanExporter",
"GoodputSimConfig",
"HardwareProfile",
"ModelArchitectureSpec",
"ServingBudgetSpec",
"analyze_kv_cache_landscape",
"compute_kv_cache_sequence_metrics",
"create_in_memory_telemetry",
"evaluate_model_codesign_suite",
"profile_prefill_and_decode_roofline",
"run_goodput_mirage_comparison",
"simulate_serving_queue_at_rate",
"summarize_finished_spans",
]
"""Exp 1 & Exp 2: LLM Serving Latency Roofline, Model Co-Design & Long-Context KV-Cache Equations."""
from __future__ import annotations
import math
from collections.abc import Sequence
from typing import Any, Literal
from pydantic import BaseModel, ConfigDict, Field
GIB_BYTES: int = 1024**3
KIB_BYTES: int = 1024
class HardwareProfile(BaseModel):
"""Strict hardware specification for GPU serving roofline analysis."""
model_config = ConfigDict(extra="forbid")
name: str
peak_bf16_tflops: float = Field(gt=0.0)
peak_fp8_tflops: float = Field(gt=0.0)
hbm_bw_tb_s: float = Field(gt=0.0)
vram_gib: float = Field(gt=0.0)
usable_vram_gib: float | None = Field(default=None, gt=0.0)
compute_eff: float = Field(default=0.55, gt=0.0, le=1.0)
bw_eff: float = Field(default=0.78, gt=0.0, le=1.0)
allreduce_decode_ms: float = Field(default=0.035, ge=0.0)
allreduce_prefill_ms: float = Field(default=0.18, ge=0.0)
layer_launch_ms: float = Field(default=0.045, ge=0.0)
tokenize_base_ms: float = Field(default=10.0, ge=0.0)
def effective_usable_vram_gib(self) -> float:
"""Usable HBM capacity after ECC/firmware/system allocation (e.g., 180 GiB on B200)."""
return self.usable_vram_gib if self.usable_vram_gib is not None else self.vram_gib
def ridge_point(self, precision: Literal["bf16", "fp8"]) -> float:
"""Theoretical arithmetic intensity ridge point (FLOPs/byte) before efficiency factors."""
peak = self.peak_bf16_tflops if precision == "bf16" else self.peak_fp8_tflops
return round(peak / self.hbm_bw_tb_s, 2)
def effective_ridge_point(self, precision: Literal["bf16", "fp8"]) -> float:
"""Achievable arithmetic intensity ridge point adjusted for MFU & HBM efficiency."""
peak = self.peak_bf16_tflops if precision == "bf16" else self.peak_fp8_tflops
return round((peak * self.compute_eff) / (self.hbm_bw_tb_s * self.bw_eff), 2)
H100_SXM = HardwareProfile(
name="NVIDIA-H100-SXM-80GB",
peak_bf16_tflops=989.0,
peak_fp8_tflops=1979.0,
hbm_bw_tb_s=3.35,
vram_gib=80.0,
usable_vram_gib=80.0,
)
B200_SXM = HardwareProfile(
name="NVIDIA-B200-SXM-192GB-180GiB-Usable",
peak_bf16_tflops=2250.0,
peak_fp8_tflops=4500.0,
hbm_bw_tb_s=8.00,
vram_gib=192.0,
usable_vram_gib=180.0,
)
class ModelArchitectureSpec(BaseModel):
"""Transformer (Dense or MoE) specification for serving-budget co-design."""
model_config = ConfigDict(extra="forbid")
model_id: str
n_layers: int = Field(ge=1, le=256)
d_model: int = Field(ge=256, le=32768)
n_heads: int = Field(ge=1, le=256)
n_kv_heads: int = Field(ge=1, le=256)
d_head: int = Field(ge=32, le=512)
ffn_hidden: int = Field(ge=256, le=131072)
vocab_size: int = Field(default=128_256, ge=1000, le=512_000)
tied_embeddings: bool = False
precision: Literal["bf16", "fp8"] = "bf16"
kv_precision: Literal["bf16", "fp8"] = "bf16"
tp_degree: int = Field(default=1, ge=1, le=16)
mfu_multiplier: float = Field(default=1.0, gt=0.2, le=1.5)
num_experts: int = Field(default=1, ge=1, le=512)
active_experts: int = Field(default=1, ge=1, le=64)
shared_expert_ffn_hidden: int = Field(default=0, ge=0, le=131_072)
def param_breakdown(self) -> dict[str, Any]:
"""Return VRAM total parameters vs active decode GEMV parameters (embedding lookup != GEMV)."""
q_out = self.n_heads * self.d_head
kv_out = self.n_kv_heads * self.d_head
attn_per_layer = (
self.d_model * q_out
+ 2 * self.d_model * kv_out
+ q_out * self.d_model
)
# SwiGLU uses 3 linear projections (gate, up, down) per expert
routed_active = min(self.active_experts, self.num_experts)
ffn_per_layer_total = 3 * self.d_model * (
self.num_experts * self.ffn_hidden + self.shared_expert_ffn_hidden
)
ffn_per_layer_active = 3 * self.d_model * (
routed_active * self.ffn_hidden + self.shared_expert_ffn_hidden
)
non_emb_params = self.n_layers * (attn_per_layer + ffn_per_layer_total)
active_non_emb_params = self.n_layers * (attn_per_layer + ffn_per_layer_active)
# VRAM holds both Input Embedding + LM Head when untied; 1-token decode only runs GEMV on LM Head
single_vocab_params = self.vocab_size * self.d_model
vocab_matrices = 1 if self.tied_embeddings else 2
vocab_params = vocab_matrices * single_vocab_params
total_params = non_emb_params + vocab_params
active_gemv_params = active_non_emb_params + single_vocab_params
bytes_per_weight = 2 if self.precision == "bf16" else 1
kv_bytes = 2 if self.kv_precision == "bf16" else 1
kv_bytes_per_token = 2 * self.n_layers * self.n_kv_heads * self.d_head * kv_bytes
return {
"non_emb_params": non_emb_params,
"active_non_emb_params": active_non_emb_params,
"single_vocab_params": single_vocab_params,
"vocab_params": vocab_params,
"total_params": total_params,
"active_gemv_params": active_gemv_params,
"total_params_b": round(total_params / 1e9, 3),
"active_params_b": round(active_gemv_params / 1e9, 3),
"is_moe": self.num_experts > 1,
"vocab_share_pct": round(100.0 * vocab_params / total_params, 2),
"weight_bytes_total": total_params * bytes_per_weight,
"active_weight_bytes_per_decode": active_gemv_params * bytes_per_weight,
"weight_gib_total": round((total_params * bytes_per_weight) / GIB_BYTES, 2),
"weight_gib_per_gpu": round(
(total_params * bytes_per_weight) / (self.tp_degree * GIB_BYTES), 2
),
"kv_bytes_per_token": kv_bytes_per_token,
"kv_kib_per_token": round(kv_bytes_per_token / KIB_BYTES, 2),
}
class ServingBudgetSpec(BaseModel):
"""Latency SLOs, reserved VRAM budget, and workload parameters for roofline profiling."""
model_config = ConfigDict(extra="forbid")
prompt_tokens: int = Field(default=2048, ge=64, le=1_048_576)
output_tokens: int = Field(default=256, ge=2, le=32_768)
decode_batch_size: int = Field(default=1, ge=1, le=2048)
ttft_budget_ms: float = Field(default=300.0, gt=0.0)
tpot_budget_ms: float = Field(default=25.0, gt=0.0)
reserved_vram_gib: float = Field(default=16.0, ge=0.0, le=64.0)
class AttentionSpec(BaseModel):
"""Long-context attention KV-cache specification across MHA/MQA/GQA/MLA/Hybrid-SWA."""
model_config = ConfigDict(extra="forbid")
arch_name: str
kind: Literal["mha", "gqa", "mqa", "mla", "hybrid_swa"]
n_layers: int = Field(default=32, ge=1, le=256)
n_query_heads: int = Field(default=32, ge=1, le=256)
n_kv_heads: int = Field(default=32, ge=1, le=256)
d_head: int = Field(default=128, ge=32, le=512)
mla_d_c: int = Field(default=512, ge=32, le=4096)
mla_d_r: int = Field(default=64, ge=16, le=512)
swa_window_tokens: int = Field(default=4096, ge=128, le=65_536)
swa_local_to_global_ratio: int = Field(default=3, ge=1, le=15)
def profile_prefill_and_decode_roofline(
model: ModelArchitectureSpec,
hw: HardwareProfile = H100_SXM,
budget: ServingBudgetSpec | None = None,
) -> dict[str, Any]:
"""Compute exact prefill TTFT, decode TPOT, E2E latency, arithmetic intensity & SLO pass."""
cfg = budget or ServingBudgetSpec()
p_info = model.param_breakdown()
non_emb = float(p_info["non_emb_params"])
active_non_emb = float(p_info["active_non_emb_params"])
active_gemv_params = float(p_info["active_gemv_params"])
vocab_params_single = float(p_info["single_vocab_params"])
w_byte_sz = 2 if model.precision == "bf16" else 1
w_bytes_per_gpu = float(p_info["weight_bytes_total"]) / model.tp_degree
kv_bytes_per_tok_per_gpu = float(p_info["kv_bytes_per_token"]) / model.tp_degree
peak_tflops = hw.peak_bf16_tflops if model.precision == "bf16" else hw.peak_fp8_tflops
eff_flops_per_s = peak_tflops * 1e12 * hw.compute_eff * model.mfu_multiplier * model.tp_degree
eff_bw_per_s = hw.hbm_bw_tb_s * 1e12 * hw.bw_eff * model.tp_degree
ridge = hw.ridge_point(model.precision)
eff_ridge = hw.effective_ridge_point(model.precision)
# --- Prefill Phase (B=1 prompt of length S_in) ---
s_in = float(cfg.prompt_tokens)
q_dim = float(model.n_heads * model.d_head)
prefill_linear_flops = 2.0 * active_non_emb * s_in + 2.0 * vocab_params_single
# Causal self-attention QK^T + AV over lower triangle (~0.5 * 4 * L * q_dim * S^2)
prefill_attn_flops = 2.0 * model.n_layers * q_dim * (s_in**2)
prefill_flops = prefill_linear_flops + prefill_attn_flops
prefill_embed_lookup_bytes = min(
float(vocab_params_single * w_byte_sz),
s_in * float(model.d_model * w_byte_sz),
)
prefill_bytes = (
(non_emb + vocab_params_single) * float(w_byte_sz)
+ prefill_embed_lookup_bytes
+ s_in * float(p_info["kv_bytes_per_token"])
)
prefill_ai = prefill_flops / prefill_bytes
t_prefill_compute_ms = (prefill_flops / eff_flops_per_s) * 1000.0
t_prefill_mem_ms = (prefill_bytes / eff_bw_per_s) * 1000.0
tp_ar_prefill_ms = (
(2.0 * model.n_layers * hw.allreduce_prefill_ms) if model.tp_degree > 1 else 0.0
)
launch_ms = model.n_layers * hw.layer_launch_ms
ttft_ms = (
max(t_prefill_compute_ms, t_prefill_mem_ms)
+ tp_ar_prefill_ms
+ launch_ms
+ hw.tokenize_base_ms
)
prefill_regime = "compute_bound" if t_prefill_compute_ms >= t_prefill_mem_ms else "memory_bound"
# --- Decode Phase (batch B at context S_ctx = S_in + S_out/2) ---
# Input embedding only gathers B rows (O(B * d) bytes); only LM Head (V x d) runs dense GEMV.
b_dec = float(cfg.decode_batch_size)
s_ctx = float(cfg.prompt_tokens) + 0.5 * float(cfg.output_tokens)
decode_flops = b_dec * (2.0 * active_gemv_params + 4.0 * model.n_layers * q_dim * s_ctx)
embed_lookup_bytes = b_dec * float(model.d_model * w_byte_sz)
if model.num_experts > 1:
routed_per_layer = float(3 * model.d_model * model.num_experts * model.ffn_hidden)
routed_k = min(model.active_experts, model.num_experts)
routed_frac = 1.0 - (1.0 - float(routed_k) / float(model.num_experts)) ** b_dec
routed_bytes = float(model.n_layers) * routed_per_layer * routed_frac * float(w_byte_sz)
fixed_active_non_emb = active_non_emb - float(
model.n_layers * 3 * model.d_model * routed_k * model.ffn_hidden
)
decode_weight_bytes = (
(fixed_active_non_emb + vocab_params_single) * float(w_byte_sz) + routed_bytes
)
else:
decode_weight_bytes = float(p_info["active_weight_bytes_per_decode"])
decode_bytes = decode_weight_bytes + embed_lookup_bytes + b_dec * s_ctx * float(
p_info["kv_bytes_per_token"]
)
decode_ai = decode_flops / decode_bytes
t_decode_compute_ms = (decode_flops / eff_flops_per_s) * 1000.0
t_decode_mem_ms = (decode_bytes / eff_bw_per_s) * 1000.0
tp_ar_decode_ms = (
(2.0 * model.n_layers * hw.allreduce_decode_ms) if model.tp_degree > 1 else 0.0
)
tpot_ms = max(t_decode_compute_ms, t_decode_mem_ms) + tp_ar_decode_ms + launch_ms
decode_regime = "compute_bound" if t_decode_compute_ms >= t_decode_mem_ms else "memory_bound"
e2e_ms = ttft_ms + max(0, cfg.output_tokens - 1) * tpot_ms
decode_tps = (b_dec * 1000.0) / tpot_ms
# LM-head per-step dense GEMV cost (single matrix V x d_model)
lm_head_bytes = float(model.vocab_size * model.d_model * w_byte_sz)
lm_head_ms = (lm_head_bytes / eff_bw_per_s) * 1000.0
usable_vram_gib = hw.effective_usable_vram_gib()
weight_gib_per_gpu = w_bytes_per_gpu / GIB_BYTES
kv_headroom_gib_per_gpu = max(
0.0, usable_vram_gib - weight_gib_per_gpu - cfg.reserved_vram_gib
)
passes_ttft = ttft_ms <= cfg.ttft_budget_ms
passes_tpot = tpot_ms <= cfg.tpot_budget_ms
passes_vram = (weight_gib_per_gpu + cfg.reserved_vram_gib) <= usable_vram_gib
passes_both = passes_ttft and passes_tpot and passes_vram
return {
"metric_origin": "analytical_roofline_equations",
"model_id": model.model_id,
"hardware": hw.name,
"tp_degree": model.tp_degree,
"precision": model.precision,
"kv_precision": model.kv_precision,
"total_params_b": p_info["total_params_b"],
"active_params_b": p_info["active_params_b"],
"is_moe": p_info["is_moe"],
"usable_vram_gib": usable_vram_gib,
"reserved_vram_gib": cfg.reserved_vram_gib,
"weight_gib_per_gpu": round(weight_gib_per_gpu, 2),
"kv_headroom_gib_per_gpu": round(kv_headroom_gib_per_gpu, 2),
"kv_kib_per_token_total": p_info["kv_kib_per_token"],
"kv_bytes_per_token_per_gpu": int(kv_bytes_per_tok_per_gpu),
"vocab_params_b": round(p_info["vocab_params"] / 1e9, 3),
"vocab_share_pct": p_info["vocab_share_pct"],
"lm_head_step_ms": round(lm_head_ms, 3),
"ridge_point_flop_per_byte": ridge,
"effective_ridge_point_flop_per_byte": eff_ridge,
"prefill_ai_flop_per_byte": round(prefill_ai, 2),
"prefill_regime": prefill_regime,
"prefill_compute_ms": round(t_prefill_compute_ms, 2),
"prefill_mem_ms": round(t_prefill_mem_ms, 2),
"ttft_ms": round(ttft_ms, 2),
"decode_ai_flop_per_byte": round(decode_ai, 2),
"decode_regime": decode_regime,
"decode_compute_ms": round(t_decode_compute_ms, 2),
"decode_mem_ms": round(t_decode_mem_ms, 2),
"tp_allreduce_decode_ms": round(tp_ar_decode_ms, 2),
"tpot_ms": round(tpot_ms, 2),
"e2e_ms": round(e2e_ms, 2),
"decode_tokens_per_sec": round(decode_tps, 1),
"passes_ttft_budget": passes_ttft,
"passes_tpot_budget": passes_tpot,
"passes_all_slos": passes_both,
}
def build_default_model_catalog() -> dict[str, ModelArchitectureSpec]:
"""Return canonical serving-budget comparison models (8B/32B/70B + co-design ablations)."""
return {
"8b_bf16": ModelArchitectureSpec(
model_id="Llama3-8B-BF16 (1x H100)",
n_layers=32,
d_model=4096,
n_heads=32,
n_kv_heads=8,
d_head=128,
ffn_hidden=14336,
vocab_size=128_256,
precision="bf16",
kv_precision="bf16",
tp_degree=1,
),
"8b_fp8": ModelArchitectureSpec(
model_id="Llama3-8B-FP8 (1x H100)",
n_layers=32,
d_model=4096,
n_heads=32,
n_kv_heads=8,
d_head=128,
ffn_hidden=14336,
vocab_size=128_256,
precision="fp8",
kv_precision="fp8",
tp_degree=1,
),
"32b_bf16": ModelArchitectureSpec(
model_id="Qwen-32B-BF16 (1x H100)",
n_layers=64,
d_model=5120,
n_heads=40,
n_kv_heads=8,
d_head=128,
ffn_hidden=27648,
vocab_size=151_936,
precision="bf16",
kv_precision="bf16",
tp_degree=1,
),
"32b_fp8": ModelArchitectureSpec(
model_id="Qwen-32B-FP8 (1x H100)",
n_layers=64,
d_model=5120,
n_heads=40,
n_kv_heads=8,
d_head=128,
ffn_hidden=27648,
vocab_size=151_936,
precision="fp8",
kv_precision="fp8",
tp_degree=1,
),
"70b_bf16_tp2": ModelArchitectureSpec(
model_id="Llama3-70B-BF16 (2x H100 TP2)",
n_layers=80,
d_model=8192,
n_heads=64,
n_kv_heads=8,
d_head=128,
ffn_hidden=28672,
vocab_size=128_256,
precision="bf16",
kv_precision="bf16",
tp_degree=2,
),
"70b_fp8_tp2": ModelArchitectureSpec(
model_id="Llama3-70B-FP8 (2x H100 TP2)",
n_layers=80,
d_model=8192,
n_heads=64,
n_kv_heads=8,
d_head=128,
ffn_hidden=28672,
vocab_size=128_256,
precision="fp8",
kv_precision="fp8",
tp_degree=2,
),
"deep_narrow_9b": ModelArchitectureSpec(
model_id="CoDesign-Deep-Narrow (L=64, d=4096, TP2)",
n_layers=64,
d_model=4096,
n_heads=32,
n_kv_heads=8,
d_head=128,
ffn_hidden=8192,
vocab_size=128_256,
precision="bf16",
kv_precision="bf16",
tp_degree=2,
mfu_multiplier=0.95,
),
"shallow_wide_9b": ModelArchitectureSpec(
model_id="CoDesign-Shallow-Wide (L=32, d=5120, TP2)",
n_layers=32,
d_model=5120,
n_heads=40,
n_kv_heads=8,
d_head=128,
ffn_hidden=14336,
vocab_size=128_256,
precision="bf16",
kv_precision="bf16",
tp_degree=2,
mfu_multiplier=1.05,
),
"moe_8x7b_bf16_tp2": ModelArchitectureSpec(
model_id="Mixtral-8x7B-MoE-BF16 (2x H100 TP2)",
n_layers=32,
d_model=4096,
n_heads=32,
n_kv_heads=8,
d_head=128,
ffn_hidden=14336,
vocab_size=32_000,
precision="bf16",
kv_precision="bf16",
tp_degree=2,
num_experts=8,
active_experts=2,
),
"dense_47b_bf16_tp2": ModelArchitectureSpec(
model_id="Dense-47B-MatchedVRAM-BF16 (2x H100 TP2)",
n_layers=75,
d_model=6144,
n_heads=48,
n_kv_heads=8,
d_head=128,
ffn_hidden=28672,
vocab_size=32_000,
precision="bf16",
kv_precision="bf16",
tp_degree=2,
),
}
def evaluate_model_codesign_suite(
hw: HardwareProfile = H100_SXM,
budget: ServingBudgetSpec | None = None,
) -> dict[str, Any]:
"""Run Exp 1: Sizing/Precision roofline, Batch AI knee, Depth/Width, MoE, FFN & Vocab."""
cfg = budget or ServingBudgetSpec()
catalog = build_default_model_catalog()
# 1a. Model sizing & quantization compliance against TTFT<=300ms, TPOT<=25ms
sizing_keys = ("8b_bf16", "8b_fp8", "32b_bf16", "32b_fp8", "70b_bf16_tp2", "70b_fp8_tp2")
sizing_comparison = [
profile_prefill_and_decode_roofline(catalog[k], hw=hw, budget=cfg) for k in sizing_keys
]
b200_32b_bf16 = profile_prefill_and_decode_roofline(catalog["32b_bf16"], hw=B200_SXM, budget=cfg)
moe_b1 = profile_prefill_and_decode_roofline(catalog["moe_8x7b_bf16_tp2"], hw=hw, budget=cfg)
moe_b128 = profile_prefill_and_decode_roofline(
catalog["moe_8x7b_bf16_tp2"],
hw=hw,
budget=ServingBudgetSpec(
prompt_tokens=cfg.prompt_tokens,
output_tokens=cfg.output_tokens,
decode_batch_size=128,
ttft_budget_ms=cfg.ttft_budget_ms,
tpot_budget_ms=cfg.tpot_budget_ms,
reserved_vram_gib=cfg.reserved_vram_gib,
),
)
dense_matched = profile_prefill_and_decode_roofline(
catalog["dense_47b_bf16_tp2"], hw=hw, budget=cfg
)
# 1b. Batch-size arithmetic-intensity knee sweep on 8B-BF16 (H100, S_ctx=128)
batch_sweep: list[dict[str, Any]] = []
for b_sz in (1, 4, 16, 32, 64, 128, 256, 384, 512, 768):
row = profile_prefill_and_decode_roofline(
catalog["8b_bf16"],
hw=hw,
budget=ServingBudgetSpec(
prompt_tokens=64,
output_tokens=128,
decode_batch_size=b_sz,
ttft_budget_ms=cfg.ttft_budget_ms,
tpot_budget_ms=cfg.tpot_budget_ms,
),
)
batch_sweep.append(
{
"batch_size": b_sz,
"decode_ai_flop_per_byte": row["decode_ai_flop_per_byte"],
"ridge_point": row["ridge_point_flop_per_byte"],
"decode_regime": row["decode_regime"],
"tpot_ms": row["tpot_ms"],
"decode_tokens_per_sec": row["decode_tokens_per_sec"],
"passes_tpot_budget": row["passes_tpot_budget"],
}
)
# 1c. Depth vs. Width co-design (matched ~9.1B non-emb params on TP2)
deep_res = profile_prefill_and_decode_roofline(catalog["deep_narrow_9b"], hw=hw, budget=cfg)
wide_res = profile_prefill_and_decode_roofline(catalog["shallow_wide_9b"], hw=hw, budget=cfg)
# 1d. SwiGLU FFN ratio (8/3 vs 4.0 bloat) & Vocabulary size (32k tied vs 128k vs 256k untied)
ffn_8_3 = ModelArchitectureSpec(
model_id="SwiGLU-8/3-Optimal (d=4096, d_ffn=10922)",
n_layers=32,
d_model=4096,
n_heads=32,
n_kv_heads=8,
d_head=128,
ffn_hidden=10922,
vocab_size=128_256,
)
ffn_4_0 = ModelArchitectureSpec(
model_id="SwiGLU-4x-Bloated (d=4096, d_ffn=16384)",
n_layers=32,
d_model=4096,
n_heads=32,
n_kv_heads=8,
d_head=128,
ffn_hidden=16384,
vocab_size=128_256,
)
ffn_ablation = {
"swiglu_8_over_3": profile_prefill_and_decode_roofline(ffn_8_3, hw=hw, budget=cfg),
"swiglu_4_0_bloated": profile_prefill_and_decode_roofline(ffn_4_0, hw=hw, budget=cfg),
}
vocab_ablation: list[dict[str, Any]] = []
for v_name, v_sz, tied in (
("32k_tied", 32_000, True),
("128k_untied", 128_256, False),
("256k_untied", 256_000, False),
):
m_v = ModelArchitectureSpec(
model_id=f"8B-{v_name}",
n_layers=32,
d_model=4096,
n_heads=32,
n_kv_heads=8,
d_head=128,
ffn_hidden=14336,
vocab_size=v_sz,
tied_embeddings=tied,
)
r_v = profile_prefill_and_decode_roofline(m_v, hw=hw, budget=cfg)
vocab_ablation.append(
{
"variant": v_name,
"vocab_size": v_sz,
"tied_embeddings": tied,
"vocab_params_b": r_v["vocab_params_b"],
"vocab_share_pct": r_v["vocab_share_pct"],
"weight_gib_per_gpu": r_v["weight_gib_per_gpu"],
"lm_head_step_ms": r_v["lm_head_step_ms"],
"tpot_ms": r_v["tpot_ms"],
}
)
return {
"metric_origin": "analytical_roofline_equations",
"hardware": hw.model_dump(),
"b200_reference": B200_SXM.model_dump(),
"budget": cfg.model_dump(),
"ridge_point_h100_bf16": hw.ridge_point("bf16"),
"ridge_point_h100_fp8": hw.ridge_point("fp8"),
"ridge_point_b200_bf16": B200_SXM.ridge_point("bf16"),
"sizing_comparison": sizing_comparison,
"b200_32b_bf16_comparison": b200_32b_bf16,
"moe_codesign_comparison": {
"moe_8x7b_b1": moe_b1,
"moe_8x7b_b128": moe_b128,
"dense_47b_matched_vram_b1": dense_matched,
"b1_tpot_speedup_vs_dense_x": round(
dense_matched["tpot_ms"] / moe_b1["tpot_ms"], 2
),
},
"batch_ai_knee_sweep_8b_bf16": batch_sweep,
"depth_vs_width": {
"deep_narrow_64x4096": deep_res,
"shallow_wide_32x5120": wide_res,
"tpot_speedup_pct": round(
100.0 * (deep_res["tpot_ms"] - wide_res["tpot_ms"]) / deep_res["tpot_ms"], 2
),
"kv_cache_reduction_x": round(
deep_res["kv_kib_per_token_total"] / wide_res["kv_kib_per_token_total"], 2
),
},
"ffn_ablation": ffn_ablation,
"vocab_ablation": vocab_ablation,
}
def compute_kv_cache_sequence_metrics(
spec: AttentionSpec,
context_length: int,
kv_precision: Literal["bf16", "fp8"] = "bf16",
kv_headroom_gib: float = 48.0,
) -> dict[str, Any]:
"""Compute exact KV-cache bytes, GiB/sequence, OOM status, and max batch concurrency."""
if context_length <= 0:
raise ValueError("context_length must be > 0")
if kv_headroom_gib <= 0.0:
raise ValueError("kv_headroom_gib must be > 0")
b_kv = 2 if kv_precision == "bf16" else 1
if spec.kind == "mha":
bytes_per_tok = 2 * spec.n_layers * spec.n_query_heads * spec.d_head * b_kv
total_kv_bytes = context_length * bytes_per_tok
elif spec.kind == "gqa":
bytes_per_tok = 2 * spec.n_layers * spec.n_kv_heads * spec.d_head * b_kv
total_kv_bytes = context_length * bytes_per_tok
elif spec.kind == "mqa":
bytes_per_tok = 2 * spec.n_layers * 1 * spec.d_head * b_kv
total_kv_bytes = context_length * bytes_per_tok
elif spec.kind == "mla":
# DeepSeek-V2/V3 Multi-head Latent Attention stores only compressed c_KV (d_c) + k_R (d_R)
bytes_per_tok = spec.n_layers * (spec.mla_d_c + spec.mla_d_r) * b_kv
total_kv_bytes = context_length * bytes_per_tok
else:
# Hybrid Sliding Window Attention: ratio local (capped at W) per 1 global layer on GQA KV
cycle = spec.swa_local_to_global_ratio + 1
n_global = max(1, spec.n_layers // cycle)
n_local = spec.n_layers - n_global
per_layer_tok_bytes = 2 * spec.n_kv_heads * spec.d_head * b_kv
eff_local_ctx = min(context_length, spec.swa_window_tokens)
total_kv_bytes = (n_global * context_length + n_local * eff_local_ctx) * per_layer_tok_bytes
bytes_per_tok = round(total_kv_bytes / context_length)
gb_per_seq = total_kv_bytes / GIB_BYTES
max_batch = math.floor(kv_headroom_gib / gb_per_seq) if gb_per_seq > 0 else 0
return {
"arch_name": spec.arch_name,
"kind": spec.kind,
"context_length": context_length,
"kv_precision": kv_precision,
"kv_headroom_gib": kv_headroom_gib,
"effective_bytes_per_token": int(bytes_per_tok),
"effective_kib_per_token": round(bytes_per_tok / KIB_BYTES, 2),
"gib_per_sequence": round(gb_per_seq, 4),
"max_concurrent_sequences": int(max_batch),
"oom_single_sequence": gb_per_seq > kv_headroom_gib,
}
def build_default_attention_catalog(n_layers: int = 32, n_heads: int = 32) -> list[AttentionSpec]:
"""Return canonical 5 attention architectures for long-context KV-cache comparison."""
return [
AttentionSpec(
arch_name="MHA (32 KV Heads)",
kind="mha",
n_layers=n_layers,
n_query_heads=n_heads,
n_kv_heads=n_heads,
d_head=128,
),
AttentionSpec(
arch_name="GQA-8 (8 KV Heads)",
kind="gqa",
n_layers=n_layers,
n_query_heads=n_heads,
n_kv_heads=8,
d_head=128,
),
AttentionSpec(
arch_name="MLA (d_c=512 + d_R=64)",
kind="mla",
n_layers=n_layers,
n_query_heads=n_heads,
n_kv_heads=n_heads,
d_head=128,
mla_d_c=512,
mla_d_r=64,
),
AttentionSpec(
arch_name="Hybrid SWA (W=4096, 3:1 GQA-8)",
kind="hybrid_swa",
n_layers=n_layers,
n_query_heads=n_heads,
n_kv_heads=8,
d_head=128,
swa_window_tokens=4096,
swa_local_to_global_ratio=3,
),
AttentionSpec(
arch_name="MQA (1 KV Head)",
kind="mqa",
n_layers=n_layers,
n_query_heads=n_heads,
n_kv_heads=1,
d_head=128,
),
]
def analyze_kv_cache_landscape(
kv_headroom_gib: float = 48.0,
context_lengths: Sequence[int] = (4096, 32_768, 131_072, 1_048_576),
reserved_vram_gib: float = 16.0,
) -> dict[str, Any]:
"""Run Exp 2: Analytical KV-cache equations across 4k..1M tokens in BF16 & FP8 on H100 80GB."""
specs_8b = build_default_attention_catalog(n_layers=32, n_heads=32)
rows: list[dict[str, Any]] = []
for prec in ("bf16", "fp8"):
prec_lit: Literal["bf16", "fp8"] = "bf16" if prec == "bf16" else "fp8"
for ctx in context_lengths:
mha_ref = compute_kv_cache_sequence_metrics(
specs_8b[0], context_length=ctx, kv_precision=prec_lit, kv_headroom_gib=kv_headroom_gib
)
mha_gib = mha_ref["gib_per_sequence"]
for sp in specs_8b:
m = compute_kv_cache_sequence_metrics(
sp, context_length=ctx, kv_precision=prec_lit, kv_headroom_gib=kv_headroom_gib
)
m["compression_vs_mha_x"] = round(mha_gib / m["gib_per_sequence"], 2)
rows.append(m)
# Also compute 32B TP2 (L=64, n_h=40, 96 GiB KV headroom = 48 GiB/GPU) at 32k & 128k BF16
specs_32b = build_default_attention_catalog(n_layers=64, n_heads=40)
tp2_32b_rows: list[dict[str, Any]] = []
for ctx in (32_768, 131_072):
for sp in specs_32b:
tp2_32b_rows.append(
compute_kv_cache_sequence_metrics(
sp, context_length=ctx, kv_precision="bf16", kv_headroom_gib=96.0
)
)
def _find(prec: str, ctx: int, kind: str) -> dict[str, Any]:
return next(
r
for r in rows
if r["kv_precision"] == prec and r["context_length"] == ctx and r["kind"] == kind
)
return {
"metric_origin": "analytical_exact_kv_equations",
"reference_hardware": (
f"NVIDIA-H100-SXM-80GB (16 GiB reserve + ~16 GiB 8B-BF16 weights -> "
f"{kv_headroom_gib:.1f} GiB KV headroom)"
),
"reserved_vram_gib": reserved_vram_gib,
"kv_headroom_gib": kv_headroom_gib,
"context_lengths": list(context_lengths),
"matrix": rows,
"highlights_128k_bf16": {
"mha": _find("bf16", 131_072, "mha"),
"gqa_8": _find("bf16", 131_072, "gqa"),
"mla": _find("bf16", 131_072, "mla"),
"hybrid_swa": _find("bf16", 131_072, "hybrid_swa"),
"mqa": _find("bf16", 131_072, "mqa"),
},
"highlights_128k_fp8": {
"mha": _find("fp8", 131_072, "mha"),
"gqa_8": _find("fp8", 131_072, "gqa"),
"mla": _find("fp8", 131_072, "mla"),
"hybrid_swa": _find("fp8", 131_072, "hybrid_swa"),
"mqa": _find("fp8", 131_072, "mqa"),
},
"highlights_1m_fp8": {
"mha": _find("fp8", 1_048_576, "mha"),
"gqa_8": _find("fp8", 1_048_576, "gqa"),
"mla": _find("fp8", 1_048_576, "mla"),
"hybrid_swa": _find("fp8", 1_048_576, "hybrid_swa"),
"mqa": _find("fp8", 1_048_576, "mqa"),
},
"tp2_32b_bf16_96gib_headroom": tp2_32b_rows,
}
"""Exp 3: Aggregate Tokens/s Mirage vs SLO Goodput (Poisson & Bursty Arrivals + Admission Control)."""
from __future__ import annotations
import heapq
import threading
from collections import deque
from collections.abc import Sequence
from typing import Any, Literal
import numpy as np
from opentelemetry import trace
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import ReadableSpan, TracerProvider
from opentelemetry.sdk.trace.export import SimpleSpanProcessor, SpanExporter, SpanExportResult
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
from pydantic import BaseModel, ConfigDict, Field
class GoodputSimConfig(BaseModel):
"""Strict configuration for deterministic discrete-event LLM serving Goodput benchmark."""
model_config = ConfigDict(extra="forbid")
seed: int = Field(default=42, ge=0)
sim_duration_s: float = Field(default=180.0, ge=20.0, le=600.0)
max_batch_slots: int = Field(default=48, ge=4, le=512)
prefill_tok_per_s: float = Field(default=12_000.0, gt=500.0)
base_decode_step_ms: float = Field(default=12.0, gt=0.5)
per_slot_decode_ms: float = Field(default=0.28, ge=0.0)
ttft_slo_ms: float = Field(default=500.0, gt=10.0)
tpot_slo_ms: float = Field(default=35.0, gt=1.0)
compliance_target_pct: float = Field(default=95.0, ge=50.0, le=100.0)
admission_batch_cap: int = Field(default=30, ge=4, le=512)
admission_max_queue_wait_ms: float = Field(default=300.0, ge=20.0)
def generate_arrival_workload(
arrival_rate_rps: float,
sim_duration_s: float,
pattern: Literal["poisson", "bursty"],
seed: int,
burst_cv2: float = 4.0,
) -> list[dict[str, float | int]]:
"""Generate deterministic request stream (arrival_s, prompt_tokens, output_tokens)."""
if arrival_rate_rps <= 0.0 or sim_duration_s <= 0.0:
raise ValueError("arrival_rate_rps and sim_duration_s must be positive")
rng = np.random.default_rng(seed)
mean_gap = 1.0 / arrival_rate_rps
shape_k = 1.0 / burst_cv2
scale_theta = mean_gap / shape_k
requests: list[dict[str, float | int]] = []
t = 0.0
req_id = 0
while t < sim_duration_s:
gap = (
float(rng.exponential(scale=mean_gap))
if pattern == "poisson"
else float(rng.gamma(shape=shape_k, scale=scale_theta))
)
t += gap
if t >= sim_duration_s:
break
prompt_tok = int(rng.integers(384, 769))
output_tok = int(rng.integers(96, 193))
requests.append(
{
"req_id": req_id,
"arrival_s": t,
"prompt_tokens": prompt_tok,
"output_tokens": output_tok,
}
)
req_id += 1
return requests
def simulate_serving_queue_at_rate(
arrival_rate_rps: float,
pattern: Literal["poisson", "bursty"] = "poisson",
admission_control: bool = False,
cfg: GoodputSimConfig | None = None,
) -> dict[str, Any]:
"""Simulate iteration-level LLM continuous batching queue at fixed arrival rate lambda."""
sc = cfg or GoodputSimConfig()
workload = generate_arrival_workload(
arrival_rate_rps=arrival_rate_rps,
sim_duration_s=sc.sim_duration_s,
pattern=pattern,
seed=sc.seed,
)
total_offered = len(workload)
if total_offered == 0:
raise ValueError("Empty workload generated")
n_req = total_offered
next_arrival_idx = 0
waiting: deque[dict[str, Any]] = deque()
# Active decode sequences tracked with remaining_output_tokens
active: list[dict[str, Any]] = []
rejected_fast = 0
completed: list[dict[str, Any]] = []
now_s = 0.0
total_prompt_tokens_done = 0
total_output_tokens_done = 0
queued_prefill_tokens = 0
def _estimate_wait_ms() -> float:
pref_wait_ms = (queued_prefill_tokens / sc.prefill_tok_per_s) * 1000.0
avg_rem = 72.0
slot_wait_ms = 0.0
if len(active) + len(waiting) >= sc.admission_batch_cap:
overflow = (len(active) + len(waiting) - sc.admission_batch_cap) + 1
step_ms = sc.base_decode_step_ms + sc.per_slot_decode_ms * len(active)
# Approximate drain rate of slots under continuous batching
drain_per_slot_ms = (avg_rem * step_ms) / max(1, len(active))
slot_wait_ms = overflow * drain_per_slot_ms
return pref_wait_ms + slot_wait_ms
def _ingest_arrivals(up_to_s: float) -> None:
nonlocal next_arrival_idx, rejected_fast, queued_prefill_tokens
while next_arrival_idx < n_req and float(workload[next_arrival_idx]["arrival_s"]) <= up_to_s:
req = workload[next_arrival_idx]
next_arrival_idx += 1
if admission_control:
est_wait = _estimate_wait_ms()
est_pref = (int(req["prompt_tokens"]) / sc.prefill_tok_per_s) * 1000.0
if (
est_wait + est_pref > sc.admission_max_queue_wait_ms
or len(active) >= sc.admission_batch_cap
):
rejected_fast += 1
continue
queued_prefill_tokens += int(req["prompt_tokens"])
waiting.append(
{
"req_id": req["req_id"],
"arrival_s": float(req["arrival_s"]),
"prompt_tokens": int(req["prompt_tokens"]),
"output_tokens": int(req["output_tokens"]),
"first_token_s": 0.0,
"generated_tokens": 0,
}
)
# Event-driven continuous batching loop
while next_arrival_idx < n_req or waiting or active:
_ingest_arrivals(now_s)
if not waiting and not active:
if next_arrival_idx >= n_req:
break
now_s = float(workload[next_arrival_idx]["arrival_s"])
_ingest_arrivals(now_s)
# Admit one waiting request into prefill if slot capacity permits
if waiting and len(active) < sc.max_batch_slots:
req_in = waiting.popleft()
p_tok = int(req_in["prompt_tokens"])
queued_prefill_tokens = max(0, queued_prefill_tokens - p_tok)
t_pref_s = p_tok / sc.prefill_tok_per_s
now_s += t_pref_s
_ingest_arrivals(now_s)
total_prompt_tokens_done += p_tok
total_output_tokens_done += 1
req_in["first_token_s"] = now_s
req_in["generated_tokens"] = 1
if int(req_in["output_tokens"]) <= 1:
ttft_ms = (now_s - float(req_in["arrival_s"])) * 1000.0
completed.append(
{
"ttft_ms": ttft_ms,
"tpot_ms": 0.0,
"e2e_ms": ttft_ms,
}
)
else:
active.append(req_in)
# Run one parallel decode iteration across all active requests
if active:
step_ms = sc.base_decode_step_ms + sc.per_slot_decode_ms * len(active)
now_s += step_ms / 1000.0
_ingest_arrivals(now_s)
still_active: list[dict[str, Any]] = []
total_output_tokens_done += len(active)
for item in active:
item["generated_tokens"] += 1
if item["generated_tokens"] >= item["output_tokens"]:
ttft_ms = (float(item["first_token_s"]) - float(item["arrival_s"])) * 1000.0
decode_span_ms = (now_s - float(item["first_token_s"])) * 1000.0
tpot_ms = decode_span_ms / max(1, int(item["output_tokens"]) - 1)
e2e_ms = (now_s - float(item["arrival_s"])) * 1000.0
completed.append(
{
"ttft_ms": ttft_ms,
"tpot_ms": tpot_ms,
"e2e_ms": e2e_ms,
}
)
else:
still_active.append(item)
active = still_active
effective_span_s = max(sc.sim_duration_s, now_s)
ttfts = np.array([c["ttft_ms"] for c in completed], dtype=np.float64)
tpots = np.array([c["tpot_ms"] for c in completed], dtype=np.float64)
slo_pass_mask = (ttfts <= sc.ttft_slo_ms) & (tpots <= sc.tpot_slo_ms)
n_completed = len(completed)
n_slo_pass = int(np.sum(slo_pass_mask))
slo_compliance_pct = 100.0 * n_slo_pass / max(1, n_completed)
# Goodput is requests/sec passing BOTH TTFT and TPOT SLOs across the simulation horizon
slo_goodput_rps = n_slo_pass / effective_span_s
raw_output_tps = total_output_tokens_done / effective_span_s
raw_total_tps = (total_prompt_tokens_done + total_output_tokens_done) / effective_span_s
return {
"arrival_rate_rps": round(arrival_rate_rps, 2),
"pattern": pattern,
"admission_control": admission_control,
"total_offered_requests": total_offered,
"completed_requests": n_completed,
"rejected_fast_requests": rejected_fast,
"slo_compliant_requests": n_slo_pass,
"slo_compliance_pct": round(slo_compliance_pct, 2),
"meets_95_pct_target": slo_compliance_pct >= sc.compliance_target_pct,
"raw_output_tokens_per_sec": round(raw_output_tps, 1),
"raw_total_tokens_per_sec": round(raw_total_tps, 1),
"slo_goodput_rps": round(slo_goodput_rps, 3),
"p50_ttft_ms": round(float(np.percentile(ttfts, 50)), 2),
"p95_ttft_ms": round(float(np.percentile(ttfts, 95)), 2),
"p99_ttft_ms": round(float(np.percentile(ttfts, 99)), 2),
"p50_tpot_ms": round(float(np.percentile(tpots, 50)), 2),
"p99_tpot_ms": round(float(np.percentile(tpots, 99)), 2),
"sim_horizon_s": round(effective_span_s, 2),
}
def run_goodput_mirage_comparison(
cfg: GoodputSimConfig | None = None,
arrival_rates_rps: Sequence[float] = (1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.5, 9.0, 11.0),
) -> dict[str, Any]:
"""Sweep arrival rates across Poisson FIFO, Bursty FIFO, and Bursty + Admission Control."""
sc = cfg or GoodputSimConfig()
regimes: dict[str, list[dict[str, Any]]] = {
"poisson_fifo": [],
"bursty_fifo": [],
"bursty_admission_control": [],
}
for lam in arrival_rates_rps:
regimes["poisson_fifo"].append(
simulate_serving_queue_at_rate(
arrival_rate_rps=float(lam), pattern="poisson", admission_control=False, cfg=sc
)
)
regimes["bursty_fifo"].append(
simulate_serving_queue_at_rate(
arrival_rate_rps=float(lam), pattern="bursty", admission_control=False, cfg=sc
)
)
regimes["bursty_admission_control"].append(
simulate_serving_queue_at_rate(
arrival_rate_rps=float(lam), pattern="bursty", admission_control=True, cfg=sc
)
)
def _peak_summary(rows: list[dict[str, Any]]) -> dict[str, Any]:
best = max(rows, key=lambda r: r["slo_goodput_rps"])
tail = rows[-1]
return {
"peak_goodput_rps": best["slo_goodput_rps"],
"peak_at_lambda_rps": best["arrival_rate_rps"],
"overload_lambda_rps": tail["arrival_rate_rps"],
"overload_goodput_rps": tail["slo_goodput_rps"],
"overload_raw_total_tps": tail["raw_total_tokens_per_sec"],
"overload_p99_ttft_ms": tail["p99_ttft_ms"],
}
# Verify strict tail-latency collapse ordering via heapq top-k extraction check
bursty_at_overload = regimes["bursty_fifo"][-1]
poisson_peak = _peak_summary(regimes["poisson_fifo"])
bursty_peak = _peak_summary(regimes["bursty_fifo"])
adm_peak = _peak_summary(regimes["bursty_admission_control"])
# Use heapq to compute top-2 peak Goodput rates across regimes cleanly
top_poisson = heapq.nlargest(2, regimes["poisson_fifo"], key=lambda r: r["slo_goodput_rps"])
return {
"config": sc.model_dump(),
"arrival_rates_rps": [float(r) for r in arrival_rates_rps],
"regimes": regimes,
"summary": {
"poisson_fifo": poisson_peak,
"bursty_fifo": bursty_peak,
"bursty_admission_control": adm_peak,
"top_2_poisson_points": [
{"lambda_rps": p["arrival_rate_rps"], "goodput_rps": p["slo_goodput_rps"]}
for p in top_poisson
],
"bursty_overload_raw_tps": bursty_at_overload["raw_total_tokens_per_sec"],
"bursty_overload_goodput_rps": bursty_at_overload["slo_goodput_rps"],
},
}
class BoundedInMemorySpanExporter(SpanExporter):
"""Thread-safe bounded FIFO OpenTelemetry span exporter backed by deque(maxlen=256)."""
def __init__(self, maxlen: int = 256) -> None:
self._spans: deque[ReadableSpan] = deque(maxlen=maxlen)
self._lock = threading.Lock()
self._stopped = False
def export(self, spans: Sequence[ReadableSpan]) -> SpanExportResult:
if self._stopped:
return SpanExportResult.FAILURE
with self._lock:
self._spans.extend(spans)
return SpanExportResult.SUCCESS
def shutdown(self) -> None:
self._stopped = True
def force_flush(self, timeout_millis: int = 30000) -> bool:
return True
def get_finished_spans(self) -> tuple[ReadableSpan, ...]:
with self._lock:
return tuple(self._spans)
def clear(self) -> None:
with self._lock:
self._spans.clear()
def create_in_memory_telemetry(
service_name: str = "fsds-wb-ch21-llm-slo-goodput",
) -> tuple[TracerProvider, BoundedInMemorySpanExporter, trace.Tracer]:
"""Create deterministic in-memory OpenTelemetry TracerProvider with bounded exporter."""
exporter = BoundedInMemorySpanExporter(maxlen=256)
provider = TracerProvider(resource=Resource.create({"service.name": service_name}))
provider.add_span_processor(SimpleSpanProcessor(exporter))
tracer = provider.get_tracer("llm_slo_goodput_lab")
return provider, exporter, tracer
def summarize_finished_spans(
exporter: BoundedInMemorySpanExporter | InMemorySpanExporter,
) -> dict[str, Any]:
"""Serialize finished OpenTelemetry spans cleanly for JSON artifact persistence."""
spans = exporter.get_finished_spans()
return {
"span_count": len(spans),
"span_names": [span.name for span in spans],
"spans": [
{
"name": span.name,
"status": span.status.status_code.name,
"attributes": dict(span.attributes or {}),
}
for span in spans
],
}
def main() -> None:
"""Quick CLI smoke entry point for Poisson vs Bursty SLO Goodput benchmark."""
res = run_goodput_mirage_comparison()
s = res["summary"]
print(
f"Poisson peak={s['poisson_fifo']['peak_goodput_rps']} req/s "
f"(overload={s['poisson_fifo']['overload_goodput_rps']} req/s) | "
f"Bursty FIFO peak={s['bursty_fifo']['peak_goodput_rps']} "
f"(overload={s['bursty_fifo']['overload_goodput_rps']}, "
f"raw_tps={s['bursty_overload_raw_tps']}) | "
f"Bursty+Admission overload={s['bursty_admission_control']['overload_goodput_rps']} req/s"
)
if __name__ == "__main__":
main()
"""Deterministic CLI runner generating artifacts/t2_ch21_wb21_results.json for WB-Ch21."""
from __future__ import annotations
import argparse
import json
import sys
from pathlib import Path
from typing import Any
if hasattr(sys.stdout, "reconfigure"):
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
try:
import llm_slo_goodput_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 llm_slo_goodput_lab.kv_attention_codesign import (
H100_SXM,
ServingBudgetSpec,
analyze_kv_cache_landscape,
evaluate_model_codesign_suite,
)
from llm_slo_goodput_lab.slo_goodput_benchmark import (
GoodputSimConfig,
create_in_memory_telemetry,
run_goodput_mirage_comparison,
summarize_finished_spans,
)
def run_full_workbench_suite(seed: int = 42) -> dict[str, Any]:
"""Execute all 3 WB-Ch21 LLM serving SLO, co-design, KV-cache & Goodput experiments."""
_provider, exporter, tracer = create_in_memory_telemetry("fsds-wb-ch21-llm-slo-goodput")
with tracer.start_as_current_span("wb21.benchmark.suite") as root_span:
root_span.set_attribute("wb.seed", seed)
with tracer.start_as_current_span("wb21.exp1.roofline_and_codesign") as sp:
exp1 = evaluate_model_codesign_suite(
hw=H100_SXM,
budget=ServingBudgetSpec(
prompt_tokens=2048,
output_tokens=256,
decode_batch_size=1,
ttft_budget_ms=300.0,
tpot_budget_ms=25.0,
reserved_vram_gib=16.0,
),
)
by_id = {r["model_id"]: r for r in exp1["sizing_comparison"]}
sp.set_attribute("hw.ridge_bf16", exp1["ridge_point_h100_bf16"])
sp.set_attribute("slo.8b_bf16_tpot_ms", by_id["Llama3-8B-BF16 (1x H100)"]["tpot_ms"])
sp.set_attribute("slo.32b_bf16_tpot_ms", by_id["Qwen-32B-BF16 (1x H100)"]["tpot_ms"])
sp.set_attribute("slo.32b_fp8_tpot_ms", by_id["Qwen-32B-FP8 (1x H100)"]["tpot_ms"])
with tracer.start_as_current_span("wb21.exp1.depth_vs_width_ablation") as sp:
dw = exp1["depth_vs_width"]
moe_cmp = exp1["moe_codesign_comparison"]
sp.set_attribute("codesign.deep_tpot_ms", dw["deep_narrow_64x4096"]["tpot_ms"])
sp.set_attribute("codesign.wide_tpot_ms", dw["shallow_wide_32x5120"]["tpot_ms"])
sp.set_attribute("codesign.kv_reduction_x", dw["kv_cache_reduction_x"])
sp.set_attribute("codesign.moe_b1_tpot_ms", moe_cmp["moe_8x7b_b1"]["tpot_ms"])
with tracer.start_as_current_span("wb21.exp2.long_context_kv_cache") as sp:
exp2 = analyze_kv_cache_landscape(kv_headroom_gib=48.0, reserved_vram_gib=16.0)
hi_bf16 = exp2["highlights_128k_bf16"]
hi_fp8 = exp2["highlights_128k_fp8"]
sp.set_attribute("kv.128k_bf16_mha_gib", hi_bf16["mha"]["gib_per_sequence"])
sp.set_attribute("kv.128k_bf16_mla_gib", hi_bf16["mla"]["gib_per_sequence"])
sp.set_attribute("kv.128k_fp8_mla_batch", hi_fp8["mla"]["max_concurrent_sequences"])
with tracer.start_as_current_span("wb21.exp3.goodput_mirage_sweep") as sp:
exp3 = run_goodput_mirage_comparison(
GoodputSimConfig(seed=seed, sim_duration_s=180.0)
)
summ = exp3["summary"]
sp.set_attribute(
"goodput.poisson_peak_rps", summ["poisson_fifo"]["peak_goodput_rps"]
)
sp.set_attribute(
"goodput.poisson_overload_rps", summ["poisson_fifo"]["overload_goodput_rps"]
)
sp.set_attribute(
"goodput.bursty_overload_rps", summ["bursty_fifo"]["overload_goodput_rps"]
)
sp.set_attribute(
"goodput.admission_overload_rps",
summ["bursty_admission_control"]["overload_goodput_rps"],
)
otel_summary = summarize_finished_spans(exporter)
sizing_map = {r["model_id"]: r for r in exp1["sizing_comparison"]}
m8_bf16 = sizing_map["Llama3-8B-BF16 (1x H100)"]
m32_bf16 = sizing_map["Qwen-32B-BF16 (1x H100)"]
m32_fp8 = sizing_map["Qwen-32B-FP8 (1x H100)"]
m70_bf16 = sizing_map["Llama3-70B-BF16 (2x H100 TP2)"]
m70_fp8 = sizing_map["Llama3-70B-FP8 (2x H100 TP2)"]
dw = exp1["depth_vs_width"]
hi_128k_bf16 = exp2["highlights_128k_bf16"]
hi_128k_fp8 = exp2["highlights_128k_fp8"]
hi_1m_bf16 = {
r["kind"]: r
for r in exp2["matrix"]
if r["kv_precision"] == "bf16" and r["context_length"] == 1_048_576
}
summ = exp3["summary"]
poisson_peak = summ["poisson_fifo"]["peak_goodput_rps"]
poisson_overload = summ["poisson_fifo"]["overload_goodput_rps"]
bursty_peak = summ["bursty_fifo"]["peak_goodput_rps"]
bursty_overload = summ["bursty_fifo"]["overload_goodput_rps"]
adm_overload = summ["bursty_admission_control"]["overload_goodput_rps"]
raw_tps_overload = summ["poisson_fifo"]["overload_raw_total_tps"]
eff_ridge = m8_bf16["effective_ridge_point_flop_per_byte"]
workbench_panels: dict[str, Any] = {
"kpis": [
{
"id": "kpi_h100_ridge_prefill_vs_decode",
"label": "Analytical Roofline (H100 BF16): Prefill vs Decode B=1",
"value": (
f"{m8_bf16['prefill_ai_flop_per_byte']:.0f} vs "
f"{m8_bf16['decode_ai_flop_per_byte']:.2f} FLOP/B"
),
"unit": f"(Ridge {exp1['ridge_point_h100_bf16']} | Eff {eff_ridge})",
"status": "ok",
"detail": (
f"Analytical Roofline equation: 8B-BF16 prefill (S=2048) is compute-bound "
f"(TTFT={m8_bf16['ttft_ms']}ms), while B=1 decode scans active GEMV weights "
f"(TPOT={m8_bf16['tpot_ms']}ms; 16 GiB non-KV reserve)."
),
},
{
"id": "kpi_codesign_32b_fp8_rescue",
"label": "Analytical Sizing & MoE: 32B FP8 vs BF16 + 8x7B MoE",
"value": f"{m32_fp8['tpot_ms']}ms vs {m32_bf16['tpot_ms']}ms TPOT",
"unit": (
f"(MoE 8x7B B1={moe_cmp['moe_8x7b_b1']['tpot_ms']}ms | "
f"{moe_cmp['b1_tpot_speedup_vs_dense_x']}x vs Dense 47B)"
),
"status": "ok",
"detail": (
"32B-BF16 (~61 GiB) exceeds 25ms decode TPOT on 3.35 TB/s HBM3; FP8 halves "
"weight bandwidth. MoE 8x7B reads ~12.9B active params/token vs 46.7B stored; "
"B200 exposes 180 GiB usable HBM3e (192 GiB physical)."
),
},
{
"id": "kpi_depth_vs_width_codesign",
"label": "Analytical Co-Design Depth vs Width (9.1B Non-Emb, TP2)",
"value": (
f"{dw['shallow_wide_32x5120']['tpot_ms']}ms vs "
f"{dw['deep_narrow_64x4096']['tpot_ms']}ms"
),
"unit": (
f"(-{dw['tpot_speedup_pct']}% TPOT, "
f"{dw['kv_cache_reduction_x']}x less KV)"
),
"status": "ok",
"detail": (
"Analytical model: Shallow-Wide (L=32, d=5120) halves sequential TP AllReduce "
"barriers and KV-cache bytes/token (128 vs 256 KiB/tok) vs Deep-Narrow."
),
},
{
"id": "kpi_kv_128k_mha_oom_vs_mla",
"label": "Exact KV Equations (128k, 48 GiB Headroom): MHA vs MLA",
"value": (
f"{hi_128k_bf16['mla']['gib_per_sequence']} GiB vs "
f"{hi_128k_bf16['mha']['gib_per_sequence']} GiB"
),
"unit": (
f"({hi_128k_bf16['mla']['compression_vs_mha_x']}x smaller | "
f"{hi_128k_fp8['mla']['max_concurrent_sequences']} seqs w/ FP8 KV)"
),
"status": "ok",
"detail": (
"Exact KV equation (with 16 GiB non-KV + 16 GiB 8B weights): MHA BF16 needs "
"64.0 GiB/seq at 128k (OOM); MLA fits 10 BF16 / 21 FP8 concurrent seqs."
),
},
{
"id": "kpi_goodput_mirage_collapse",
"label": "Poisson Peak Goodput vs Overload Collapse (11 req/s)",
"value": f"{poisson_peak:.2f} -> {poisson_overload:.2f} req/s",
"unit": f"(Raw TPS still hits {raw_tps_overload:,.0f} tok/s!)",
"status": "warn",
"detail": (
"Aggregate tokens/s rises monotonically to saturation while SLO Goodput "
"(TTFT<=500ms & TPOT<=35ms) collapses to 0.0 under tail queueing."
),
},
{
"id": "kpi_admission_rescue_and_otel",
"label": "Bursty Overload Goodput w/ Admission Control & OTel",
"value": f"{adm_overload:.2f} vs {bursty_overload:.2f} req/s",
"unit": (
f"(Bursty peak {bursty_peak:.2f} | "
f"{otel_summary['span_count']} OTel Spans)"
),
"status": "ok",
"detail": (
"SLO-aware deadline shedding prevents queue drowning under CV^2=4.0 bursts, "
"sustaining >=98% compliance on admitted requests vs total FIFO collapse."
),
},
],
"bars": [
{
"id": "bar_model_sizing_tpot_ms",
"title": "Exp 1 — Decode TPOT (ms) vs 25ms Budget Across Sizing & Precision",
"metric_label": "TPOT (ms, lower is better)",
"items": [
{
"label": "Llama3-8B-FP8 (1x H100)",
"value": sizing_map["Llama3-8B-FP8 (1x H100)"]["tpot_ms"],
"display": f"{sizing_map['Llama3-8B-FP8 (1x H100)']['tpot_ms']} ms (PASS)",
"css_class": "is-fast",
},
{
"label": "Llama3-8B-BF16 (1x H100)",
"value": m8_bf16["tpot_ms"],
"display": f"{m8_bf16['tpot_ms']} ms (PASS)",
"css_class": "is-fast",
},
{
"label": "Qwen-32B-FP8 (1x H100)",
"value": m32_fp8["tpot_ms"],
"display": f"{m32_fp8['tpot_ms']} ms (PASS)",
"css_class": "is-fast",
},
{
"label": "Llama3-70B-FP8 (2x H100 TP2)",
"value": m70_fp8["tpot_ms"],
"display": f"{m70_fp8['tpot_ms']} ms (PASS)",
"css_class": "is-mid",
},
{
"label": "Qwen-32B-BF16 (1x H100)",
"value": m32_bf16["tpot_ms"],
"display": f"{m32_bf16['tpot_ms']} ms (FAIL >25ms)",
"css_class": "is-slow",
},
{
"label": "Llama3-70B-BF16 (2x H100 TP2)",
"value": m70_bf16["tpot_ms"],
"display": f"{m70_bf16['tpot_ms']} ms (FAIL >25ms)",
"css_class": "is-slow",
},
],
},
{
"id": "bar_kv_cache_128k_gib",
"title": "Exp 2 — KV-Cache Footprint per 128k Sequence (GiB, BF16 KV vs 48 GiB Budget)",
"metric_label": "KV Footprint (GiB / seq)",
"items": [
{
"label": "MQA (1 KV Head)",
"value": hi_128k_bf16["mqa"]["gib_per_sequence"],
"display": f"{hi_128k_bf16['mqa']['gib_per_sequence']} GiB (24 seqs)",
"css_class": "is-fast",
},
{
"label": "Hybrid SWA (W=4096, 3:1)",
"value": hi_128k_bf16["hybrid_swa"]["gib_per_sequence"],
"display": f"{hi_128k_bf16['hybrid_swa']['gib_per_sequence']} GiB (10 seqs)",
"css_class": "is-fast",
},
{
"label": "MLA (d_c=512 + d_R=64)",
"value": hi_128k_bf16["mla"]["gib_per_sequence"],
"display": f"{hi_128k_bf16['mla']['gib_per_sequence']} GiB (10 seqs)",
"css_class": "is-fast",
},
{
"label": "GQA-8 (8 KV Heads)",
"value": hi_128k_bf16["gqa_8"]["gib_per_sequence"],
"display": f"{hi_128k_bf16['gqa_8']['gib_per_sequence']} GiB (3 seqs)",
"css_class": "is-mid",
},
{
"label": "MHA (32 KV Heads)",
"value": hi_128k_bf16["mha"]["gib_per_sequence"],
"display": f"{hi_128k_bf16['mha']['gib_per_sequence']} GiB (OOM: 0 seqs!)",
"css_class": "is-slow",
},
],
},
{
"id": "bar_kv_128k_fp8_concurrency",
"title": "Exp 2b — Max Concurrent 128k Sequences Inside 48 GiB Headroom (FP8 KV-Cache)",
"metric_label": "Max Concurrent Batch (seqs)",
"items": [
{
"label": "MHA (FP8 KV: 32.0 GiB/seq)",
"value": hi_128k_fp8["mha"]["max_concurrent_sequences"],
"display": f"{hi_128k_fp8['mha']['max_concurrent_sequences']} seq",
"css_class": "is-slow",
},
{
"label": "GQA-8 (FP8 KV: 8.0 GiB/seq)",
"value": hi_128k_fp8["gqa_8"]["max_concurrent_sequences"],
"display": f"{hi_128k_fp8['gqa_8']['max_concurrent_sequences']} seqs",
"css_class": "is-mid",
},
{
"label": "MLA (FP8 KV: 2.25 GiB/seq)",
"value": hi_128k_fp8["mla"]["max_concurrent_sequences"],
"display": f"{hi_128k_fp8['mla']['max_concurrent_sequences']} seqs",
"css_class": "is-fast",
},
{
"label": "Hybrid SWA (FP8 KV: 2.19 GiB/seq)",
"value": hi_128k_fp8["hybrid_swa"]["max_concurrent_sequences"],
"display": f"{hi_128k_fp8['hybrid_swa']['max_concurrent_sequences']} seqs",
"css_class": "is-fast",
},
{
"label": "MQA (FP8 KV: 1.0 GiB/seq)",
"value": hi_128k_fp8["mqa"]["max_concurrent_sequences"],
"display": f"{hi_128k_fp8['mqa']['max_concurrent_sequences']} seqs",
"css_class": "is-fast",
},
],
},
{
"id": "bar_goodput_overload_comparison",
"title": "Exp 3 — Goodput Collapse at 11.0 req/s Overload vs Peak Capacity (req/s)",
"metric_label": "SLO Goodput (req/s)",
"items": [
{
"label": "Poisson FIFO at Peak (6.0 req/s)",
"value": poisson_peak,
"display": f"{poisson_peak:.3f} req/s",
"css_class": "is-fast",
},
{
"label": "Poisson FIFO at Overload (11.0 req/s)",
"value": poisson_overload,
"display": f"{poisson_overload:.3f} req/s (COLLAPSED!)",
"css_class": "is-slow",
},
{
"label": "Bursty FIFO at Overload (11.0 req/s)",
"value": bursty_overload,
"display": f"{bursty_overload:.3f} req/s (COLLAPSED!)",
"css_class": "is-slow",
},
{
"label": "Bursty + Admission Control (11.0 req/s)",
"value": adm_overload,
"display": f"{adm_overload:.3f} req/s (PROTECTED)",
"css_class": "is-fast",
},
],
},
],
"tables": [
{
"id": "table_sizing_and_codesign",
"title": "Exp 1a (Analytical Roofline) — Sizing, Precision, MoE & Co-Design",
"columns": [
"model_config",
"weights_and_kv",
"ttft_and_tpot",
"slo_verdict",
],
"rows": [
[
r["model_id"],
(
f"{r['weight_gib_per_gpu']} GiB/GPU "
f"(active {r['active_params_b']}B) | {r['kv_kib_per_token_total']} KiB/tok"
),
f"TTFT={r['ttft_ms']}ms | TPOT={r['tpot_ms']}ms",
"PASS" if r["passes_all_slos"] else "FAIL (Budget Breach)",
]
for r in (
*exp1["sizing_comparison"],
dw["deep_narrow_64x4096"],
dw["shallow_wide_32x5120"],
moe_cmp["moe_8x7b_b1"],
moe_cmp["dense_47b_matched_vram_b1"],
)
],
},
{
"id": "table_batch_ai_knee",
"title": "Exp 1b — Decode Batch Arithmetic-Intensity Knee (8B-BF16, Ridge=295.22)",
"columns": [
"batch_size",
"arithmetic_intensity",
"roofline_regime",
"tpot_and_throughput",
],
"rows": [
[
f"B = {r['batch_size']}",
f"{r['decode_ai_flop_per_byte']} FLOP/B",
r["decode_regime"],
f"{r['tpot_ms']} ms | {r['decode_tokens_per_sec']:,.1f} tok/s",
]
for r in exp1["batch_ai_knee_sweep_8b_bf16"]
if r["batch_size"] in (1, 16, 64, 128, 256, 384, 512, 768)
],
},
{
"id": "table_kv_cache_long_context",
"title": "Exp 2 — Long-Context KV-Cache Equations (BF16 KV, 48 GiB Headroom)",
"columns": [
"attention_arch",
"bytes_per_tok",
"gb_per_seq_128k_1m",
"max_batch_128k_bf16_fp8",
],
"rows": [
[
hi_128k_bf16[k]["arch_name"],
f"{hi_128k_bf16[k]['effective_kib_per_token']} KiB/tok",
(
f"128k={hi_128k_bf16[k]['gib_per_sequence']} GiB | "
f"1M={hi_1m_bf16[hi_128k_bf16[k]['kind']]['gib_per_sequence']} GiB"
),
(
f"BF16={hi_128k_bf16[k]['max_concurrent_sequences']} | "
f"FP8={hi_128k_fp8[k]['max_concurrent_sequences']} seqs"
),
]
for k in ("mha", "gqa_8", "mla", "hybrid_swa", "mqa")
],
},
{
"id": "table_goodput_poisson_vs_bursty",
"title": "Exp 3 — Raw Tokens/s Mirage vs SLO Goodput (500ms TTFT, 35ms TPOT)",
"columns": [
"lambda_rps",
"poisson_goodput_and_p99",
"bursty_goodput_and_p99",
"admission_goodput_and_raw_tps",
],
"rows": [
[
f"{p['arrival_rate_rps']} req/s",
f"{p['slo_goodput_rps']:.3f} req/s (p99={p['p99_ttft_ms']:.0f}ms)",
f"{b['slo_goodput_rps']:.3f} req/s (p99={b['p99_ttft_ms']:.0f}ms)",
(
f"{a['slo_goodput_rps']:.3f} req/s | "
f"Raw={p['raw_total_tokens_per_sec']:,.0f} tok/s"
),
]
for p, b, a in zip(
exp3["regimes"]["poisson_fifo"],
exp3["regimes"]["bursty_fifo"],
exp3["regimes"]["bursty_admission_control"],
strict=True,
)
],
},
],
}
return {
"unit_id": "T2-P4-U02",
"lab_id": "ch21-llm-serving-slo-goodput-workbench",
"seed": seed,
"exp1_roofline_and_codesign": exp1,
"exp2_kv_cache_landscape": exp2,
"exp3_goodput_benchmark": exp3,
"opentelemetry_summary": otel_summary,
"workbench_panels": workbench_panels,
}
def main() -> None:
parser = argparse.ArgumentParser(description="Run WB-Ch21 LLM Serving SLO & Goodput suite.")
parser.add_argument("--seed", type=int, default=42)
parser.add_argument(
"--output",
type=Path,
default=Path("artifacts/t2_ch21_wb21_results.json"),
)
args = parser.parse_args()
results = run_full_workbench_suite(seed=args.seed)
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(json.dumps(results, indent=2), encoding="utf-8")
n_spans = results["opentelemetry_summary"]["span_count"]
print(f"Saved WB-Ch21 results to {args.output} (spans={n_spans})")
if __name__ == "__main__":
main()
"""Automated verification suite (25 tests, 0 skips) for WB-Ch21: LLM Serving SLOs & Goodput."""
from __future__ import annotations
import ast
import io
import itertools
import json
import math
import tokenize
from pathlib import Path
from typing import Any
import pytest
from hypothesis import given, settings
from hypothesis import strategies as st
from pydantic import ValidationError
from llm_slo_goodput_lab.kv_attention_codesign import (
B200_SXM,
H100_SXM,
AttentionSpec,
HardwareProfile,
ModelArchitectureSpec,
ServingBudgetSpec,
analyze_kv_cache_landscape,
compute_kv_cache_sequence_metrics,
evaluate_model_codesign_suite,
profile_prefill_and_decode_roofline,
)
from llm_slo_goodput_lab.slo_goodput_benchmark import (
GoodputSimConfig,
create_in_memory_telemetry,
run_goodput_mirage_comparison,
simulate_serving_queue_at_rate,
summarize_finished_spans,
)
from scripts.run_lab_demo import run_full_workbench_suite
LAB_ROOT = Path(__file__).resolve().parents[1]
def test_01_ast_safety_no_type_ignore_no_wall_sleep_or_disk_artifacts() -> None:
forbidden_modules = {"pickle", "cPickle", "joblib", "cloudpickle", "dill", "shelve", "marshal"}
forbidden_calls = {"eval", "exec"}
py_files = [
*sorted((LAB_ROOT / "src").rglob("*.py")),
*sorted((LAB_ROOT / "scripts").rglob("*.py")),
*sorted((LAB_ROOT / "tests").rglob("*.py")),
]
assert len(py_files) >= 5
forbidden_comment = "type:" + " ignore"
for py_file in py_files:
source = py_file.read_text(encoding="utf-8")
with io.StringIO(source) as buf:
for tok in tokenize.generate_tokens(buf.readline):
if tok.type == tokenize.COMMENT and forbidden_comment in tok.string:
raise AssertionError(f"Forbidden type-ignore comment found in {py_file}")
tree = ast.parse(source, filename=str(py_file))
for node in ast.walk(tree):
if isinstance(node, ast.Import):
for alias in node.names:
root_mod = alias.name.split(".")[0]
assert root_mod not in forbidden_modules
assert root_mod != "time"
elif isinstance(node, ast.ImportFrom) and node.module:
root_mod = node.module.split(".")[0]
assert root_mod not in forbidden_modules
assert root_mod != "time"
elif isinstance(node, ast.Call) and isinstance(node.func, ast.Name):
assert node.func.id not in forbidden_calls
for pat in ("*.png", "*.parquet", "*.duckdb*"):
leftover = list(LAB_ROOT.rglob(pat))
assert not leftover, f"Unexpected leftover files matching {pat}: {leftover}"
def test_02_pydantic_strict_configs_forbid_extra_fields() -> None:
hw = HardwareProfile(
name="H100",
peak_bf16_tflops=989.0,
peak_fp8_tflops=1979.0,
hbm_bw_tb_s=3.35,
vram_gib=80.0,
)
model = ModelArchitectureSpec(
model_id="test-8b",
n_layers=32,
d_model=4096,
n_heads=32,
n_kv_heads=8,
d_head=128,
ffn_hidden=14336,
)
budget = ServingBudgetSpec()
attn = AttentionSpec(arch_name="MLA", kind="mla")
sim_cfg = GoodputSimConfig()
assert hw.vram_gib == 80.0 and model.vocab_size == 128_256
assert budget.ttft_budget_ms == 300.0 and attn.mla_d_c == 512 and sim_cfg.seed == 42
for cls, payload in (
(
HardwareProfile,
{
"name": "x",
"peak_bf16_tflops": 100,
"peak_fp8_tflops": 200,
"hbm_bw_tb_s": 2,
"vram_gib": 40,
"extra": 1,
},
),
(
ModelArchitectureSpec,
{
"model_id": "m",
"n_layers": 1,
"d_model": 512,
"n_heads": 8,
"n_kv_heads": 2,
"d_head": 64,
"ffn_hidden": 1024,
"extra": 1,
},
),
(ServingBudgetSpec, {"prompt_tokens": 512, "unknown": True}),
(AttentionSpec, {"arch_name": "a", "kind": "mha", "unknown": True}),
(GoodputSimConfig, {"seed": 42, "unknown": True}),
):
with pytest.raises(ValidationError):
cls.model_validate(payload)
def test_03_h100_and_b200_ridge_points_and_prefill_vs_decode_regimes() -> None:
assert H100_SXM.ridge_point("bf16") == pytest.approx(295.22, abs=0.05)
assert H100_SXM.ridge_point("fp8") == pytest.approx(590.75, abs=0.05)
assert B200_SXM.ridge_point("bf16") == pytest.approx(281.25, abs=0.05)
exp1 = evaluate_model_codesign_suite()
m8 = next(r for r in exp1["sizing_comparison"] if r["model_id"] == "Llama3-8B-BF16 (1x H100)")
assert m8["prefill_regime"] == "compute_bound"
assert m8["decode_regime"] == "memory_bound"
assert m8["prefill_ai_flop_per_byte"] > exp1["ridge_point_h100_bf16"]
assert m8["decode_ai_flop_per_byte"] < 5.0
def test_04_sizing_and_fp8_rescue_compliance_against_strict_slos() -> None:
exp1 = evaluate_model_codesign_suite()
by_id = {r["model_id"]: r for r in exp1["sizing_comparison"]}
assert by_id["Llama3-8B-BF16 (1x H100)"]["passes_all_slos"] is True
assert by_id["Llama3-8B-FP8 (1x H100)"]["passes_all_slos"] is True
assert by_id["Qwen-32B-BF16 (1x H100)"]["passes_tpot_budget"] is False
assert by_id["Qwen-32B-BF16 (1x H100)"]["passes_all_slos"] is False
assert by_id["Qwen-32B-FP8 (1x H100)"]["passes_all_slos"] is True
assert by_id["Llama3-70B-BF16 (2x H100 TP2)"]["passes_all_slos"] is False
assert by_id["Llama3-70B-FP8 (2x H100 TP2)"]["passes_all_slos"] is True
def test_05_batch_arithmetic_intensity_knee_transitions_to_compute_bound() -> None:
exp1 = evaluate_model_codesign_suite()
sweep = exp1["batch_ai_knee_sweep_8b_bf16"]
assert sweep[0]["batch_size"] == 1
assert sweep[0]["decode_regime"] == "memory_bound"
assert sweep[-1]["batch_size"] == 768
assert sweep[-1]["decode_regime"] == "compute_bound"
ais = [r["decode_ai_flop_per_byte"] for r in sweep]
tps = [r["decode_tokens_per_sec"] for r in sweep]
assert all(b > a for a, b in itertools.pairwise(ais))
assert all(b > a for a, b in itertools.pairwise(tps))
def test_06_depth_vs_width_codesign_shallow_wide_beats_deep_narrow() -> None:
exp1 = evaluate_model_codesign_suite()
dw = exp1["depth_vs_width"]
deep = dw["deep_narrow_64x4096"]
wide = dw["shallow_wide_32x5120"]
assert wide["tpot_ms"] < deep["tpot_ms"]
assert wide["ttft_ms"] < deep["ttft_ms"]
assert wide["kv_kib_per_token_total"] < deep["kv_kib_per_token_total"]
assert dw["kv_cache_reduction_x"] == pytest.approx(2.0)
def test_07_swiglu_ffn_ratio_and_vocab_overhead_equations() -> None:
exp1 = evaluate_model_codesign_suite()
ffn = exp1["ffn_ablation"]
assert ffn["swiglu_4_0_bloated"]["total_params_b"] > ffn["swiglu_8_over_3"]["total_params_b"] + 2.0
assert ffn["swiglu_4_0_bloated"]["tpot_ms"] > ffn["swiglu_8_over_3"]["tpot_ms"]
vocab_map = {r["variant"]: r for r in exp1["vocab_ablation"]}
v32 = vocab_map["32k_tied"]
v128 = vocab_map["128k_untied"]
v256 = vocab_map["256k_untied"]
assert v32["vocab_params_b"] < v128["vocab_params_b"] < v256["vocab_params_b"]
assert v256["vocab_params_b"] == pytest.approx(2.097, abs=0.01)
assert v256["lm_head_step_ms"] > v128["lm_head_step_ms"] > v32["lm_head_step_ms"]
def test_08_exact_kv_cache_equations_mha_gqa_mqa_mla_and_hybrid_swa() -> None:
exp2 = analyze_kv_cache_landscape(kv_headroom_gib=48.0)
hi = exp2["highlights_128k_bf16"]
# L=32, n_h=32, d_h=128, BF16 (2 B)
assert hi["mha"]["effective_bytes_per_token"] == 524_288
assert hi["gqa_8"]["effective_bytes_per_token"] == 131_072
assert hi["mla"]["effective_bytes_per_token"] == 32 * (512 + 64) * 2 # 36,864 B/tok
assert hi["mqa"]["effective_bytes_per_token"] == 16_384
assert hi["mha"]["gib_per_sequence"] == pytest.approx(64.0)
assert hi["gqa_8"]["gib_per_sequence"] == pytest.approx(16.0)
assert hi["mla"]["gib_per_sequence"] == pytest.approx(4.5)
assert hi["hybrid_swa"]["gib_per_sequence"] == pytest.approx(4.375)
assert hi["mqa"]["gib_per_sequence"] == pytest.approx(2.0)
assert hi["mla"]["compression_vs_mha_x"] == pytest.approx(14.22, abs=0.02)
def test_09_mha_ooms_at_128k_bf16_while_mla_and_swa_unlock_high_concurrency() -> None:
exp2 = analyze_kv_cache_landscape(kv_headroom_gib=48.0)
hi_bf16 = exp2["highlights_128k_bf16"]
hi_fp8 = exp2["highlights_128k_fp8"]
hi_1m_fp8 = exp2["highlights_1m_fp8"]
assert hi_bf16["mha"]["oom_single_sequence"] is True
assert hi_bf16["mha"]["max_concurrent_sequences"] == 0
assert hi_bf16["gqa_8"]["max_concurrent_sequences"] == 3
assert hi_bf16["mla"]["max_concurrent_sequences"] == 10
assert hi_bf16["hybrid_swa"]["max_concurrent_sequences"] == 10
assert hi_bf16["mqa"]["max_concurrent_sequences"] == 24
assert hi_fp8["mla"]["max_concurrent_sequences"] == 21
assert hi_fp8["hybrid_swa"]["max_concurrent_sequences"] == 21
assert hi_1m_fp8["mha"]["oom_single_sequence"] is True
assert hi_1m_fp8["mla"]["oom_single_sequence"] is False
assert hi_1m_fp8["mla"]["max_concurrent_sequences"] == 2
def test_10_kv_cache_fp8_halves_bytes_and_32b_tp2_mha_ooms_at_128k() -> None:
mla_spec = AttentionSpec(arch_name="MLA", kind="mla")
bf16_m = compute_kv_cache_sequence_metrics(mla_spec, 131_072, "bf16", 48.0)
fp8_m = compute_kv_cache_sequence_metrics(mla_spec, 131_072, "fp8", 48.0)
assert fp8_m["effective_bytes_per_token"] * 2 == bf16_m["effective_bytes_per_token"]
assert fp8_m["gib_per_sequence"] * 2 == pytest.approx(bf16_m["gib_per_sequence"])
exp2 = analyze_kv_cache_landscape()
mha_32b_128k = next(
r
for r in exp2["tp2_32b_bf16_96gib_headroom"]
if r["kind"] == "mha" and r["context_length"] == 131_072
)
assert mha_32b_128k["oom_single_sequence"] is True
def test_11_validation_rejects_non_positive_kv_and_workload_args() -> None:
spec = AttentionSpec(arch_name="MHA", kind="mha")
with pytest.raises(ValueError):
compute_kv_cache_sequence_metrics(spec, context_length=0)
with pytest.raises(ValueError):
compute_kv_cache_sequence_metrics(spec, context_length=4096, kv_headroom_gib=0.0)
with pytest.raises(ValueError):
simulate_serving_queue_at_rate(arrival_rate_rps=0.0)
def test_12_raw_tokens_per_sec_mirage_rises_while_slo_goodput_collapses() -> None:
exp3 = run_goodput_mirage_comparison(GoodputSimConfig(seed=42, sim_duration_s=180.0))
poisson = exp3["regimes"]["poisson_fifo"]
summ = exp3["summary"]["poisson_fifo"]
low = poisson[2] # 3.0 req/s
peak = next(r for r in poisson if r["arrival_rate_rps"] == summ["peak_at_lambda_rps"])
overload = poisson[-1] # 11.0 req/s
assert (
overload["raw_total_tokens_per_sec"]
> peak["raw_total_tokens_per_sec"]
> low["raw_total_tokens_per_sec"]
)
assert peak["slo_goodput_rps"] > 5.0
assert overload["slo_goodput_rps"] < 0.1
assert overload["p99_ttft_ms"] > 10_000.0
def test_13_bursty_arrivals_degrade_tail_latency_and_collapse_earlier_than_poisson() -> None:
exp3 = run_goodput_mirage_comparison(GoodputSimConfig(seed=42, sim_duration_s=180.0))
p_rows = {r["arrival_rate_rps"]: r for r in exp3["regimes"]["poisson_fifo"]}
b_rows = {r["arrival_rate_rps"]: r for r in exp3["regimes"]["bursty_fifo"]}
assert (
exp3["summary"]["bursty_fifo"]["peak_goodput_rps"]
< exp3["summary"]["poisson_fifo"]["peak_goodput_rps"]
)
# At 6.0 req/s, Poisson is near peak while Bursty already suffers severe tail queue buildup
assert b_rows[6.0]["p99_ttft_ms"] > p_rows[6.0]["p99_ttft_ms"] * 2.0
assert b_rows[6.0]["slo_compliance_pct"] < p_rows[6.0]["slo_compliance_pct"]
def test_14_slo_aware_admission_control_prevents_goodput_collapse_under_bursty_overload() -> None:
exp3 = run_goodput_mirage_comparison(GoodputSimConfig(seed=42, sim_duration_s=180.0))
b_fifo = exp3["regimes"]["bursty_fifo"][-1]
b_adm = exp3["regimes"]["bursty_admission_control"][-1]
assert b_fifo["slo_goodput_rps"] < 0.2
assert b_adm["slo_goodput_rps"] > 5.0
assert b_adm["rejected_fast_requests"] > 100
assert b_adm["slo_compliance_pct"] >= 95.0
assert b_adm["p99_ttft_ms"] <= 500.0
assert b_adm["p99_tpot_ms"] <= 35.0
def test_15_goodput_sim_accounts_for_all_offered_requests_under_admission_control() -> None:
res = simulate_serving_queue_at_rate(
arrival_rate_rps=9.0,
pattern="bursty",
admission_control=True,
cfg=GoodputSimConfig(seed=42, sim_duration_s=180.0),
)
assert res["completed_requests"] + res["rejected_fast_requests"] == res["total_offered_requests"]
assert res["slo_compliant_requests"] <= res["completed_requests"]
def test_16_e2e_latency_consistency_on_roofline_profiles() -> None:
budget = ServingBudgetSpec(prompt_tokens=2048, output_tokens=256)
exp1 = evaluate_model_codesign_suite(budget=budget)
for row in exp1["sizing_comparison"]:
expected_e2e = row["ttft_ms"] + (budget.output_tokens - 1) * row["tpot_ms"]
assert row["e2e_ms"] == pytest.approx(expected_e2e, abs=2.5)
def test_17_seed_42_determinism_across_repeated_runs() -> None:
r1 = run_full_workbench_suite(seed=42)
r2 = run_full_workbench_suite(seed=42)
assert r1["exp1_roofline_and_codesign"] == r2["exp1_roofline_and_codesign"]
assert r1["exp2_kv_cache_landscape"] == r2["exp2_kv_cache_landscape"]
assert r1["exp3_goodput_benchmark"] == r2["exp3_goodput_benchmark"]
def test_18_opentelemetry_bounded_exporter_records_clean_spans() -> None:
_provider, exporter, tracer = create_in_memory_telemetry("wb21-test")
for idx in range(6):
with tracer.start_as_current_span(f"wb21.span.{idx}") as sp:
sp.set_attribute("idx", idx)
summary = summarize_finished_spans(exporter)
assert summary["span_count"] == 6
res = run_full_workbench_suite(seed=42)
otel = res["opentelemetry_summary"]
assert otel["span_count"] >= 5
serialized = json.dumps(otel)
for forbidden in ("password", "secret_key", "private_key"):
assert forbidden not in serialized.lower()
def test_19_workbench_panels_exact_schema_6_kpis_4_bars_4_tables() -> None:
res = run_full_workbench_suite(seed=42)
panels: dict[str, Any] = res["workbench_panels"]
assert len(panels["kpis"]) == 6
assert len(panels["bars"]) == 4
assert len(panels["tables"]) == 4
for kpi in panels["kpis"]:
assert {"id", "label", "value", "unit", "status", "detail"} <= set(kpi.keys())
for bar in panels["bars"]:
assert {"id", "title", "metric_label", "items"} <= set(bar.keys())
assert len(bar["items"]) >= 3
for item in bar["items"]:
assert {"label", "value", "display", "css_class"} <= set(item.keys())
for tbl in panels["tables"]:
assert {"id", "title", "columns", "rows"} <= set(tbl.keys())
assert len(tbl["columns"]) == 4
assert len(tbl["rows"]) >= 2
@given(
ctx=st.integers(min_value=8192, max_value=1_048_576),
n_layers=st.integers(min_value=8, max_value=80),
)
@settings(max_examples=25, database=None)
def test_20_hypothesis_kv_cache_attention_ordering_at_long_context(
ctx: int,
n_layers: int,
) -> None:
mha = compute_kv_cache_sequence_metrics(
AttentionSpec(arch_name="MHA", kind="mha", n_layers=n_layers, n_query_heads=32, n_kv_heads=32),
context_length=ctx,
)
gqa = compute_kv_cache_sequence_metrics(
AttentionSpec(arch_name="GQA", kind="gqa", n_layers=n_layers, n_query_heads=32, n_kv_heads=8),
context_length=ctx,
)
mla = compute_kv_cache_sequence_metrics(
AttentionSpec(arch_name="MLA", kind="mla", n_layers=n_layers, mla_d_c=512, mla_d_r=64),
context_length=ctx,
)
swa = compute_kv_cache_sequence_metrics(
AttentionSpec(
arch_name="SWA",
kind="hybrid_swa",
n_layers=n_layers,
n_query_heads=32,
n_kv_heads=8,
swa_window_tokens=4096,
swa_local_to_global_ratio=3,
),
context_length=ctx,
)
mqa = compute_kv_cache_sequence_metrics(
AttentionSpec(arch_name="MQA", kind="mqa", n_layers=n_layers, n_query_heads=32, n_kv_heads=1),
context_length=ctx,
)
assert (
mqa["gib_per_sequence"]
< mla["gib_per_sequence"]
< gqa["gib_per_sequence"]
< mha["gib_per_sequence"]
)
assert swa["gib_per_sequence"] < gqa["gib_per_sequence"]
@given(
prompt_tokens=st.integers(min_value=512, max_value=16_384),
batch_size=st.integers(min_value=1, max_value=64),
)
@settings(max_examples=25, database=None)
def test_21_hypothesis_ttft_monotonic_in_prompt_and_tps_monotonic_in_small_batch(
prompt_tokens: int,
batch_size: int,
) -> None:
m8 = ModelArchitectureSpec(
model_id="8b",
n_layers=32,
d_model=4096,
n_heads=32,
n_kv_heads=8,
d_head=128,
ffn_hidden=14336,
)
r_short = profile_prefill_and_decode_roofline(
m8, budget=ServingBudgetSpec(prompt_tokens=prompt_tokens, decode_batch_size=batch_size)
)
r_long = profile_prefill_and_decode_roofline(
m8, budget=ServingBudgetSpec(prompt_tokens=prompt_tokens * 2, decode_batch_size=batch_size)
)
r_big_batch = profile_prefill_and_decode_roofline(
m8, budget=ServingBudgetSpec(prompt_tokens=prompt_tokens, decode_batch_size=batch_size * 2)
)
assert r_long["ttft_ms"] > r_short["ttft_ms"]
assert r_big_batch["decode_tokens_per_sec"] > r_short["decode_tokens_per_sec"]
assert r_big_batch["decode_ai_flop_per_byte"] > r_short["decode_ai_flop_per_byte"]
@given(
headroom_gib=st.floats(min_value=16.0, max_value=192.0, allow_nan=False, allow_infinity=False),
)
@settings(max_examples=20, database=None)
def test_22_hypothesis_fp8_kv_doubles_or_more_concurrency_capacity(headroom_gib: float) -> None:
spec = AttentionSpec(arch_name="MLA", kind="mla")
bf16 = compute_kv_cache_sequence_metrics(spec, 65_536, "bf16", headroom_gib)
fp8 = compute_kv_cache_sequence_metrics(spec, 65_536, "fp8", headroom_gib)
assert fp8["max_concurrent_sequences"] >= 2 * bf16["max_concurrent_sequences"]
assert math.isclose(fp8["gib_per_sequence"] * 2.0, bf16["gib_per_sequence"], rel_tol=1e-3)
def test_23_cli_artifact_roundtrip_and_non_empty_panels(tmp_path: Path) -> None:
res = run_full_workbench_suite(seed=42)
out = tmp_path / "t2_ch21_wb21_results.json"
out.write_text(json.dumps(res, indent=2), encoding="utf-8")
loaded = json.loads(out.read_text(encoding="utf-8"))
assert loaded["unit_id"] == "T2-P4-U02"
assert len(loaded["workbench_panels"]["kpis"]) == 6
assert loaded["exp1_roofline_and_codesign"]["metric_origin"] == "analytical_roofline_equations"
assert loaded["exp2_kv_cache_landscape"]["metric_origin"] == "analytical_exact_kv_equations"
def test_24_untied_embedding_lookup_does_not_execute_full_vocab_gemv() -> None:
base_kwargs: dict[str, Any] = {
"n_layers": 32,
"d_model": 4096,
"n_heads": 32,
"n_kv_heads": 8,
"d_head": 128,
"ffn_hidden": 14336,
"vocab_size": 256_000,
}
m_tied = ModelArchitectureSpec(model_id="256k-tied", tied_embeddings=True, **base_kwargs)
m_untied = ModelArchitectureSpec(model_id="256k-untied", tied_embeddings=False, **base_kwargs)
p_tied = m_tied.param_breakdown()
p_untied = m_untied.param_breakdown()
# Untied stores an extra V x d matrix in VRAM (~2.0 GiB in BF16),
# while active decode GEMV parameters stay identical (embedding only reads 1 row/seq).
assert p_untied["total_params"] - p_tied["total_params"] == 256_000 * 4096
assert p_untied["active_gemv_params"] == p_tied["active_gemv_params"]
budget = ServingBudgetSpec(prompt_tokens=2048, output_tokens=256, decode_batch_size=1)
r_tied = profile_prefill_and_decode_roofline(m_tied, hw=H100_SXM, budget=budget)
r_untied = profile_prefill_and_decode_roofline(m_untied, hw=H100_SXM, budget=budget)
# Decode TPOT differs negligibly (<0.002ms from 1-row lookup) instead of +0.8ms bogus GEMV
assert abs(r_untied["tpot_ms"] - r_tied["tpot_ms"]) <= 0.01
assert r_untied["weight_gib_per_gpu"] > r_tied["weight_gib_per_gpu"] + 1.8
def test_25_moe_active_vs_total_params_b200_usable_vram_and_unified_reserve() -> None:
assert B200_SXM.vram_gib == 192.0
assert B200_SXM.effective_usable_vram_gib() == 180.0
exp1 = evaluate_model_codesign_suite()
moe = exp1["moe_codesign_comparison"]
b1 = moe["moe_8x7b_b1"]
b128 = moe["moe_8x7b_b128"]
dense = moe["dense_47b_matched_vram_b1"]
assert b1["total_params_b"] > 40.0
assert b1["active_params_b"] < 15.0
assert b1["tpot_ms"] < dense["tpot_ms"]
assert moe["b1_tpot_speedup_vs_dense_x"] >= 2.0
# At B=128, MoE reads almost all experts simultaneously, erasing B=1 bandwidth speedup over dense
assert b128["decode_ai_flop_per_byte"] > b1["decode_ai_flop_per_byte"] * 20.0
# Unified 16 GiB non-KV VRAM reserve in Exp 1 & Exp 2
m8 = next(r for r in exp1["sizing_comparison"] if r["model_id"] == "Llama3-8B-BF16 (1x H100)")
assert m8["reserved_vram_gib"] == 16.0
expected_kv = 80.0 - float(m8["weight_gib_per_gpu"]) - 16.0
assert m8["kv_headroom_gib_per_gpu"] == pytest.approx(expected_kv, abs=0.05)
exp2 = analyze_kv_cache_landscape(kv_headroom_gib=48.0, reserved_vram_gib=16.0)
assert exp2["reserved_vram_gib"] == 16.0
NVIDIA H100 SXM (989 TFLOP/s BF16, 3.35 TB/s HBM3, điểm gãy lý thuyết 295.22 FLOP/B, 16.0 GiB dự trữ hệ thống), kết quả WB-Ch21 (Exp 1) cho Llama3-8B-BF16 (S_in = 2048, B = 1) phản ánh đặc trưng vật lý nào?16.0 GiB reserve, còn 49.04 GiB KV headroom), một lần đọc trọng số 14.96 GiB phục vụ đồng thời 2,048 token (AI = 1941.08 FLOP/B >> 295.22, hoàn toàn compute_bound, TTFT = 66.02 ms). Trong decode B = 1, toàn bộ trọng số phải đọc lại chỉ cho 1 token (AI = 1.06 FLOP/B, memory_bound, TPOT = 7.29 ms, 137.1 tok/s).
B = 1..768 trên 8B-BF16 (H100, S_ctx = 128, Exp 1b), hệ thống chuyển biến thế nào khi tăng B vượt qua điểm gối cường độ số học?B <= 256 (AI = 199.91 < 208.17 FLOP/B hiệu dụng), thời gian đọc trọng số chi phối nên gom lô tăng thông lượng từ 139.1 lên 28,996.7 tok/s mà TPOT chỉ nhích 7.19 -> 8.83 ms. Từ B = 384 (269.84 FLOP/B), GPU chuyển sang compute_bound: thông lượng bão hòa quanh 31.8–33.8k tok/s còn TPOT tăng tuyến tính lên 22.73 ms ở B = 768.
16.0 GiB, vì sao Qwen-32B-BF16 (61.02 GiB) lọt gọn vào 80 GiB của 1x H100 nhưng trượt kiểm định WB-Ch21 (TTFT <= 300 ms, TPOT <= 25 ms), và FP8 hoặc B200 (180 GiB khả dụng / 192 GiB vật lý) giải quyết ra sao?16.0 GiB reserve, 32B-BF16 (61.02 GiB) chỉ còn 2.98 GiB KV và TPOT = 27.58 ms > 25 ms (tương tự 70B-BF16 TP2 đạt 305.18 ms / 35.93 ms). FP8 giảm 2x byte và tăng 2x TFLOPs giúp 32B-FP8 (132.84 / 15.23 ms) và 70B-FP8 TP2 (173.72 / 22.57 ms) đạt chuẩn; hoặc B200 SXM (180 GiB usable / 192 GiB vật lý, 8.0 TB/s) chạy 32B-BF16 đạt 118.39 / 13.22 ms.
Exp 1, Tests 06–07, 24–25), nhận định nào chính xác về Độ sâu vs Độ rộng (TP2), Untied Input Embed O(d) vs LM Head GEMV, và Mixtral-8x7B-MoE-BF16 (TP2)?Tests 06–07, 24–25: Shallow-Wide (L=32, d=5120) cắt nửa rào TP AllReduce (2.24 vs 4.48 ms) và giảm 2.0x KV (128 vs 256 KiB/tok), hạ TPOT 33.24% (7.45 vs 11.16 ms). Trên từ vựng 256k untied (2.097B, 23.11%), input embedding chỉ đọc 1 hàng O(d), chỉ LM Head chạy GEMV (active_gemv_params). Còn Mixtral-8x7B-MoE-BF16 TP2 lưu 46.701B nhưng chỉ quét 12.748B active mỗi token ở B=1, đạt TPOT = 8.61 ms (3.08x nhanh hơn Dense-47B 26.53 ms).
32 tầng (n_h = 32, d_h = 128) trên H100 80 GiB (16.0 GiB reserve + ~16 GiB trọng số 8B \(\implies\) 48.0 GiB headroom KV-cache), điều gì xảy ra ở 128k (BF16 KV) giữa MHA và MLA (d_c=512 + d_R=64)?Tests 08–09: Với 48.0 GiB KV headroom (80 - 16 reserve - ~16 weights), MHA BF16 = 2 * 32 * 32 * 128 * 2 = 524,288 B/tok (512 KiB/tok) -> 128k cần 64.0 GiB/chuỗi > 48.0 GiB (OOM). MLA chỉ lưu L * (d_c + d_R) * 2 = 32 * 576 * 2 = 36 KiB/tok (nén 14.22x nhờ hấp thụ ma trận \(W_{UK}, W_{UV}\) vào \(W_Q, W_O\)), chỉ còn 4.50 GiB/chuỗi (10 chuỗi).
Exp 2 (Tests 09–10), việc kết hợp Hybrid SWA (W = 4096, tỷ lệ 3:1 trên GQA-8) hoặc MLA với lượng tử hóa FP8 KV-cache mang lại năng lực phục vụ nào ở 128k và 1M token?Hybrid SWA (3:1), 24/32 tầng khóa trần KV tại W = 4096 và 8 tầng toàn cục lưu toàn chuỗi (4.375 GiB ở 128k BF16). Khi bật FP8 KV (1 byte), dung lượng giảm nửa: tại 128k MLA (2.25 GiB) và Hybrid SWA (2.1875 GiB) đạt 21 chuỗi, còn tại 1M (18.0 GiB / 16.1875 GiB) đều chạy được 2 chuỗi trên 48 GiB trong khi MHA (256 GiB) và GQA-8 (64 GiB) đều OOM.
Exp 3 (seed = 42, 180s, ngưỡng TTFT <= 500 ms & TPOT <= 35 ms, Test 12), điều gì xảy ra với Poisson FIFO khi đẩy tốc độ đến từ 6.0 lên 11.0 req/s?#22): tại 11.0 req/s, GPU chạy tối đa 100% công suất nên raw_total_tokens_per_sec đạt mức cao nhất 5,751.7 tok/s. Tuy nhiên, hàng đợi FIFO phình không giới hạn đẩy p99 TTFT lên 63,880.32 ms (gấp 127x SLO 500 ms), làm 0% yêu cầu đạt SLO và SLO Goodput = 0.000 req/s.
WB-Ch21 (Exp 3, Tests 13–14), lưu lượng Bursty (Gamma CV^2 = 4.0) tác động ra sao so với Poisson, và Kiểm soát Nạp Nhận thức SLO giải cứu hệ thống thế nào ở tải 11.0 req/s?CV^2 = 4.0), Bursty FIFO đẩy p99 TTFT ở 5.0 req/s lên 464.31 ms (gấp 2.63x mức 176.55 ms của Poisson) và sụp xuống 0.035 req/s tại 11.0 req/s. Khi bật SLO-Aware Admission Control (từ chối nhanh 839 yêu cầu tràn), toàn bộ 1,190 yêu cầu được phục vụ đạt 100.0% SLO (p99 TTFT = 403.29 ms, p99 TPOT = 32.33 ms), bảo toàn Goodput = 6.496 req/s.
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 — Đường mái H100 B200 (180 GiB Usable) và Khớp Gối Batch Size 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Tính \(I^* = \text{Peak TFLOP/s} / \text{HBM BW}\) trên H100 BF16 (989 / 3.35), đối chiếu 16.0 GiB reserve với B200 (180 GiB usable / 192 GiB vật lý) và quét B = 1..768.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Kiểm tra profile_prefill_and_decode_roofline trong src/llm_slo_goodput_lab/kv_attention_codesign.py và chạy pytest -k "test_03 or test_05 or test_21 or test_24" -v.
Tiêu chí Đáp án & Số đối chứng
H100 BF16 (16.0 GiB reserve) có ridge = 295.22 (eff = 208.17 FLOP/B). 8B-BF16 prefill (S=2048) đạt AI = 1941.08 (compute_bound, TTFT = 66.02 ms), còn B=1 decode chỉ đạt 1.06 FLOP/B (memory_bound, TPOT = 7.29 ms). Quét lô B = 1..256 tăng thông lượng 139.1 -> 28,996.7 tok/s (8.83 ms) trước khi sang compute_bound tại B = 384 (269.84 FLOP/B, 12.08 -> 22.73 ms, 33,793.4 tok/s).
Bài tập 2 — Đồng thiết kế FP8, MoE 8x7B, Untied LM Head GEMV và Depth vs Width 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Tách input embedding đọc 1 hàng O(d) khỏi LM Head GEMV (active_gemv_params), so sánh Mixtral-8x7B-MoE (12.748B active) với Dense-47B (TP2), và đếm số rào AllReduce 2*L giữa L=64 và L=32.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy pytest -k "test_04 or test_06 or test_07 or test_25" -v và kiểm tra moe_codesign_comparison, depth_vs_width, vocab_ablation trong artifacts/t2_ch21_wb21_results.json.
Tiêu chí Đáp án & Số đối chứng
32B-BF16 (27.58 ms) và 70B-BF16 TP2 (305.18 / 35.93 ms) trượt SLO nhưng FP8 đưa về 15.23 ms / 22.57 ms (hoặc B200 180 GiB đạt 13.22 ms). Mixtral-8x7B-MoE-BF16 (12.748B active) đạt 8.61 ms (3.08x vs Dense-47B 26.53 ms). Shallow-Wide (L=32, d=5120) giảm 33.24% TPOT (7.45 vs 11.16 ms) và 2.0x KV; SwiGLU 8/3 (6.688B vs 8.835B); 256k untied (2.097B, 23.11%) chỉ chạy GEMV tại LM Head.
Bài tập 3 — Phương trình KV-Cache Ngữ cảnh Dài 4k đến 1M Token 20%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Áp dụng công thức 2*L*n_kv*d_h*b_kv cho MHA/GQA/MQA, L*(d_c+d_R)*b_kv cho MLA, và tách L_global + L_local*min(S,W) cho Hybrid SWA (3:1) với 16.0 GiB reserve (48.0 GiB headroom).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy pytest -k "test_08 or test_09 or test_10 or test_20 or test_22" -v và đối chiếu highlights_128k_bf16, highlights_128k_fp8, highlights_1m_fp8.
Tiêu chí Đáp án & Số đối chứng
Trên 48.0 GiB headroom (16.0 GiB reserve), tại 128k BF16: MHA = 64.0 GiB (OOM: 0 seqs), GQA-8 = 16.0 GiB (3), MLA = 4.50 GiB (10, nén 14.22x), Hybrid SWA = 4.375 GiB (10), MQA = 2.0 GiB (24). Bật FP8 KV nâng MLA/SWA lên 21 chuỗi ở 128k và 2 chuỗi ở 1M.
Bài tập 4 — Phân tích Ảo ảnh Raw Tokens/s vs Sụp đổ SLO Goodput 20%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Quan sát hai đại lượng raw_total_tokens_per_sec và slo_goodput_rps trong Poisson FIFO khi \(\lambda\) tăng từ 6.0 lên 7.5 -> 9.0 -> 11.0 req/s.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Kiểm tra simulate_serving_queue_at_rate trong src/llm_slo_goodput_lab/slo_goodput_benchmark.py và chạy pytest -k "test_12 or test_15" -v.
Tiêu chí Đáp án & Số đối chứng
Khi quá tải (lambda = 11.0 req/s), GPU bão hòa kéo raw_total_tokens_per_sec lên đỉnh 5,751.7 tok/s, nhưng hàng đợi FIFO tích tụ đẩy p99 TTFT lên 63,880.32 ms khiến SLO Goodput (đạt TTFT <= 500 ms & TPOT <= 35 ms) sụp từ 5.535 (lambda=6.0) về 0.000 req/s.
Bài tập 5 — Lưu lượng Đột biến Bursty và Kiểm soát Nạp Bảo toàn SLO 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
So sánh độ trễ hàng đợi dưới CV^2 = 4.0 (Gamma) vs CV^2 = 1.0 (Poisson) theo công thức Pollaczek–Khinchine và vai trò ngưỡng admission_batch_cap=30, max_wait=300ms.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy pytest -k "test_13 or test_14" -v và đọc bảng table_goodput_poisson_vs_bursty trong artifacts/t2_ch21_wb21_results.json.
Tiêu chí Đáp án & Số đối chứng
Bursty FIFO đẩy p99 TTFT tại 5.0 req/s lên 464.31 ms (2.63x Poisson 176.55 ms), tụt đỉnh xuống 4.728 req/s và sụp về 0.035 req/s ở 11.0 req/s. Admission Control từ chối nhanh 839 yêu cầu tràn, giữ 100.0% SLO compliance (p99 TTFT = 403.29 ms, p99 TPOT = 32.33 ms) và Goodput = 6.496 req/s.
Bài tập 6 — Kiểm định AST, Bounded OpenTelemetry và Tái lập WB-Ch21 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Kiểm tra BoundedInMemorySpanExporter(maxlen=256), tính bất biến Pydantic extra="forbid", 0 # type: ignore và 0 time.sleep.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy trọn bộ run_lab_demo.py, ruff check src tests scripts, mypy src tests, pytest -p no:cacheprovider -v và uv lock --check.
Tiêu chí Đáp án & Số đối chứng
Xưởng đạt 25/25 pytest pass (gồm Hypothesis property tests & kiểm định B200 usable / MoE / Untied Embed), 0 lỗi ruff/mypy --strict, 0 # type: ignore, 0 time.sleep, xuất 5 OpenTelemetry spans sạch bí mật và đủ 6 KPI, 4 bar, 4 table trong workbench_panels.