Chương 23 — Bố cục Đa GPU, Phục vụ MoE Wide-EP, Định tuyến Nhận thức KV-Cache, Truy vết Đến Nhân GPU & CUDA Graphs
Chuyên đề #31–#35: TP2+DP4 đạt 7,790.5 tok/s (1.41x vs TP8), Wide-EP32 đạt 2,246.8 tok/s/GPU (3.10x vs TP8) và Greedy EPLB+LPT+PoC giảm lệch MoE 6.09x -> 1.05x/1.09x (DeepEP/DeepGEMM/DualPipe), định tuyến tiền tố có ràng buộc tải đạt 74.17% hit & p99 275.49 ms (8.21x vs Unbounded), PyTorch Profiler + 39 OTel spans & Piecewise CUDA Graphs 7,450.3 tok/s (2.76x Eager).
Unit ID:
T2-P4-U04
Track & Part: Track 2 (EDAI) — Part 4: Production ML & LLM Serving Systems (part-04-ml-and-llm-serving-systems)
Cầu nối Từ Chương 22 (Part 4): Nếu Chương 22 tối ưu hóa nội tại một bản sao động cơ suy luận (Chunked Prefill,PagedAttention,RadixAttention, tách rờiP/D,Speculative Decodingvà lượng tử hóa), thì Chương 23 mở rộng quy mô ra cụm đa GPU và đa bản sao phân tán (#31–#35): chọn đúng kiến trúc song song (TP/PP/DP/CP), phục vụ mô hình thưaMoEbằngWide-EPchống lệch tải Zipfian, định tuyếnKV-Cachegiữa hàng loạt bản sao không tạo điểm nóng, truy vết nghẽn từ yêu cầu mạng đến nhân CUDA, và cắt đứt chi phí CPU launch bằngPiecewise CUDA Graphs.
Truy xuất Giáo trình Gốc (R42, Chuyên đề#31–#35): Block 4: Dive into LLM-serving (KV cache,LLM serving challenges and solutions,vLLM,TensorRT-LLM,SGLang); Serving Mixture-of-Experts Models Across GPUs (#31); Picking a Multi-GPU Layout for LLM Inference (#32); Cache-Aware Routing Across LLM Replicas (#33); Profiling LLM Inference from Request Trace to GPU Kernel (#34); CUDA Graphs for LLM Serving with Variable Shapes (#35) trong 02-track-edai-raw-curriculum.md và 02-track-2-edai-sota-syllabus.md
Bài thực hành Song hành (Lab 18): labs/lab-18-trace-to-kernel-profiling-and-cuda-graphs/README.md (multi_gpu_profiling_cudagraph_lab)
Tình huống Mở đầu: Năm Cú Sập Cụm GPU Quy mô Lớn Dù Từng Node Đơn Chạy Rất Mượt#
Khi đưa cụm suy luận từ 1 GPU thử nghiệm lên hệ thống sản xuất 8–32 GPU và nhiều bản sao đằng sau Gateway, đội ngũ hạ tầng thường vấp phải năm cú sốc định lượng sau (đều được tái hiện xác định với seed=42 trong Lab 18):
- Ép
TP8Mù quáng & Rơi XuốngPCIeLàmTPOTVỡ5.03x(#32): Phục vụ mô hình70B FP8(~70 GBtrọng số) trên8x H100(SLOTTFT <= 500 ms,TPOT <= 25 ms), việc dùng cấu hìnhTP8quaPCIe Gen5(64 GB/s, không cóNVLink) đẩy chi phí đồng bộAll-Reducelên84.81%bước lặp, làmTPOTvọt từ5.75 mslên28.91 ms(5.03xchậm hơn, vỡ SLO,0.43 req/sGoodput)! Ngay cả trênNVLink,PP8vẫn chịu30.43%bong bóng đường ống và27.92 msTPOT (vỡ SLO). Ngược lại, bố cụcTP2 + DP4(NVLink,4bản sao độc lập) đạt7,790.5 tok/s(30.43 req/sGoodput) — nhanh hơn1.41xvề thông lượng và rẻ hơn1.41x($0.8557/1Mvs$1.2025/1Mtokens) so vớiTP8 NVLink. - Chạy
MoETheo KiểuTP8Lãng phíKV& Lệch Tải Zipfian Gây Nghẽn6.09x(#31): Với mô hìnhSparse MoEchuẩnDeepSeek-V3(256chuyên gia,Top-K = 8,1chuyên gia dùng chung,FP8), chạyTP8làm phân mảnh ma trận (m_e = 4.0token/chuyên gia) và nhân bảnKV-Cachegấp8x(725.5 tok/s/GPU). Chuyển sangDP8 + EP8(Attention chạyDP, Experts chạyEP) giải phóng8xsức chứaKV, nhưng dưới phân phối Zipfian thực (s = 1.15), các chuyên gia nóng tạo ra nút nghẽn lệch6.09x(43.55 ms/step)! Áp dụngEPLBtham lam (48khe chuyên gia nóng dư thừa + đóng góiLPT+ điều phốiPower-of-Choice) kéo độ lệch xuống tự nhiên còn1.05x(5.80xcân bằng hơn), nâng tốc độ lên1,916.3 tok/s/GPU(15,330.2 tok/s); mở rộng lênWide-EP32(gối đầuDualPipe/DeepEPẩnAll-to-All) đạt2,246.8 tok/s/GPU(71,898.3 tok/scụm,1.09xskew, gấp3.10xmỗi GPU so vớiTP8). - Định tuyến Dính Tiền tố Không Giới hạn Làm Nổ Điểm Nóng
2,261.66 msTrên1/8Bản sao (#33): Trên240yêu cầu lệch Zipfian (46%dùng chung1system prompt1,536token) qua8bản sao (TTFT <= 550 ms),Round-Robinphá vỡ cache (50.83%hit,p99 TTFT = 831.83 ms,92.08%SLO). Chuyển sangPrefix-Aware Unboundedđạt97.5%hit nhưng dồn118/240yêu cầu vào đúng1bản sao (max load = 3.77x), làmp99 TTFTnổ tung lên2,261.66 ms(58.33%SLO). BậtCache-Aware Load-Bounded(load_bound_factor = 1.25) giữ74.17%hit (+23.34 ppvs RR), khóa tải ở1.41x, hạp99 TTFTxuống275.49 ms(8.21xnhanh hơn Unbounded) và đạt100.0%SLO (58.25 req/s). - Hồ sơ
nvidia-smiBáo Đầy Dù GPU Đang Ngồi Chờ63.78%Bọt Khí CPU (#34): Thực nghiệmPyTorch CPU Profilerthật (torch.profiler.profile) cho thấy cùng một mạng Transformer4tầng nhưng tách nhỏ từng đầu chú ý tạo ra1,668lệnh ATen (3lượt), so với444lệnh ATen khi hợp nhất (3.76xít hơn). Trên thácOpenTelemetry6 tầng, chế độcpu_launch_boundphơi bày63.78%thời gian GPU ngồi chơi chờ CPU phát lệnh, tách biệt rạch ròi vớihbm_bandwidth_bound(75.26%đọc HBM) vànccl_comm_bound(69.58%NCCL). Eager ModeĐốt5.18 ms/stepPhát Lệnh &Monolithic CUDA GraphNổ8.64 GiBVRAM (#35): Trên120bước batch & chiều dài chuỗi biến thiên,Eagertốn5.18 ms/stepchỉ để đẩy280kernel nhỏ (2,698.5 tok/s). ChụpMonolithic 2D (batch x seq)ngốn8.64 GiBVRAM (vượt ngưỡng3.5 GiB) và lãng phí26.08%batch +26.78%seq padding. Kiến trúcPiecewise CUDA Graphs+ Xô Hỗn hợp ([1,2,4,8,16,24,32,48,64,96,128]) cắt chi phí phát lệnh xuống0.38 ms(13.63x), xóa sạch0.0%đệm chiều dàiKV, hạ padding batch xuống11.05%(1.67xtốt hơn Power-of-2) chỉ với1.76 GiBVRAM, đạt7,450.3 tok/s(2.76xnhanh hơnEager).
Mục tiêu Học tập (Learning Objectives)#
Sau Chương 23 và Lab 18 (multi_gpu_profiling_cudagraph_lab), kỹ sư Hệ thống ML/LLM làm chủ năm năng lực cấp Principal:
- Thiết kế Bố cục Đa GPU
TP/PP/DP/CP(#32): Định lượng phương trìnhHockney All-Reduce, bong bóng đường ốngPPvà bộ nhớ kích hoạtContext Parallelism(Ring Attention) trênNVLinkvsPCIe/InfiniBandđể tối ưu đồng thờiTPOT SLOvà chi phí$/1M tokens. - Vận hành Mô hình
Sparse MoEQuy mô Lớn (#31): Phân biệtTP8vớiDP+EPvàWide-EP, tính toán giao tiếpAll-to-All Dispatch/Combine, chẩn đoán lệch tải Zipfian (straggler ratio) và thiết kế nhân bản chuyên gia nóng dư thừa (EPLB). - Xây dựng Bộ Định tuyến Cụm Nhận thức
KV-Cache(#33): Thiết kế bộ định tuyến Consistent Hashing Có Giới hạn Tải (Cache-Aware Load-Bounded,SGLang Router/llm-d/Dynamo) giữ tỷ lệ trúng tiền tố toàn cụm cao mà không làm quá tải cục bộ bất kỳ bản sao nào. - Phân tích Hồ sơ Từ Truy vết Yêu cầu Đến Nhân GPU (
#34): Kết hợpOpenTelemetryWaterfall Spans,PyTorch Profiler(torch.profiler),Nsight Systems(nsys) vàNsight Compute(ncu) để phân loại dứt khoát 4 chế độ nghẽn (CPU-Launch,HBM-BW,NCCL-Comm,Balanced). - Tối ưu Thực thi Động Bằng
Piecewise CUDA Graphs(#35): Thiết kế xô lô hỗn hợp (Hybrid Buckets) tách rời các đoạn tuyến tính (QKV,MLP,Norm,RoPE) vàoCUDA Graphtrong khi chạyPagedAttention varlenđộng bên ngoài — cân bằng giữa chi phí phát lệnh CPU, padding compute và ngân sách VRAM bể đồ thị.
Bảng Truy xuất Giáo trình Gốc sang Chuẩn SOTA 2026 (Unit T2-P4-U04)#
Nội dung Gốc (R42) & Chuyên đề Sâu |
Nâng cấp Chuẩn SOTA 2026 (ch-23) |
Mục trong Chương 23 | Tạo tác & Kiểm thử (multi_gpu_profiling_cudagraph_lab) |
|---|---|---|---|
1. #32 Picking a Multi-GPU Layout (TP/PP/DP/CP) |
So sánh 5 cấu trúc 8x H100 (70B FP8): TP2+DP4 (7,790.5 tok/s, $0.8557/1M, 1.41x) vs TP8 NVLink vs TP8 PCIe (28.91 ms TPOT, FAIL) vs PP8 (30.43% bubble) + CP4+TP2 128k (1.44x ít RAM) |
Trụ cột 1 (§1.1) + Mermaid 1 + Widget 1 | evaluate_multi_gpu_layouts, evaluate_context_parallel_long_prefill, Tests 02–05 |
2. #31 Serving MoE Across GPUs (EP, Wide-EP, EPLB, DeepEP/DeepGEMM/DualPipe) |
Mô phỏng DeepSeek-V3 (256 experts, Top-K=8, zipf_s=1.15): TP8 (725.5) vs DP8+EP8 lệch (6.09x) vs EPLB 48 khe + Po2 (1.05x, 1,916.3) vs Wide-EP32 (2,246.8 tok/s/GPU, 3.10x, 1.09x skew, 32x KV) |
Trụ cột 1 (§1.2) + Mermaid 1 + Widget 1 | simulate_moe_ep_serving, sweep_moe_zipf_skew, Tests 06–07, 28 |
3. #33 Cache-Aware Routing Across LLM Replicas |
240 yêu cầu lệch Zipfian qua 8 bản sao (TTFT<=550ms): RR (50.83% hit, 831.83 ms), Unbounded (2,261.66 ms, 3.77x load) vs Load-Bounded 1.25x (74.17% hit, 275.49 ms p99, 100% SLO) |
Trụ cột 1 (§1.3) + Mermaid 2 + Widget 2 | simulate_cache_aware_routing, Tests 08–09 |
4. #34 Profiling Inference: Trace to GPU Kernel |
PyTorch CPU Profiler thực (1,668 -> 444 ATen ops, 3.76x) + Thác OTel 39 spans phân loại 4 chế độ (63.78% CPU bubble vs 75.26% HBM vs 69.58% NCCL vs 13.35% balanced) |
Trụ cột 1 (§1.4) + Trụ cột 3 + Mermaid 3 + Widget 3 | run_pytorch_cpu_op_profiling, run_request_to_kernel_profiling, Tests 10–12 |
5. #35 CUDA Graphs with Variable Shapes |
120 bước động: Eager (5.18 ms launch) vs Monolithic 2D (8.64 GiB OOM) vs Power-of-2 (18.48% pad) vs Piecewise Hybrid (0.38 ms, 13.63x cut, 11.05% pad, 1.76 GiB, 2.76x tok/s) |
Trụ cột 1 (§1.5) + Mermaid 3 + Widget 3 | simulate_cuda_graph_bucketing, Tests 13–14 |
6. Config Audit YAML & Bounded OTel |
Kiểm toán sạch 2/2 YAML (0 bí mật, 0 :latest, 3 image ghim, 127.0.0.1) & 39 OTel spans sạch (clean_attributes=True) |
Trụ cột 2 & 4 | configs/*.yaml, audit_lab18_configs, Tests 15–28 |
Bảng Ký hiệu Thống nhất Xuyên suốt Chương 23 (Unified Notation)#
| Ký hiệu | Miền / Đơn vị | Định nghĩa Chính xác Trong Chương 23 & multi_gpu_profiling_cudagraph_lab |
Giá trị Thực nghiệm Lab 18 (seed=42) |
|---|---|---|---|
| \(\text{TP}, \text{PP}, \text{DP}, \text{CP}, \text{EP}\) | Số nguyên | Bậc song song Tensor, Pipeline, Data, Context và Expert trên cụm GPU | Tối ưu 70B FP8: TP2+DP4 (7,790.5 tok/s); MoE: Wide-EP32 (2,246.8 tok/s/GPU) |
| \(T_{\text{allreduce}}, B_{\text{pp}}\) | \(\text{ms}, \%\) | Độ trễ tập thể Hockney \(\alpha + \frac{2(P-1)}{P}\frac{M}{BW}\) và tỷ lệ bong bóng pipeline \(\frac{p-1}{m+p-1}\) | TP8 PCIe: 84.81% comm (28.91 ms TPOT); PP8: 30.43% bubble (27.92 ms) |
| \(s_{\text{zipf}}, R_{\text{strag}}\) | Số thực, (\(\times\)) | Tham số lệch Zipfian chuyên gia MoE và tỷ số tải nút chậm nhất \(\max/\text{mean}\) | DP8+EP8 lệch: 6.09x \(\to\) EPLB + Po2 thật: 1.05x (5.80x cân bằng hơn) |
| \(H_{\text{cluster}}, c_{\text{bound}}\) | \(\%\), Hệ số | Tỷ lệ trúng tiền tố KV toàn cụm \(8\) bản sao và hệ số trần tải định tuyến |
Load-Bounded (1.25x): 74.17% hit, 275.49 ms p99 (8.21x vs Unbounded 2,261.66 ms) |
| \(\phi_{\text{cpu}}, \phi_{\text{nccl}}, \phi_{\text{hbm}}\) | \(\%\) | Tỷ trọng thời gian bước suy luận ở CPU launch, NCCL comm, và HBM read |
cpu_launch_bound: 63.78% bubble vs balanced: 13.35%, PyTorch 3.76x ít ATen op |
| \(W_{\text{pad}}, M_{\text{graph}}\) | \(\%, \text{GiB}\) | Tỷ lệ tính toán thừa do padding xô batch và VRAM giữ bể đồ thị CUDA Graph |
Monolithic 2D: 8.64 GiB OOM vs Piecewise Hybrid: 1.76 GiB, 11.05% pad, 2.76x tok/s |
Trụ cột 1 — Nguyên lý Gốc & Frontier: Đa GPU, MoE Wide-EP, Định tuyến KV-Cache, Truy vết & CUDA Graphs#
1.1 Chuyên đề #32: Lựa chọn Bố cục Đa GPU (TP, PP, DP, CP) Trên Từng Loại Hạ tầng Mạng#
1. Cơ chế Gốc & Mô hình Toán học (Hockney All-Reduce, Bong bóng PP, CP)#
Khi trọng số mô hình hoặc thông lượng vượt giới hạn 1 GPU (80 GiB H100 SXM), bốn chiều song song tạo thành một không gian đánh đổi chặt chẽ về băng thông liên kết, bộ nhớ KV-Cache và độ trễ từng bước:
-
Tensor Parallelism (
TP): Chia đôi từng ma trận cột/hàng trong mỗi lớp Transformer. Trên mỗi GPU thuộc một tầngPPchứa \(L / \text{PP}\) lớp,TPđòi hỏi2phépAll-Reducemỗi lớp (tức \(2(L/\text{PP})\) rào đồng bộ trong một giai đoạn đường ống — bằng160lần khi \(\text{PP}=1, L=80\)):\[T_{\text{allreduce}}(P, M_{\text{bytes}}) = \alpha_{\text{eff}}(P) + \frac{2(P - 1)}{P} \cdot \frac{M_{\text{bytes}}}{BW_{\text{link}}}\]TPcắt giảm trực tiếp cảTTFTlẫnTPOTvà chia nhỏKV-Cachetheo \(1/\text{TP}\), nhưng cực kỳ nhạy với độ trễ khởi tạo \(\alpha\) và băng thông liên kết \(BW_{\text{link}}\). 2. Pipeline Parallelism (PP): Chia theo chiều dọc các tầng (\(L / \text{PP}\) tầng mỗi GPU), chỉ truyền tensor kích hoạt biên quaP2P Send/Recv. Tuy tốn rất ít băng thông mạng và giảm số phépAll-Reducetrên mỗi giai đoạn xuống \(L / \text{PP}\),PPsinh ra bong bóng đường ống (Pipeline Bubble) tỷ lệ \(\frac{p - 1}{m + p - 1}\) (\(m\) là số microbatch) và không giảm độ trễ đơn luồngTPOTvì mỗi token vẫn đi tuần tự qua toàn bộ \(p\) giai đoạn. 3. Data Parallelism (DP): Tạo \(D\) bản sao độc lập hoàn toàn (0giao tiếpNCCLgiữa các bản sao). Khi trọng số đã lọt vào \(1\) nhómTPnhỏ (TP=1,2, hoặc4), tăngDPnhân tuyến tính thông lượng cụm và hạ mạnh chi phí$/1M tokens. 4. Context Parallelism (CP): Chia theo chiều dài chuỗi token \(S\) (Ring Attention/Ulysses) choPrefillngữ cảnh siêu dài (128k–1M), giảm \(1/\text{CP}\) bộ nhớ kích hoạt mà không bị giới hạn bởi số lượng đầuKVít ỏi củaGQA-8.
2. Đánh đổi Kiến trúc & Thực nghiệm Lab 18 Trên 8x H100 (70B FP8, TTFT <= 500 ms, TPOT <= 25 ms)#
Bố cục Cụm (8 GPU) |
Băng thông & Giao tiếp | TTFT / TPOT |
Comm % / Bubble % |
Thông lượng & Chi phí ($3/GPU-hr) |
Phán quyết SLO |
|---|---|---|---|---|---|
TP8_NVLink |
NVLink 900 GB/s |
44.52 ms / 5.75 ms |
23.69% / 0.0% |
5,544.0 tok/s ($1.2025/1M) |
Đạt (Ưu tiên TPOT siêu thấp) |
TP8_PCIe_Mismatch |
PCIe 64 GB/s (Không NVLink) |
442.75 ms / 28.91 ms |
84.81% / 0.0% |
1,106.3 tok/s ($6.0262/1M) |
VỠ SLO (5.03x chậm hơn!) |
PP8_NVLink (m=16) |
NVLink P2P tuần tự 8 tầng |
38.00 ms / 27.92 ms |
66.46% / 30.43% |
796.8 tok/s ($8.3664/1M) |
VỠ SLO (Bong bóng & trễ nối tầng) |
TP4_PP2_NVLink |
NVLink nội tầng (40 lớp/giai đoạn) + P2P |
39.04 ms / 8.28 ms |
40.11% / 5.88% |
3,629.8 tok/s ($1.8367/1M) |
Đạt (Phù hợp mô hình >140B) |
TP2_DP4_NVLink_FP8 |
NVLink TP2 \(\times\) 4 bản sao DP |
137.84 ms / 16.36 ms |
2.72% / 0.0% |
7,790.5 tok/s ($0.8557/1M) |
Tối ưu Tốt nhất (1.41x tok/s & giá) |
- Mở rộng Ngữ cảnh
128k(evaluate_context_parallel_long_prefill): So vớiTP8(14.0 GiB/GPUbộ nhớ kích hoạt đỉnh,1,516.01 msTTFT,160barriers), kết hợpCP4 + TP2 Ring Attention(gối đầu trao đổiKVtheo vòng88.5%) cắt giảm1.44xbộ nhớ kích hoạt xuống9.7 GiB/GPU, hạ ràoAll-Reducexuống80và rútTTFTcòn1,389.15 ms.
3. Các Tình huống Lỗi Thực tế (Failure Modes & Traps)#
- Rơi Xuống
PCIeKhi ChạyTP >= 4(TP8_PCIe_Mismatch): Trên các VM đám mây không gắn cầuNVLink/NVSwitch, băng thông hiệu dụng rớt còn~24 GB/svới độ trễ nhảy node \(\alpha \approx 115\,\mu\text{s}\). Vì160phépAll-Reducechạy tuần tự theo từng lớp, thời gian đồng bộ chiếm84.81%toàn bộ bước decode và đẩyTPOTlên28.91 ms(vỡ SLO25 msdù GPU tính toán rảnh rỗi). - Dùng
PPQuá Sâu Cho Dịch vụ Tương tác (PP8_NVLink):PP8cắt giảm lưu lượng liên kết nhưng khóa chết luồng xử lý từng token qua7rào chuyển tiếp liên tầng +30.43%bong bóng (TPOT = 27.92 ms, thông lượng sụp còn796.8 tok/s, đắt nhất cụm\$8.3664/1M tokens). - Ép
TPVượt Quá Số ĐầuKVỞ Ngữ cảnh Dài: Trên mô hìnhGQA-8, nângTPtừ8lên16buộc phải nhân bảnKV-Cachelên2xtrên mỗi nửa cụm, vừa lãng phí HBM vừa tăng gấp đôi số ràoAll-Reducethay vì dùngCP.
4. Quy tắc Ra quyết định Sản xuất (#32)#
- Kiểm tra topo trước khi chia
TP: Chỉ bậtTP2/TP4/TP8bên trong cùng một miềnNVLink/NVSwitch; nếu chỉ cóPCIe/Ethernet, dùngDPhoàn toàn (hoặc giữPP2tối đa nếu bất khả kháng). - Ưu tiên
TPnhỏ nhất nhét vừa trọng số + đệmKV: Với70B FP8trên8x H100, chọnTP2+DP4(35 GBtrọng số +37 GBheadroomKV/GPU,$0.8557/1Mtokens); chỉ dùngTP8khi ứng dụng giọng nói/agent épTPOT < 8 ms. - Chuyển sang
CP + TPcho chuỗi>= 128k: GiữTP <= num_kv_headsvà chia phần ngữ cảnh theoCP(Ring Attention/Ulysses) để cắt đỉnh activation mà không trùng lặpKV.
1.2 Chuyên đề #31: Phục vụ Mô hình Mixture-of-Experts (MoE) Qua Nhiều GPU (EP, Wide-EP, EPLB & Bộ ba DeepSeek Stack)#
1. Cơ chế Gốc & Mô hình Toán học (DP+EP, Wide-EP, DeepEP, DeepGEMM, DualPipe)#
Với mô hình thưa như DeepSeek-V3 (256 chuyên gia định tuyến, chọn Top-K = 8 mỗi token, cộng 1 chuyên gia dùng chung shared expert, 61 lớp, FP8), mỗi token chỉ kích hoạt 37B trong tổng số 671B tham số:
- Vì sao
TP8_DenseStylesụp đổ: Nếu chia1/8từng chuyên gia lên mỗi GPU ở lôB = 128, trung bình mỗi chuyên gia chỉ nhận \(\bar{m}_e = \frac{128 \times 8}{256} = 4.0\) token! Chia nhỏ ma trận theoTP8làm kích thướcGEMMquá bé để bão hòa Tensor Core, đồng thời8GPU phải lưu8bản saoKV-Cachegiống hệt nhau (725.5 tok/s/GPU,5,803.7 tok/scụm). - Giải pháp SOTA 2025–2026 (
DPAttention +Wide-EP+ Bộ baDeepSeek):DPcho Attention +EPcho Experts: Mỗi GPU giữ lô yêu cầuKVđộc lập (\(\implies\) nhân sức chứaKV-Cachelên \(N\times\):8xởEP8,32xởWide-EP32), đồng thời gộp lô lớn cho từng chuyên gia (\(\bar{m}_e = 32.0\) token ởWide-EP32, bão hòa Tensor Core FP8!).- Nhân bản Chuyên gia Nóng Dư thừa (
EPLB— Expert Parallelism Load Balancer): Phân phối gọi chuyên gia thực tế tuân theo luật Zipf (\(p_r \propto r^{-s}\), \(s \approx 1.15\)).EPLBlấy mẫu cửa sổ trượt lịch sử gần nhất \(\hat{p}_e\), lặp tham lamgreedy replica allocationbằng cách cộng thêm khe bản sao cho chuyên gia có tải trên mỗi bản sao lớn nhất:\[e^\star = \arg\max_{e:\, c_e < \text{EP}} \frac{\hat{p}_e}{c_e}, \quad c_{e^\star} \leftarrow c_{e^\star} + 1\]Sau đó đóng gói toàn bộ \((E + R_{\text{hot}})\) khe vật lý vàoEPGPU qua thuật toánLPT(Longest-Processing-Time-First) sao cho mỗi GPU có số khe cân bằng; cuối cùng tại lúc chạy, mỗirank DPphân phát token bằngPower-of-Choice(2-choice least-loaded) trên các bản sao khả dụng của chuyên gia đó. - Bộ ba Phần cứng/Kernel
DeepSeekStack (Bảng 5 SOTA):DeepEP: Thư viện giao tiếpNVSHMEMbất đồng bộ RDMA chuyên biệt choMoE All-to-All Dispatch/Combine, loại bỏ đồng bộNCCLnặng nề ở pha decode trễ thấp và gối đầu truyền mạng trực tiếp với tính toán SM.DeepGEMM: Bộ sinh nhânFP8 DeepJIT(biên dịch tức thời grouped GEMM) dùng cơ chế cân chỉnh tỷ lệ theo khối hạt mịn (fine-grained1x128activation /128x128weight block scaling), giữ sai số FP8 cực thấp ngay cả khi chiều \(M_e\) biến thiên bất thường giữa các chuyên gia.DualPipe: Lập lịch hai microbatch hai chiều (bidirectional two-microbatch overlap) luân phiên gối đầu phaAll-to-All Dispatch/CombinecủaEPphía sau phép tínhAttentionvàShared Expert, che phủ phần lớn thời gian truyền liên node (~68%chi phíAll-to-Allbị ẩn trongWide-EP32, chỉ lộ1.04 ms/step!).
2. Đánh đổi & Thực nghiệm Quét Lệch Tải Zipfian Trong Lab 18 (sweep_moe_zipf_skew)#
Khi để lộ nguyên bản không nhân bản (redundant_hot_experts = 0) trên DP8+EP8, rào đồng bộ All-to-All Combine buộc toàn cụm chờ GPU chậm nhất (straggler):
- Khi \(s = 0.0\) (phân phối đều):
DP8+EP8lệch nhẹ1.09x(15,074.2 tok/s), cònEPLBđạt1.07x(15,217.0 tok/s). - Khi \(s = 0.70 \to 1.15 \to 1.50\): Không nhân bản khiến tỷ số straggler vọt từ
3.63x\(\to\)6.09x\(\to\)7.28x, kéo thông lượng cụmDP8+EP8rơi tự do từ15,074.2xuống8,400.6, rồi5,878.3(s=1.15,43.55 ms/step) và5,131.8 tok/s(s=1.5)! - Khi bật
EPLBthật (48khe bản sao + đóng góiLPT+ điều phốiPower-of-Choicegiữa các DP rank): ở \(s = 0.70 \to 1.15 \to 1.50\), tỷ số straggler giữ tự nhiên ở1.04x\(\to\)1.05x\(\to\)1.06x(giảm5.80xđộ lệch tạis=1.15mà không cần kẹp cứng!), giữ vững15,330.2 tok/s(1,916.3 tok/s/GPU, gấp2.64xvsTP8_DenseStyle)! - Mở rộng lên
Wide-EP32(DP32+EP32,64khe nóng dư thừa, lô toàn cụm1,024, \(\bar{m}_e = 32.0\) token/chuyên gia, gối đầuDualPipe/DeepEPcòn1.04 msAll-to-Alllộ diện): tỷ số straggler thực đo là1.09x(14.24 ms/step), đạt2,246.8 tok/s/GPU(71,898.3 tok/stoàn cụm, gấp3.10xmỗi GPU so vớiTP8_DenseStyle) với sức chứaKV-Cachetăng32x!
3. Các Tình huống Lỗi Thực tế (Failure Modes & Traps)#
- Đặt Kịch bản Chuyên gia Nóng Cố định Mà Không Đóng gói Lại
LPT: Nếu giữ nguyên vị tríbase_ownertĩnh (dồn toàn bộtop-8chuyên gia nóng lên GPU 0), ngay cả khi thêm bản sao phụ, GPU 0 vẫn bị kẹt bởi phần dư của chính các chuyên gia đó trên cụmEP32. Phải chạy lại đóng gói cân bằngLPTđịnh kỳ (eplb_rebalance_interval_steps: 200). - Thả Độc Lập
EPKhông Gối Đầu (Unoverlapped All-to-All): KhiWide-EP32vượt qua ranh giới1nodeNVLinksangInfiniBand NDR, độ trễAll-to-Allchưa che phủ (~3.25 ms) sẽ ăn hết lợi íchGEMMnếu không tách 2 microbatch kiểuDualPipe+DeepEP. - Khóa Chặt Một Bản sao Duy nhất Trong Dispatch: Khi thiếu điều phối Power-of-Choice theo tải hàng đợi cục bộ tại từng DP rank, dao động vi mô từng batch vẫn có thể tạo điểm nóng tạm thời dù trọng số trung bình đã chia đều.
4. Quy tắc Ra quyết định Sản xuất (#31)#
- Tách
PrefillvàDecodechoMoElớn: DùngTP8/EP8hoặcDP+EPvừa cho cụmPrefill(bão hòaDeepGEMMtức thì) và triển khaiWide-EP32/64+DeepEP+DualPipecho cụmDecodenhằm mở khóa32x–64xdung lượngKV-Cache. - Luôn dự phòng
10%–25%khe VRAM choEPLB(+1tới+2chuyên gia nóng/GPU): Chạy cân bằng lại định kỳ mỗi200bước dựa trên EMA đếm token, phối hợp Power-of-Choice tại dispatcher.
1.3 Chuyên đề #33: Định tuyến Nhận thức KV-Cache Qua Nhiều Bản sao (Cache-Aware Prefix Routing)#
1. Cơ chế Gốc & Toán học (Consistent Hashing with Bounded Loads)#
Khi vận hành \(R = 8\) bản sao độc lập (mỗi bản sao có cây RadixAttention hoặc bảng APC cục bộ chứa 192 khối KV \(\times 16 = 3,072\) token), bộ cân bằng tải ở tầng Gateway quyết định trực tiếp tỷ lệ tái sử dụng KV-Cache lẫn độ trễ đuôi p99 TTFT. Với hàm băm Rendezvous nhất quán sinh vòng ứng viên \([r_0, r_1, \dots, r_{R-1}]\) từ mã băm tiền tố SHA-256(prefix_id), thuật toán Giới hạn Tải (c_bound) chỉ chuyển tiếp vào bản sao đứng đầu \(r_0\) khi thỏa điều kiện sức chứa cục bộ:
Nếu vi phạm, yêu cầu tràn có kiểm soát sang ứng viên thứ cấp ấm kế tiếp \(r_k\) trong vòng băm (giữ bản sao thứ hai của tiền tố nóng), thay vì rơi vào sập hàng đợi như định tuyến không giới hạn.
2. Đánh đổi & Thực nghiệm Lab 18 Trên 240 Yêu cầu Lệch Zipfian (62 req/s, 46% Hot Prefix)#
Chính sách Định tuyến (8 Bản sao, TTFT SLO <= 550 ms) |
Tỷ lệ Trúng KV Toàn cụm |
avg TTFT / p99 TTFT |
Tỷ lệ Lệch Tải Max | SLO Attainment & Goodput |
|---|---|---|---|---|
round_robin (req_id % 8) |
50.83% |
206.81 ms / 831.83 ms |
1.28x |
92.08% (47.50 req/s — Vỡ SLO) |
least_loaded (argmin(queue)) |
50.00% |
133.99 ms / 335.53 ms |
1.03x |
100.0% (58.82 req/s) |
prefix_aware_unbounded (Dính cứng chủ tiền tố) |
97.50% |
683.78 ms / 2,261.66 ms |
3.77x (Nổ 1 nút!) |
58.33% (22.44 req/s — SẬP!) |
cache_aware_load_bounded (c_bound = 1.25) |
74.17% (+23.34 pp vs RR) |
91.78 ms / 275.49 ms |
1.41x |
100.0% (58.25 req/s) |
3. Các Tình huống Lỗi Thực tế (Failure Modes & Traps)#
- Hội chứng Điểm nóng Trên
Prefix-Aware Unbounded: Dù đạt97.5%tỷ lệ trúng cache, việc tiền tố nóng (46%lưu lượng cụm) bị dính cứng vào duy nhấtReplica 1(118/240yêu cầu,max load = 3.77x) khiến hàng đợi trênReplica 1phình to đẩyp99 TTFTvọt lên2,261.66 ms(58.33%SLO), trong khi3bản sao khác (Replica 0, 5, 6) ngồi chơi với0yêu cầu! - Định tuyến
Round-RobinPhá VỡPrefix Cache: Chia đều mù quáng phân tán cùng một system prompt ra cả8bản sao (50.83%hit), buộc mọi bản sao tính lại prefill1,536token liên tục làm tăngp99 TTFTlên831.83 ms. - Đặt
c_boundQuá Chặt (<= 1.02) Hoặc Quá Lỏng (>= 2.5): Quá chặt thoái hóa vềLeast-Loadedmất lợi thế hit (50%); quá lỏng thoái hóa vềUnboundedsập đuôip99.
4. Quy tắc Ra quyết định Sản xuất (#33)#
- Triển khai
Cache-Aware Load-Bounded(SGLang Router,llm-d,NVIDIA Dynamo): Đặtload_bound_factor = 1.25, ngưỡng chờ dự kiến<= 90 msvàconsistent_hash_virtual_nodes >= 150. - Giữ ấm tối thiểu
2bản sao cho mỗi tenant nóng: Tràn có kiểm soát sangReplica 5giữ74.17%KV hit,avg TTFT = 91.78 ms(nhanh nhất cả 4 phương pháp) và khóa chặtp99 TTFT = 275.49 ms(8.21xnhanh hơn Unbounded,100.0%SLO).
1.4 Chuyên đề #34: Phân tích Hồ sơ Từ Truy vết Yêu cầu Đến Nhân GPU (Trace-to-Kernel Profiling)#
1. Cơ chế Gốc: Thác Truy vết 6 Tầng Từ Gateway Đến Nhân CUDA#
Để chẩn đoán nguyên nhân sâu xa khi p99 tăng vọt mà nvidia-smi vẫn báo 90%+ (SM utilization illusion), kỹ sư phải ghép nối bốn lớp công cụ theo một thác truy vết xuyên suốt 6 tầng (End-to-End Request-to-Kernel Waterfall):
- Lớp Truy vết Phân tán (
OpenTelemetry+Jaeger): Đoapi_gateway\(\to\)tokenizer\(\to\)scheduler_queue(tuyệt đối ẩn hoặc băm nội dung prompt thô để tránh rò rỉ dữ liệu nhạy cảm). - Lớp CPU Framework (
PyTorch Profilertorch.profiler/py-spy): Đếm số lần gọi toán tửATen, chi phí giữ khóaPython GILvà thời gian dựng metadata batch. - Lớp Dòng Thời gian Hệ thống (
NVIDIA Nsight Systemsnsys): Soi trực quan các khoảng trống (GPU Idle Bubbles) giữa hai nhân CUDA trên stream GPU khi CPU phát lệnh không kịp (cudaLaunchKernel), cùng mức độ chồng lấp với luồng giao tiếpNCCL. - Lớp Vi kiến trúc Nhân (
NVIDIA Nsight Computencu): Đo Roofline mức kernel, tỷ lệ bão hòa Tensor Core vs băng thôngHBM3(3.35 TB/s), và thống kê nguyên nhân dừng warp (Long Scoreboard chờ dữ liệu HBM vs Barrier).
2. Đánh đổi & Thực nghiệm Lab 18 (PyTorch CPU Profiler Thật & 39 OpenTelemetry Spans)#
- Thực nghiệm
PyTorch CPU Profilerthật (run_pytorch_cpu_op_profiling,seed=42): Chạy mạng Transformer4tầng (batch=8, hidden=256), cách chạy tách lẻ từng đầu chú ý (eager_fragmented_ops) phát sinh1,668lệnhATentrong3vòng lặp, trong khi hợp nhất ma trận (fused_batched_ops) chỉ gọi444lệnhATen— giảm3.76xsố lệnh dispatch với sai khác số học tối đa chỉ2.6e-06.
Hồ sơ Truy vết (Lab 18, 39 OTel Spans) |
Tầng Chiếm ưu thế | Bọt khí GPU (Bubble %) |
Tính toán Hữu ích | Chẩn đoán & Hành động Sửa dứt điểm |
|---|---|---|---|---|
cpu_launch_bound |
cuda_launch_cpu (5.18 ms, 46.67%) + scheduler |
63.78% |
14.86% |
Bật Piecewise CUDA Graphs & tách tiến trình scheduler |
hbm_bandwidth_bound |
gpu_hbm_kv_read (11.80 ms, 75.26%) |
8.32% |
9.25% |
Lượng tử hóa FP8/INT4 AWQ, MLA/FP8 KV, tăng batch |
nccl_comm_bound |
nccl_allreduce (16.40 ms, 69.58%) |
6.02% |
9.76% |
Sửa kết nối NVLink P2P, đổi TP8 \(\to\) TP2+DP4 hoặc Wide-EP |
balanced_optimized_step |
gpu_compute_kernel (3.40 ms, 41.26%) |
13.35% |
41.26% |
Trạng thái khỏe mạnh (8.24 ms/step, không có tầng phụ nghẽn) |
3. Các Tình huống Lỗi Thực tế (Failure Modes & Traps)#
- Tin Tưởng Mù Quáng
nvidia-smiUtilization (%):nvidia-smichỉ lấy mẫu xem tại tích tắc lấy mẫu có ít nhất một kernel hay context hoạt động trên GPU hay không — một GPU có63.78%bọt khí trống giữa hàng trăm kernel nhỏ vẫn hiện95%+GPU util! - Quên Chạy
nsysTrướcncu: Chạyncuthu thập bộ đếm phần cứng trên từng kernel kéo chậm hệ thống100x; nếu nút thắt nằm ở tầng CPU (cuda_launch_cpu, Python tokenizer hayGIL),ncusẽ nhìn nhầm chỗ hoàn toàn. - Gắn Prompt Văn bản Thuần Vào
OpenTelemetry Span Attributes: Ghi trực tiếp khóa API,hf_token, hoặc nội dung người dùng lên trace exporter gây rò rỉ dữ liệu nghiêm trọng và phình bộ nhớ vòng đệm (BoundedInMemorySpanExporter).
4. Quy tắc Ra quyết định Sản xuất (#34)#
- Phân loại tự động theo 3 ngưỡng vàng (
classify_waterfall_bottleneck): Nếunccl_comm >= 45%\(\implies\) sửa topo mạng/P2P; nếucpu_launch + scheduler >= 42%\(\implies\) bậtCUDA Graphs& tách tiến trìnhEngineCore; nếuhbm_read >= 48%\(\implies\) lượng tử hóa trọng số/KV và gom lôbatchlớn hơn. - Giữ vòng đệm trace giới hạn & làm sạch thuộc tính (
Bounded + Redacted): Luôn đặtredact_prompt_text: true, giới hạn số span giữ trong bộ nhớ (otel_max_spans <= 512), và không bao giờ lưu thô prompt/token trong span attributes.
1.5 Chuyên đề #35: CUDA Graphs Cho Phục vụ LLM Với Hình dạng Biến thiên (Piecewise CUDA Graphs)#
1. Cơ chế Gốc: Vì sao Cần Tách Mảnh Đồ thị Quanh Attention?#
Ở pha Decode batch nhỏ/vừa, một bước Transformer gọi ~280 kernel nhỏ (RMSNorm, RoPE, QKV, Attention, SiLU, Add). Trên CPU, mỗi lệnh gọi Eager tốn ~18.5 us \(\implies\) tổng cộng 5.18 ms/step chỉ cho chi phí CPU khởi chạy, gấp đôi thời gian GPU thực sự tính toán (~2.17 ms)!
CUDA Graph đóng gói chuỗi kernel thành đồ thị tĩnh chạy bằng một lệnh cudaGraphLaunch duy nhất, nhưng đòi hỏi địa chỉ tensor và kích thước tĩnh. Trong Continuous Batching + Chunked Prefill, cả số token đang chạy \(B_t\) lẫn độ dài ngữ cảnh KV từng yêu cầu \(S_{t,i}\) biến thiên ở mọi bước! Piecewise CUDA Graphs (vLLM V1) cắt đồ thị mô hình ngay tại mỗi phép Attention:
- Các đoạn tuyến tính (
RMSNorm,QKV,RoPE,MLP,All-Reduce): chỉ phụ thuộc duy nhất kích thước batch \(B_t\), nên được chụp trước vào \(K\) đồ thị tĩnh theo xô lô hỗn hợp 1 chiều (Hybrid Buckets:[1, 2, 4, 8, 16, 24, 32, 48, 64, 96, 128]). - Phép
PagedAttention/FlashAttention: chạyEager varlenngay giữa hai mảnhCUDA Graphvới độ dài chuỗi thực \(S_{t,i}\) không cần padding.
2. Đánh đổi & Thực nghiệm Trên 120 Bước Động (Lab 18, Ngân sách Bể Đồ thị <= 3.5 GiB)#
| Chiến lược Thực thi | Số Đồ thị Chụp | CPU Launch / Bước | Lãng phí Pad Batch / Seq | Bể VRAM Đồ thị |
Thời gian Bước & Thông lượng |
|---|---|---|---|---|---|
eager_no_graphs |
0 |
5.18 ms |
0.0% / 0.0% |
0.00 GiB |
7.35 ms (2,698.5 tok/s) |
monolithic_2d_capture (6 B x 4 S) |
24 |
0.06 ms |
26.08% / 26.78% |
8.64 GiB (VƯỢT NGÂN SÁCH!) |
3.06 ms (6,489.4 tok/s, dễ OOM) |
power2_coarse_buckets (Piecewise) |
8 |
0.38 ms |
18.48% / 0.0% |
1.28 GiB |
2.94 ms (6,758.0 tok/s) |
piecewise_hybrid_buckets (vLLM v1) |
11 |
0.38 ms (13.63x ít hơn) |
11.05% (1.67x thấp hơn P2) / 0.0% |
1.76 GiB (An toàn!) |
2.66 ms (7,450.3 tok/s, 2.76x vs Eager) |
3. Các Tình huống Lỗi Thực tế (Failure Modes & Traps)#
- Chụp Đồ thị
Monolithic 2D (Batch x Seq)Gây Tràn VRAM (8.64 GiB OOM): Nhân chéo các xô batch với xô chiều dài chuỗi (24đồ thị) không chỉ ngốn8.64 GiBVRAM dành riêng cho memory pool (đẩy văng hàng chục GBKV-Cache) mà còn lãng phí26.08%tính toán batch +26.78%đọc thừaKVchuỗi. - Dùng Xô Lũy thừa
2Quá Thưa Ở Vùng Batch Phổ biến: Nhảy từ16 -> 32hay32 -> 64khiến batch thực19hay35bị đệm tới18.48%tính toán thừa vô ích; chèn thêm các mốc trung gian[24, 48, 96]chỉ tốn thêm3đồ thị (+0.48 GiB) nhưng cắt1.67xchi phí padding xuống11.05%. - Quên Giải phóng Memory Pool Hoặc Chạy Đồ thị Cho Lô Prefill Khổng lồ (
B > 128): Ở lô rất lớn, GPU đã compute-bound hoàn toàn nên tiết kiệm5 msCPU launch không đáng đổi bằng việc khóa cứng VRAM đồ thị; buộc phải fallback vềEager.
4. Quy tắc Ra quyết định Sản xuất (#35)#
- Dùng
Piecewise CUDA GraphsvớiHybrid Buckets[1,2,4,8,16,24,32,48,64,96,128]: Khóa trần ngân sáchgraph_pool_budget_gib <= 3.5 GiB(1.76 GiBthực tế) để bảo toàn dung lượngKV-Cache, đặteager_varlen_attention: truevàeager_fallback_above_batch: 128. - Kết hợp với tách tiến trình
EngineCore(vLLM V1/SGLang Overlap): Đảm bảo vòng chuẩn bị tensor metadata trên CPU chạy song song với đồ thị đang phát trên GPU stream trước đó.
Trụ cột 2 — Kiến trúc Hệ thống & Cẩm nang Quyết định Sản xuất (Production Playbook)#
Ma trận Quyết định Năm Tầng Triển khai Cụm LLM Quy mô Lớn (2026)#
- Chọn Bố cục Đa GPU (
#32):- Kiểm tra trước tiên nút mạng: tuyệt đối không chạy
TP >= 4quaPCIehoặc Ethernet (TP8 PCIepháTPOTchậm hơn5.03x). - Nếu mô hình đã lọt vào
TP2hoặcTP4ởFP8(70B FP8\(\to\)35 GB/GPUởTP2): dùngTP2 + DP4trênNVLinkđể tối đa hóa thông lượng (1.41x) và hạ$/1M tokens, chỉ dùngTP8khi cầnTPOTsiêu thấp (< 6 ms). - Khi ngữ cảnh dài
>= 128kkhiếnActivationphình lớn hoặcGQA-8không chia hết choTP16: ghépContext Parallelism(CP4 + TP2) thay choPP.
- Kiểm tra trước tiên nút mạng: tuyệt đối không chạy
- Triển khai
Sparse MoE(#31):- Dùng
DPcho Attention +EPcho Experts (DP8+EP8hoặcWide-EP32/64trongSGLang/vLLM/DeepSeekstack) để nhân8x–32xsức chứaKV-Cachevà gộp lô lớn cho từng chuyên gia. - Bắt buộc bật
EPLB(nhân bản chuyên gia nóng dư thừa + đóng góiLPT+ điều phối Power-of-Choice),DeepEP(NVSHMEMRDMA),DeepGEMM(FP8 DeepJIT), và gối đầuDualPipe2 microbatch — hạ độ lệch tải Zipfian thật từ6.09xxuống1.05x–1.09x!
- Dùng
- Cân bằng Tải Đa Bản sao (
#33):- Đặt
Cache-Aware Load-Bounded Router(load_bound_factor = 1.25) trước nhóm8+bản saoSGLang/vLLM— tuyệt đối tránhRound-Robin(mất hitKV) lẫnPrefix-Aware Unbounded(nổ hàng đợi3.77xtrên một bản sao nóng).
- Đặt
- Quy trình Truy vết Nghẽn Chuẩn (
#34):- Dựng thác
OpenTelemetrycó lọc bỏ hoàn toàn prompt thô \(\to\) nếucpu_launch + scheduler > 42%(GPU bubble lớn): kiểm tra số lệnh ATen bằngtorch.profilervà bậtPiecewise CUDA Graphs; nếuhbm_read > 48%: nénFP8/AWQ; nếunccl > 45%: kiểm tra liên kếtNVLink P2P.
- Dựng thác
- Bật
CUDA GraphsAn toàn Cho Tải Động (#35):- Luôn chọn
Piecewise CUDA Graphs+ Xô Lô Hỗn hợp ([1,2,4,8,16,24,32,48,64,96,128]), đặt ngưỡng fallback sangEagerở \(B > 128\) và khóa trần bể VRAM đồ thị<= 3.5 GiB(1.76 GiBthực tế).
- Luôn chọn
Trụ cột 3 — Công nghệ 2026 & Mã nguồn Python/PyTorch/OpenTelemetry Độc lập (100% Khả thi Trong .venv)#
Đoạn mã độc lập dưới đây chạy trực tiếp trong .venv (chỉ dùng numpy, torch và opentelemetry-sdk), kiểm chứng ngay tại chỗ: (1) Độ trễ Hockney All-Reduce (NVLink vs PCIe) + lệch tải Zipfian MoE giảm tự nhiên từ >4x xuống <1.2x nhờ thuật toán EPLB tham lam (argmax load/replicas + đóng gói LPT) & điều phối Power-of-Choice; (2) Bộ định tuyến Cache-Aware Load-Bounded trên 8 bản sao tránh quá tải điểm nóng; và (3) Thực thi PyTorch CPU Profiler thật trên mô hình 4 lớp (Fused giảm >=3x lệnh ATen so với Fragmented) kèm phát hành span OpenTelemetry (InMemorySpanExporter).
from __future__ import annotations
import hashlib
import numpy as np
import torch
import torch.nn.functional as F
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
from torch.profiler import ProfilerActivity, profile
def demo_multigpu_and_moe_skew(seed: int = 42) -> None:
# 1. Hockney All-Reduce (80 layers * 2 per layer = 160 barriers) on TP8 NVLink vs PCIe
payload_bytes = 2.0 * 32 * 8192
ar_nvlink_ms = 160 * (0.0075 + (2 * 7 / 8) * (payload_bytes / 900e9) * 1000.0)
ar_pcie_ms = 160 * (0.115 + (2 * 7 / 8) * (payload_bytes / 24e9) * 1000.0)
assert ar_nvlink_ms < 2.0 and ar_pcie_ms > 20.0
# 2. Zipfian MoE expert load skew (256 experts, 8 GPUs, s=1.15) with genuine EPLB + Po2 dispatch
rng = np.random.default_rng(seed)
ranks = np.arange(1, 257, dtype=np.float64)
probs = ranks ** -1.15
probs /= probs.sum()
ep_degree, step_sz, n_steps, redundant, tile = 8, 2048, 8, 48, 64
raw_step_skews = []
for _ in range(n_steps):
chosen = rng.choice(256, size=step_sz, p=probs)
sl_raw = np.bincount(chosen // 32, minlength=ep_degree).astype(np.float64)
raw_step_skews.append(float(sl_raw.max() / sl_raw.mean()))
raw_skew = float(np.mean(raw_step_skews))
# Genuine Greedy EPLB replica allocation (argmax est_probs / rep_cnt) + LPT packing
tel_cnt = np.bincount(rng.choice(256, size=8192, p=probs), minlength=256).astype(np.float64)
est = (tel_cnt + 0.5) / (tel_cnt.sum() + 0.5 * 256)
rep_cnt = np.ones(256, dtype=np.int64)
for _ in range(redundant):
sc = np.where(rep_cnt < ep_degree, est / rep_cnt, -1.0)
e_hot = int(np.argmax(sc))
if sc[e_hot] <= 0.0:
break
rep_cnt[e_hot] += 1
slots = [(float(est[e] / rep_cnt[e]), e) for e in range(256) for _ in range(int(rep_cnt[e]))]
slots.sort(reverse=True)
slots_per_gpu = (len(slots) + ep_degree - 1) // ep_degree
gpu_exp, gpu_cnt = np.zeros(ep_degree), np.zeros(ep_degree, dtype=np.int64)
expert_replicas: list[list[int]] = [[] for _ in range(256)]
for w, e in slots:
cands = [g for g in range(ep_degree) if g not in expert_replicas[e] and gpu_cnt[g] < slots_per_gpu]
if not cands:
cands = [g for g in range(ep_degree) if g not in expert_replicas[e]]
tgt = min(cands, key=lambda g: (gpu_exp[g], gpu_cnt[g], g))
expert_replicas[e].append(tgt)
gpu_exp[tgt] += w
gpu_cnt[tgt] += 1
# Distributed Power-of-Choice dispatch across DP ranks per decode step
bal_step_skews = []
per_dp = step_sz // ep_degree
for _ in range(n_steps):
chosen = rng.choice(256, size=step_sz, p=probs)
sl_bal = np.zeros(ep_degree, dtype=np.float64)
dl = np.zeros((ep_degree, ep_degree), dtype=np.float64)
pend = np.zeros((ep_degree, ep_degree), dtype=np.float64)
for idx, e_idx in enumerate(chosen):
r_id = min(ep_degree - 1, idx // per_dp)
reps = expert_replicas[int(e_idx)]
if len(reps) == 1:
g = reps[0]
elif len(reps) == 2:
g = reps[0] if dl[r_id, reps[0]] <= dl[r_id, reps[1]] else reps[1]
else:
i1, i2 = rng.choice(len(reps), size=2, replace=False)
g1, g2 = reps[int(i1)], reps[int(i2)]
g = g1 if dl[r_id, g1] <= dl[r_id, g2] else g2
pend[r_id, g] += 1.0
sl_bal[g] += 1.0
if (idx + 1) % tile == 0:
dl += pend
pend.fill(0.0)
bal_step_skews.append(float(sl_bal.max() / sl_bal.mean()))
bal_skew = float(np.mean(bal_step_skews))
assert raw_skew > 4.0 and bal_skew < 1.15
print(f"[1. MultiGPU+MoE] NVLink_AR={ar_nvlink_ms:.2f}ms vs PCIe_AR={ar_pcie_ms:.2f}ms | Zipf_skew={raw_skew:.2f}x -> {bal_skew:.2f}x")
def demo_bounded_prefix_routing() -> None:
loads = [0] * 8
counts_unbounded = [0] * 8
counts_bounded = [0] * 8
primary = int.from_bytes(hashlib.sha256(b"hot_tenant:0").digest()[:4], "big") % 8
ring = [(primary + k * 3) % 8 for k in range(8)]
for i in range(120):
# 50% traffic hits hot_tenant prefix
is_hot = i % 2 == 0
p = primary if is_hot else (i % 8)
counts_unbounded[p] += 1
mean_l = max(1.0, sum(loads) / 8.0)
cap = max(2.0, 1.25 * mean_l)
if is_hot:
chosen = next((c for c in ring if loads[c] <= cap), min(range(8), key=lambda r: loads[r]))
else:
chosen = p if loads[p] <= cap else min(range(8), key=lambda r: loads[r])
counts_bounded[chosen] += 1
loads[chosen] += 1
unb_ratio = max(counts_unbounded) / (sum(counts_unbounded) / 8.0)
bnd_ratio = max(counts_bounded) / (sum(counts_bounded) / 8.0)
assert unb_ratio > 3.5 and bnd_ratio < 1.6
print(f"[2. Cache-Aware Router] Unbounded_max_load={unb_ratio:.2f}x vs Bounded_1.25x={bnd_ratio:.2f}x")
def demo_pytorch_profiler_and_otel(seed: int = 42) -> None:
torch.manual_seed(seed)
x = torch.randn((8, 256))
wq = torch.randn((256, 256)) * 0.04
w1 = torch.randn((256, 512)) * 0.04
w2 = torch.randn((512, 256)) * 0.04
def run_fragmented(inp: torch.Tensor) -> torch.Tensor:
heads = [torch.matmul(inp, wq[:, i * 32 : (i + 1) * 32]) for i in range(8)]
h = inp + torch.cat(heads, dim=-1)
return h + sum(
torch.matmul(F.silu(torch.matmul(h, w1[:, j * 128 : (j + 1) * 128])), w2[j * 128 : (j + 1) * 128, :])
for j in range(4)
)
def run_fused(inp: torch.Tensor) -> torch.Tensor:
h = inp + torch.matmul(inp, wq)
return h + torch.matmul(F.silu(torch.matmul(h, w1)), w2)
with torch.no_grad():
assert float(torch.max(torch.abs(run_fragmented(x) - run_fused(x))).item()) < 1e-4
with profile(activities=[ProfilerActivity.CPU]) as pf1:
_ = run_fragmented(x)
with profile(activities=[ProfilerActivity.CPU]) as pf2:
_ = run_fused(x)
n_frag = sum(e.count for e in pf1.key_averages())
n_fused = sum(e.count for e in pf2.key_averages())
exporter = InMemorySpanExporter()
tp = TracerProvider()
tp.add_span_processor(SimpleSpanProcessor(exporter))
tracer = tp.get_tracer("ch23-pillar3")
with tracer.start_as_current_span("request.e2e"):
with tracer.start_as_current_span("cuda_launch_piecewise"):
pass
spans = exporter.get_finished_spans()
assert n_frag > n_fused * 2.5 and len(spans) == 2
print(f"[3. PyTorch+OTel] ATen_ops: fragmented={n_frag} -> fused={n_fused} | OTel_spans={len(spans)}")
if __name__ == "__main__":
demo_multigpu_and_moe_skew(seed=42)
demo_bounded_prefix_routing()
demo_pytorch_profiler_and_otel(seed=42)
print("Pillar 3 Multi-GPU, MoE, Routing, Profiler & CUDA Graphs PASSED!")
Trụ cột 4 — Thực hành Công nghiệp (Lab 18: multi_gpu_profiling_cudagraph_lab) & Kết quả Thực nghiệm#
4.1 Kiến trúc Hai Tầng Lab 18 (labs/lab-18-trace-to-kernel-profiling-and-cuda-graphs/)#
- Tầng 1 — Cấu hình Sản xuất Sạch (
configs/):configs/moe_wide_ep_vllm_config.yaml: Ghim phiên bảnvllm/vllm-openai:v0.8.5,lmsysorg/sglang:v0.4.6-cu124,nvcr.io/nvidia/ai-dynamo/dynamo-router:0.3.2(0:latest,0bí mật tĩnh,bind_host: 127.0.0.1), cấu hìnhTP2+DP4cho 70B FP8 vàWide-EP32(dp_size: 32, ep_size: 32,redundant_hot_experts: 64,pipelined_two_microbatch_overlap: true).configs/cuda_graph_and_router_config.yaml: Chính sách định tuyếncache_aware_load_bounded(load_bound_factor: 1.25,replica_kv_capacity_blocks: 192),piecewise_hybrid_buckets([1,2,4,8,16,24,32,48,64,96,128],graph_pool_budget_gib: 3.5), và bậtredact_prompt_text: true.
- Tầng 2 — Gói Python
multi_gpu_profiling_cudagraph_lab(src/multi_gpu_profiling_cudagraph_lab/):multi_gpu_moe_and_routing.py: Triển khai mô hình Hockney (chuẩn hóa \(L/\text{PP}\) cho cả prefill và decode) + phân tíchTP/PP/DP/CP(#32), bộ mô phỏngSparse MoEvới phân phối Zipfian +EPLBtham lam (argmax load/replicas+ đóng góiLPT) + điều phối Power-of-Choice (#31), và bộ mô phỏng cụm8bản sao giữOrderedDictLRU cache thực tế cho 4 chiến lược định tuyến (#33).trace_profiling_and_cudagraphs.py: Thực thitorch.profiler.profiletrênPyTorch CPU, phát hành39spanOpenTelemetryphân cấp có bảo vệ chống rò rỉ (BoundedInMemorySpanExporter) và phân loại4chế độ nghẽn (#34), mô phỏng120bướcCUDA Graphs&Piecewise Hybrid Buckets(#35), cùng bộ kiểm toán tĩnhaudit_lab18_configs.
4.2 Tóm tắt Kết quả Đo đạc Thực nghiệm (artifacts/t2_ch23_lab18_results.json, seed=42)#
Thực nghiệm (multi_gpu_profiling_cudagraph_lab) |
Thông số Đo được (Xác định seed=42) |
Bất biến Kỹ thuật Được Chứng minh |
|---|---|---|
Exp 1 (#32): Bố cục 8x H100 (70B FP8) |
TP2+DP4: 7,790.5 tok/s ($0.8557/1M, 1.41x vs TP8 NVLink 5,544.0); TP4_PP2: 8.28 ms TPOT (3,629.8 tok/s); TP8 PCIe: 28.91 ms TPOT (5.03x chậm, FAIL); PP8: 30.43% bubble (FAIL); CP4+TP2 128k: 1.44x ít RAM |
Không chạy TP qua PCIe; chọn TP2+DP4 khi mô hình lọt VRAM để tối ưu giá/Goodput |
Exp 2 (#31): MoE TP8 vs EP8 vs Wide-EP32 |
TP8: 725.5 tok/s/GPU (1x KV); DP8+EP8 lệch: 6.09x straggler (734.8); EPLB + Po2: 1.05x (5.80x cân bằng, 1,916.3); Wide-EP32: 2,246.8 /GPU (3.10x), 71,898.3 cụm (1.09x skew, 32x KV) |
DP+EP mở khóa sức chứa KV; EPLB tham lam + Power-of-Choice triệt tiêu nút thắt All-to-All |
Exp 3 (#33): Định tuyến 8 Bản sao (240 Req) |
RR: 50.83% hit, 831.83 ms p99; Unbounded: 97.5% hit, 2,261.66 ms p99 (3.77x load, 58.33% SLO); Load-Bounded: 74.17% hit, 275.49 ms p99 (8.21x), 1.41x load, 100% SLO |
Băm nhất quán có giới hạn tải 1.25x vừa giữ cache hit vừa chống sập điểm nóng |
Exp 4 (#34): PyTorch CPU Profiler & OTel |
1,668 -> 444 ATen ops (3.76x ít hơn, diff 2.6e-06); Thác OTel tách cpu_launch_bound (63.78% bubble) vs hbm (75.26%) vs nccl (69.58%) vs balanced (13.35%) |
Đo thực tế từ API đến nhân CUDA chỉ ra chính xác điểm gãy trước khi tối ưu |
Exp 5 (#35): CUDA Graphs & Piecewise Buckets |
Eager: 5.18 ms launch (2,698.5 tok/s); Monolithic 2D: 8.64 GiB OOM; P2: 18.48% pad; Piecewise Hybrid: 0.38 ms (13.63x), 11.05% pad (1.67x), 0% seq pad, 1.76 GiB, 7,450.3 tok/s (2.76x) |
Piecewise CUDA Graphs chạy varlen Attention ngoài đồ thị giữ nguyên 0% đệm KV |
Kiểm toán YAML & Bounded OTel |
2/2 YAML sạch (0 secrets, 0 :latest, 3 image ghim, 127.0.0.1); 39 OTel spans sạch (clean_attributes=True) |
Bảo đảm chuỗi cung ứng cấu hình đa GPU & quan sát hệ thống không lộ prompt |
4.3 Quy trình Kiểm định Tự động (28/28 Test Cases Pass, 0 Skipped, 0 # type: ignore)#
cd 03-track-2-data-and-ai-engineering/part-04-ml-and-llm-serving-systems/labs/lab-18-trace-to-kernel-profiling-and-cuda-graphs
PYTHONPATH=src python scripts/run_lab_demo.py --seed 42 --output artifacts/t2_ch23_lab18_results.json
ruff check src scripts tests
mypy 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 2017–2026#
- Shoeybi et al. (NVIDIA, 2019–2020) & Narayanan et al. (SC 2021). Megatron-LM: Training Multi-Billion Parameter Language Models Using Model Parallelism. — Nền tảng chia cột/hàng
Tensor ParallelismvàPipeline Parallelismkèm mô hình hóa bong bóng đường ống. - Liu et al. (ICLR 2024). Ring Attention with Blockwise Transformers for Near-Infinite Context. — Cơ sở thuật toán
Context Parallelismgối đầu truyềnKVvòng tròn cho chuỗi128k–1Mtoken. - DeepSeek-AI (2024–2026). DeepSeek-V3 Technical Report & Open-Source Infra (
Wide-EP,DeepEP,DeepGEMM,DualPipe,EPLB). — Bản thiết kế chuẩn công nghiệp cho phục vụMoEbằngDP+EP, giao tiếpNVSHMEMbất đồng bộDeepEP, nhânFP8 DeepJITcân chỉnh theo khối hạt mịnDeepGEMM, gối đầu hai chiềuDualPipeẩn chi phíAll-to-All, và nhân bản chuyên gia nóngEPLB. - Mirrokni, Thorup & Zadimoghaddam (ACM TALG / Google, 2018) & SGLang Team (2025–2026). Consistent Hashing with Bounded Loads & SGLang Router: Cache-Aware Load-Balanced Prefix Routing. — Nền tảng toán học cho định tuyến nhận thức
KV-Cachequa nhiều bản sao mà không tạo nút nóng sập đuôip99. - Kwon et al. / vLLM Team (2025–2026). vLLM v1 Architecture: Zero-Overhead Core Loop & Piecewise CUDA Graphs. — Tách vòng lặp lập lịch khỏi HTTP/Tokenizer và cắt mảnh
CUDA Graphquanh các nhânPagedAttentionkích thước biến thiên. - NVIDIA Corporation (2024–2026). NVIDIA Nsight Systems, Nsight Compute Roofline Guide & CUDA Graphs Programming Guide. — Quy chuẩn phân tích khoảng trống CPU launch bubble và tắc nghẽn HBM/Tensor Core ở cấp độ warp.
- OpenTelemetry GenAI Semantic Conventions & PyTorch Kineto Profiler (2024–2026). — Chuẩn hóa truy vết phân tán từ yêu cầu API đến phân tích đồ thị ATen và kiểm soát ẩn dữ liệu nhạy cảm.
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%) — Phân tích Bố cục Đa GPUTP/PP/DP/CP& BẫyPCIe(#32): Dựa trên phương trình Hockney và mô phỏngevaluate_multi_gpu_layouts, giải thích tại saoTP8trênPCIe Gen5(64 GB/s) tăngTPOTlên28.91 ms(84.81%thời gian giao tiếp, vỡ SLO), vì saoPP8chịu30.43%bong bóng, và vì saoTP2+DP4trênNVLinkđạt7,790.5 tok/svới chi phí$0.8557/1M(Tests 02–05).Thang điểm: Tính đúng chi phí
All-ReduceHockney (5%), phân tích chính xácTP2+DP4vsPP8&CP4+TP2(5%), passTests 02–05(5%). -
Bài tập 2 (
ex2, 15%) — Phục vụMoEWide-EP& Chống Lệch Tải Zipfian (#31): Giải thích hai lý do khiếnTP8_DenseStyleđạt hiệu năng thấp trênSparse MoE(m_e = 4.0, nhân bản8x KV), lần theo sự bùng phát straggler từ1.09x -> 6.09x -> 7.28xtrongsweep_moe_zipf_skew, và trình bày cơ chếEPLBtham lam (48khe chuyên gia nóng + đóng góiLPT+ Power-of-Choice),DeepEP/DeepGEMM/DualPipecùngWide-EP32đạt2,246.8 tok/s/GPU(Tests 06–07, 28).Thang điểm: Chứng minh lợi thế
DP+EPvề dung lượngKVvàGEMM(5%), giải thích đúngEPLB& gối đầuAll-to-All(5%), passTests 06–07(5%). -
Bài tập 3 (
ex3, 15%) — Định tuyến Nhận thứcKV-CacheCó Giới hạn Tải (#33): Phân tích chuỗi nhân quả trên240yêu cầu qua8bản sao: vì saoPrefix-Aware Unboundedđạt97.5%cache hit nhưng làm sụpSLO Attainmentxuống58.33%(p99 TTFT = 2,261.66 ms), và cáchCache-Aware Load-Bounded(load_bound_factor = 1.25) giữ74.17%hit đồng thời đạt100.0%SLO ở275.49 ms(Tests 08–09).Thang điểm: Phân tích đúng hội chứng điểm nóng
3.77x(5%), thiết kế đúng quy tắc tràn giới hạn tải (5%), passTests 08–09(5%). -
Bài tập 4 (
ex4, 15%) — Phân tích Hồ sơPyTorch CPU Profiler& ThácOpenTelemetry(#34): Kiểm tra hàmrun_pytorch_cpu_op_profilingvàclassify_waterfall_bottleneck: giải thích vì sao hợp nhất tác vụ cắt giảm3.76xsố lệnh ATen (1,668 -> 444) với sai khác2.6e-06, và phân biệt dấu hiệu nhận diện4chế độ nghẽn trên thácOTel(Tests 10–12).Thang điểm: Giải thích chính xác
torch.profilerATen dispatch (5%), phân biệt đủ4chế độ nghẽn & giải pháp (5%), passTests 10–12(5%). -
Bài tập 5 (
ex5, 20%) —Piecewise CUDA Graphs& Đánh đổi Xô Lô (#35): Đối chiếu4chiến lược trongsimulate_cuda_graph_bucketing: lý doEagertốn5.18 ms/steplaunch overhead, vì saoMonolithic 2D Capturenổ8.64 GiBVRAM vượt trần3.5 GiB, và cáchPiecewise Hybrid Bucketsxóa0.0%padding chuỗi, cắt13.63xlaunch overhead (0.38 ms) và đạt7,450.3 tok/s(Tests 13–14).Thang điểm: Phân tích đúng cơ chế tách mảnh quanh
varlen Attention(7%), định lượng đúng đánh đổi VRAM vs padding (7%), passTests 13–14(6%). -
Bài tập 6 (
ex6, 20%) — Kiểm toán Cấu hìnhYAML, Truy vếtBounded OTel& Tính Xác định (seed=42): Giải thích các bất biến kiểm toán trongaudit_lab18_configs(0bí mật tĩnh,0:latest, bind127.0.0.1, bậtWide-EP + EPLB,cache_aware_load_bounded,piecewise_hybrid_buckets,redact_prompt_text), kiểm chứng39OTel spans sạch và vượt quaruff,mypy strict,28pytest,uv lock --check(Tests 01, 15–28).Thang điểm: Nêu đúng quy tắc kiểm toán YAML & thử nghiệm giả mạo (
7%), xác minh39spanOTel& tính xác định (7%), passTests 01, 15–28(6%).
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— Bố cục Đa GPUTP2+DP4vs.TP8 PCIe&PP8,#32): Trên cụm8x H100phục vụ70B FP8(Lab 18,Tests 02–03), vì saoTP8trênPCIe(64 GB/s) vàPP8trênNVLinkđều vỡTPOT SLO 25 mstrong khiTP2+DP4thắng áp đảo về thông lượng và chi phí? - (
q2—Context ParallelismCho Ngữ cảnh128k,#32): So vớiTP8đơn thuần, cơ chếCP4 + TP2 Ring Attentiongiải quyết nút thắt nào khi tiền điền chuỗi131,072token (Test 04)? - (
q3—Sparse MoE:TP8vs.DP8+EP8vs.Wide-EP32,#31): Trên mô hìnhMoE256chuyên giaTop-K=8(Test 06), tại sao kiến trúcDP+EP(Wide-EP32) đạt2,246.8 tok/s/GPU(3.10xso vớiTP8_DenseStyle) và32xsức chứaKV-Cache? - (
q4— Lệch Tải Zipfian & Nhân bản Chuyên gia NóngEPLB,#31): Khi độ lệch Zipfian tăng lêns = 1.15(Tests 06–07, 28), điều gì gây nghẽnAll-to-AllởDP8+EP8thuần và việc thêm48khe chuyên gia nóng dư thừa (EPLBtham lam + đóng góiLPT+ điều phối Power-of-Choice) cải thiện ra sao? - (
q5— Định tuyến CụmPrefix-Aware Unboundedvs.Load-Bounded,#33): Trên240yêu cầu lệch Zipfian qua8bản sao (Test 08), tại saoPrefix-Aware Unboundedđạt97.5%hit rate nhưng vẫn sụp đổ xuống58.33%SLO, cònCache-Aware Load-Bounded(1.25x) lại đạt100.0%SLO? - (
q6— Thác Truy vếtOTel -> PyTorch Profiler -> Nsight,#34): Khinvidia-smibáo GPU bận nhưng hiệu năng thực thấp, tổ hợpPyTorch CPU Profiler+ thácOpenTelemetry(Tests 10–11) phân biệtcpu_launch_boundvớihbm_bandwidth_boundvànccl_comm_bounddựa trên chỉ số nào? - (
q7—Eagervs.Monolithic 2D Capturevs.Piecewise CUDA Graphs,#35): Vì sao chụpCUDA Graphnguyên khối 2D(B, S)lại thất bại ở hình dạng biến thiên vàPiecewise CUDA Graphs(vLLM v1) giải quyết triệt để vấn đề này như thế nào (Test 13)? - (
q8— Xô Lô Hỗn hợpHybrid Buckets& Kiểm toán Cấu hình Đa GPU,#35): TrongLab 18(Tests 13, 15–22), lợi ích định lượng của việc dùng xô lô hỗn hợp[1,2,4,8,16,24,32,48,64,96,128]thay cho xô lũy thừa2cùng cơ chế bảo mật truy vếtOTellà gì?
8x H100 70B FP8 Cluster Throughput (tokens/s)
Sparse MoE Decode Per-GPU Throughput (tokens/s/GPU)
8-Replica Cluster p99 TTFT (ms) Under Hot-Prefix Skew
Dynamic Batch Decode Step Latency (ms): Eager vs Piecewise CUDA Graphs
Exp 1 (#32): 8x H100 Multi-GPU Parallelism Layouts (70B FP8)
| layout | ttft_and_tpot | comm_and_bubble | throughput_and_cost |
|---|---|---|---|
| TP8_NVLink | 44.52 ms | 5.75 ms (SLO=True) | comm=23.69% | bubble=0.0% | 5544.0 tok/s ($1.2025/1M) |
| TP8_PCIe_Mismatch | 442.75 ms | 28.91 ms (SLO=False) | comm=84.81% | bubble=0.0% | 1106.3 tok/s ($6.0262/1M) |
| PP8_NVLink | 38.0 ms | 27.92 ms (SLO=False) | comm=66.46% | bubble=30.43% | 796.8 tok/s ($8.3664/1M) |
| TP4_PP2_NVLink | 39.04 ms | 8.28 ms (SLO=True) | comm=40.11% | bubble=5.88% | 3629.8 tok/s ($1.8367/1M) |
| TP2_DP4_NVLink_FP8 | 137.84 ms | 16.36 ms (SLO=True) | comm=2.72% | bubble=0.0% | 7790.5 tok/s ($0.8557/1M) |
Exp 2 (#31): Sparse MoE Serving Across TP8, DP8+EP8 & Wide-EP32
| strategy | skew_and_comm | kv_cap_and_m_e | per_gpu_and_cluster_tok_s |
|---|---|---|---|
| TP8_DenseStyle | skew=1.0x | comm=0.65 ms | 1.0x KV | m_e=4.0 | 725.5 /GPU (5803.7 total) |
| DP8_EP8_Skewed | skew=6.09x | comm=2.08 ms | 8.0x KV | m_e=8.0 | 734.8 /GPU (5878.3 total) |
| DP8_EP8_RedundantHotExperts | skew=1.05x | comm=2.08 ms | 8.0x KV | m_e=8.0 | 1916.3 /GPU (15330.2 total) |
| WideEP32_Pipelined | skew=1.09x | comm=1.04 ms | 32.0x KV | m_e=32.0 | 2246.8 /GPU (71898.3 total) |
Exp 3 (#33): 8-Replica Cluster Routing Under Zipfian Prefix Skew
| routing_policy | kv_hit_rate | p99_ttft_and_load | slo_and_goodput |
|---|---|---|---|
| round_robin | 50.83% | 831.83 ms | load=1.28x | 92.08% (47.5 req/s) |
| least_loaded | 50.0% | 335.53 ms | load=1.03x | 100.0% (58.82 req/s) |
| prefix_aware_unbounded | 97.5% | 2261.66 ms | load=3.77x | 58.33% (22.44 req/s) |
| cache_aware_load_bounded | 74.17% | 275.49 ms | load=1.41x | 100.0% (58.25 req/s) |
Exp 5 (#35): CUDA Graph Capture & Piecewise Bucketing Trade-offs
| capture_mode | launch_and_pad_waste | graph_vram | step_ms_and_tok_s |
|---|---|---|---|
| eager_no_graphs | 5.18 ms | batch_pad=0.0% | seq_pad=0.0% | 0.0 GiB (ok=True) | 7.35 ms | 2698.5 tok/s |
| monolithic_2d_capture | 0.06 ms | batch_pad=26.08% | seq_pad=26.78% | 8.64 GiB (ok=False) | 3.06 ms | 6489.4 tok/s |
| power2_coarse_buckets | 0.38 ms | batch_pad=18.48% | seq_pad=0.0% | 1.28 GiB (ok=True) | 2.94 ms | 6758.0 tok/s |
| piecewise_hybrid_buckets | 0.38 ms | batch_pad=11.05% | seq_pad=0.0% | 1.76 GiB (ok=True) | 2.66 ms | 7450.3 tok/s |
03-track-2-data-and-ai-engineering/part-04-ml-and-llm-serving-systems/labs/lab-18-trace-to-kernel-profiling-and-cuda-graphs
[build-system]
requires = ["setuptools>=68.0"]
build-backend = "setuptools.build_meta"
[project]
name = "multi-gpu-profiling-cudagraph-lab"
version = "0.1.0"
description = "FSDS-SOTA-2026 Track 2 Lab 18: Multi-GPU TP/PP/DP/CP Layouts, MoE Wide-EP & Skew Mitigation, Cache-Aware Prefix Routing, Request-to-Kernel OTel/PyTorch Profiling & Piecewise CUDA Graphs"
readme = "README.md"
requires-python = ">=3.12"
dependencies = [
"numpy>=1.26",
"opentelemetry-sdk>=1.28",
"pydantic>=2.0",
"pyyaml>=6.0",
"torch>=2.5",
]
[project.optional-dependencies]
dev = [
"hypothesis>=6.100",
"mypy>=1.11",
"pytest>=8.0",
"ruff>=0.6",
]
[project.scripts]
fsds-multigpu-prof-lab = "multi_gpu_profiling_cudagraph_lab.trace_profiling_and_cudagraphs:main"
[[tool.uv.index]]
name = "pytorch-cpu"
url = "https://download.pytorch.org/whl/cpu"
explicit = true
[tool.uv.sources]
torch = { index = "pytorch-cpu" }
[tool.setuptools]
package-dir = {"" = "src"}
[tool.setuptools.packages.find]
where = ["src"]
[tool.pytest.ini_options]
testpaths = ["tests"]
pythonpath = ["src", "."]
addopts = "-v"
[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 = [
"yaml",
]
ignore_missing_imports = true
# Production Multi-GPU & MoE Wide-EP Serving Specification (Pinned Images, Zero Plaintext Secrets)
apiVersion: serving.fsds-sota.io/v1alpha1
kind: DistributedMoEServingSpec
metadata:
name: deepseek-v3-wide-ep-prod
namespace: ai-serving
spec:
model_id: deepseek-ai/DeepSeek-V3-0324
architecture:
num_layers: 61
routed_experts: 256
active_experts_top_k: 8
shared_experts: 1
attention_type: mla
weight_dtype: fp8_e4m3
runtime_images:
vllm_image: vllm/vllm-openai:v0.8.5
sglang_image: lmsysorg/sglang:v0.4.6-cu124
dynamo_router_image: nvcr.io/nvidia/ai-dynamo/dynamo-router:0.3.2
auth:
hf_token_secret_ref:
name: vault-hf-credentials
key: read_token
network:
bind_host: 127.0.0.1
http_port: 8000
intra_node_fabric: nvlink5_900gbps
inter_node_fabric: infiniband_ndr_400gbps
nccl_p2p_level: NVL
parallelism:
dense_70b_baseline:
tp_size: 2
pp_size: 1
dp_size: 4
cp_size: 1
moe_prefill_pool:
tp_size: 8
pp_size: 1
dp_size: 1
ep_size: 8
moe_decode_wide_ep:
dp_size: 32
ep_size: 32
tp_size: 1
redundant_hot_experts: 64
eplb_rebalance_interval_steps: 200
pipelined_two_microbatch_overlap: true
slo_targets:
ttft_p99_ms: 500.0
tpot_p99_ms: 25.0
goodput_min_attainment_pct: 95.0
# Production Cache-Aware Load-Bounded Router, Piecewise CUDA Graph & Trace Profiling Spec
apiVersion: serving.fsds-sota.io/v1alpha1
kind: PrefixRouterAndCudaGraphPolicy
metadata:
name: sglang-vllm-router-cudagraph-prod
namespace: ai-serving
spec:
router:
policy: cache_aware_load_bounded
num_replicas: 8
consistent_hash_virtual_nodes: 150
load_bound_factor: 1.25
max_queue_depth_per_replica: 24
radix_prefix_block_size: 16
replica_kv_capacity_blocks: 192
bind_host: 127.0.0.1
port: 8081
cuda_graphs:
mode: piecewise_hybrid_buckets
capture_batch_buckets: [1, 2, 4, 8, 16, 24, 32, 48, 64, 96, 128]
eager_varlen_attention: true
max_capture_seq_len: 8192
graph_pool_budget_gib: 3.5
eager_fallback_above_batch: 128
profiling:
otel_exporter: in_memory_bounded
otel_max_spans: 512
pytorch_profiler_cpu_ops: true
nsys_nvtx_ranges: true
redact_prompt_text: true
slo_ttft_p99_ms: 550.0
"""FSDS-SOTA-2026 Track 2 Lab 18: Multi-GPU MoE, Cache-Aware Routing, Profiling & CUDA Graphs."""
from __future__ import annotations
from multi_gpu_profiling_cudagraph_lab.multi_gpu_moe_and_routing import (
evaluate_context_parallel_long_prefill,
evaluate_multi_gpu_layouts,
simulate_cache_aware_routing,
simulate_moe_ep_serving,
sweep_moe_zipf_skew,
)
from multi_gpu_profiling_cudagraph_lab.trace_profiling_and_cudagraphs import (
BoundedInMemorySpanExporter,
audit_lab18_configs,
classify_waterfall_bottleneck,
create_in_memory_telemetry,
main,
run_pytorch_cpu_op_profiling,
run_request_to_kernel_profiling,
simulate_cuda_graph_bucketing,
summarize_finished_spans,
)
__all__ = [
"BoundedInMemorySpanExporter",
"audit_lab18_configs",
"classify_waterfall_bottleneck",
"create_in_memory_telemetry",
"evaluate_context_parallel_long_prefill",
"evaluate_multi_gpu_layouts",
"main",
"run_pytorch_cpu_op_profiling",
"run_request_to_kernel_profiling",
"simulate_cache_aware_routing",
"simulate_cuda_graph_bucketing",
"simulate_moe_ep_serving",
"summarize_finished_spans",
"sweep_moe_zipf_skew",
]
"""Exp 1-3 (#32, #31, #33): Multi-GPU Parallelism Layouts, MoE Wide-EP & Cache-Aware Routing."""
from __future__ import annotations
import hashlib
from collections import OrderedDict
from dataclasses import dataclass
from typing import Any
import numpy as np
from pydantic import BaseModel, ConfigDict, Field
class MultiGpuLayoutMetrics(BaseModel):
"""Evaluated serving performance and cost metrics for a Multi-GPU topology."""
model_config = ConfigDict(frozen=True)
layout_name: str
tp: int = Field(ge=1)
pp: int = Field(ge=1)
dp: int = Field(ge=1)
cp: int = Field(ge=1)
fabric_name: str
link_bandwidth_gbps: float = Field(gt=0.0)
num_replicas: int = Field(ge=1)
weights_gb_per_gpu: float = Field(gt=0.0)
kv_headroom_gb_per_gpu: float = Field(ge=0.0)
ttft_ms: float = Field(gt=0.0)
tpot_ms: float = Field(gt=0.0)
comm_overhead_pct: float = Field(ge=0.0)
pp_bubble_pct: float = Field(ge=0.0)
cluster_tokens_per_sec: float = Field(gt=0.0)
goodput_req_s: float = Field(ge=0.0)
cost_per_1m_tokens_usd: float = Field(gt=0.0)
slo_met: bool
class MoEServingMetrics(BaseModel):
"""Evaluated MoE serving performance across TP vs DP+EP vs Wide-EP topologies."""
model_config = ConfigDict(frozen=True)
strategy_name: str
num_gpus: int = Field(ge=1)
dp_degree: int = Field(ge=1)
ep_degree: int = Field(ge=1)
tp_degree: int = Field(ge=1)
redundant_hot_experts: int = Field(ge=0)
global_decode_batch: int = Field(ge=1)
avg_tokens_per_expert_invocation: float = Field(gt=0.0)
skew_straggler_ratio: float = Field(ge=1.0)
all_to_all_comm_ms: float = Field(ge=0.0)
step_latency_ms: float = Field(gt=0.0)
kv_capacity_multiplier_vs_tp8: float = Field(gt=0.0)
cluster_decode_tokens_per_sec: float = Field(gt=0.0)
per_gpu_tokens_per_sec: float = Field(gt=0.0)
@dataclass(frozen=True, slots=True)
class ClusterRequest:
"""Single incoming inference request for the 8-replica cluster routing simulation."""
req_id: int
arrival_ms: float
prefix_id: str
prefix_tokens: int
unique_tokens: int
output_tokens: int
class _ReplicaState:
"""Mutable per-replica worker state with bounded LRU KV prefix cache."""
def __init__(self, replica_id: int, capacity_blocks: int, block_size: int = 16) -> None:
self.replica_id = replica_id
self.capacity_blocks = capacity_blocks
self.block_size = block_size
self.cache: OrderedDict[tuple[str, int], int] = OrderedDict()
self.worker_free_at_ms: float = 0.0
self.request_count: int = 0
self.compute_busy_ms: float = 0.0
self.pending_end_times: list[float] = []
def inflight_count(self, now_ms: float) -> int:
self.pending_end_times = [t for t in self.pending_end_times if t > now_ms]
return len(self.pending_end_times)
def access_prefix(self, prefix_id: str, prefix_tokens: int) -> tuple[int, int]:
num_blocks = prefix_tokens // self.block_size
hits = 0
misses = 0
for blk_idx in range(num_blocks):
key = (prefix_id, blk_idx)
if key in self.cache:
self.cache.move_to_end(key)
hits += 1
else:
misses += 1
if len(self.cache) >= self.capacity_blocks:
self.cache.popitem(last=False)
self.cache[key] = 1
return hits * self.block_size, misses * self.block_size
# ---------------------------------------------------------------------------
# Experiment 1 (#32): Multi-GPU Parallelism Layout (TP / PP / DP / CP)
# ---------------------------------------------------------------------------
def _hockney_allreduce_ms(tp: int, payload_bytes: float, bw_gbps: float, alpha_us: float) -> float:
if tp <= 1:
return 0.0
bw_bytes_per_s = bw_gbps * 1e9
transfer_s = (2.0 * (tp - 1) / tp) * (payload_bytes / bw_bytes_per_s)
return (alpha_us * 1e-3) + transfer_s * 1000.0
def evaluate_multi_gpu_layouts(
batch_per_replica: int = 32,
prompt_tokens: int = 2048,
output_tokens: int = 256,
ttft_slo_ms: float = 500.0,
tpot_slo_ms: float = 25.0,
) -> dict[str, Any]:
"""Compare TP, PP, DP layouts for 70B FP8 serving across an 8x H100 cluster (#32)."""
num_cluster_gpus = 8
num_layers = 80
d_model = 8192
weights_total_gb = 70.0
hbm_capacity_gb = 80.0
activation_reserve_gb = 8.0
kv_bytes_per_tok_fp8 = 163_840.0 # 2 * 80 * 8 * 128 * 1 byte
flops_per_tok = 140e9
eff_tflops = 1090e12 # H100 FP8 at ~55% MFU
eff_hbm_bw = 2.65e12 # H100 HBM3 effective 2.65 TB/s
gpu_hourly_usd = 3.0
# (name, tp, pp, dp, cp, fabric_name, link_bw_gbps, eff_bw_gbps, alpha_us, microbatches)
specs: list[tuple[str, int, int, int, int, str, float, float, float, int]] = [
("TP8_NVLink", 8, 1, 1, 1, "NVLink5_900GBps", 900.0, 900.0, 7.5, 1),
("TP8_PCIe_Mismatch", 8, 1, 1, 1, "PCIe_Gen5_64GBps_NoNVLink", 64.0, 24.0, 115.0, 1),
("PP8_NVLink", 1, 8, 1, 1, "NVLink5_900GBps", 900.0, 900.0, 7.5, 16),
("TP4_PP2_NVLink", 4, 2, 1, 1, "NVLink5_900GBps", 900.0, 900.0, 7.5, 16),
("TP2_DP4_NVLink_FP8", 2, 1, 4, 1, "NVLink5_900GBps", 900.0, 900.0, 2.2, 1),
]
layouts: list[MultiGpuLayoutMetrics] = []
for name, tp, pp, dp, cp, fabric, bw_gbps, eff_bw_gbps, alpha_us, m_batches in specs:
assert tp * pp * dp * cp == num_cluster_gpus
model_gpus = tp * pp
weights_per_gpu = weights_total_gb / model_gpus
kv_headroom = max(0.0, hbm_capacity_gb - weights_per_gpu - activation_reserve_gb)
# Prefill (compute-bound scaled by model_gpus)
prefill_flops_per_gpu = (prompt_tokens * flops_per_tok) / model_gpus
prefill_compute_ms = (prefill_flops_per_gpu / eff_tflops) * 1000.0
prefill_ar_payload = 2.0 * prompt_tokens * d_model
prefill_ar_ms = (
2.0
* (num_layers / pp)
* _hockney_allreduce_ms(tp, prefill_ar_payload, eff_bw_gbps, alpha_us)
)
p2p_prefill_ms = (
(pp - 1) * (2.0 * prompt_tokens * d_model / (eff_bw_gbps * 1e9) * 1000.0 + 0.04)
if pp > 1
else 0.0
)
pp_bubble_frac = (pp - 1) / (m_batches + pp - 1) if pp > 1 else 0.0
ttft_ms = (prefill_compute_ms + prefill_ar_ms + p2p_prefill_ms) * (1.0 + pp_bubble_frac * 0.45)
# Decode step for batch_per_replica
b_rep = batch_per_replica
kv_read_bytes = b_rep * (prompt_tokens + output_tokens * 0.5) * kv_bytes_per_tok_fp8
weight_read_bytes = weights_total_gb * 1e9
decode_bytes_per_gpu = (weight_read_bytes + kv_read_bytes) / model_gpus
decode_mem_ms = (decode_bytes_per_gpu / eff_hbm_bw) * 1000.0
decode_comp_ms = ((b_rep * flops_per_tok / model_gpus) / eff_tflops) * 1000.0
kernel_launch_ms = 0.55 / pp if pp == 1 else 0.85
# TP does 2 All-Reduces per layer on each stage (num_layers / pp layers per GPU stage);
# PP adds sequential stage handoff latency across the pp pipeline boundary.
decode_ar_payload = 2.0 * b_rep * d_model
decode_ar_ms = (
2.0
* (num_layers / pp)
* _hockney_allreduce_ms(tp, decode_ar_payload, eff_bw_gbps, alpha_us)
)
# In PP8, a single microbatch still traverses pp stages with stage launch + P2P sync overhead
pp_stage_handoff_ms = (pp - 1) * (2.65 + (2.0 * b_rep * d_model / (eff_bw_gbps * 1e9) * 1000.0))
base_compute_ms = max(decode_mem_ms, decode_comp_ms) + kernel_launch_ms
# PP bubble reduces effective utilization across microbatches
raw_tpot_ms = base_compute_ms + decode_ar_ms + pp_stage_handoff_ms
tpot_ms = raw_tpot_ms / max(0.25, 1.0 - pp_bubble_frac * 0.55) if pp > 1 else raw_tpot_ms
comm_ms = decode_ar_ms + pp_stage_handoff_ms
comm_pct = min(99.0, 100.0 * comm_ms / tpot_ms)
pp_bubble_pct = 100.0 * pp_bubble_frac
# Cluster throughput across dp replicas (accounting for prefill+decode mix)
rep_decode_tok_s = (b_rep * 1000.0) / tpot_ms
prefill_share = prefill_compute_ms / max(1.0, prefill_compute_ms + output_tokens * tpot_ms)
cluster_tok_s = dp * rep_decode_tok_s * (1.0 - 0.15 * prefill_share) * (1.0 - pp_bubble_frac)
slo_met = (ttft_ms <= ttft_slo_ms) and (tpot_ms <= tpot_slo_ms)
goodput_req_s = (
(cluster_tok_s / output_tokens) if slo_met else (cluster_tok_s / output_tokens) * 0.10
)
cluster_usd_per_sec = (num_cluster_gpus * gpu_hourly_usd) / 3600.0
cost_per_1m = (cluster_usd_per_sec / cluster_tok_s) * 1e6
layouts.append(
MultiGpuLayoutMetrics(
layout_name=name,
tp=tp,
pp=pp,
dp=dp,
cp=cp,
fabric_name=fabric,
link_bandwidth_gbps=bw_gbps,
num_replicas=dp,
weights_gb_per_gpu=round(weights_per_gpu, 2),
kv_headroom_gb_per_gpu=round(kv_headroom, 2),
ttft_ms=round(ttft_ms, 2),
tpot_ms=round(tpot_ms, 2),
comm_overhead_pct=round(comm_pct, 2),
pp_bubble_pct=round(pp_bubble_pct, 2),
cluster_tokens_per_sec=round(cluster_tok_s, 1),
goodput_req_s=round(goodput_req_s, 2),
cost_per_1m_tokens_usd=round(cost_per_1m, 4),
slo_met=slo_met,
)
)
by_name = {item.layout_name: item for item in layouts}
tp2_dp4 = by_name["TP2_DP4_NVLink_FP8"]
tp8_nv = by_name["TP8_NVLink"]
tp8_pcie = by_name["TP8_PCIe_Mismatch"]
return {
"cluster_gpus": num_cluster_gpus,
"slo_targets": {"ttft_ms": ttft_slo_ms, "tpot_ms": tpot_slo_ms},
"layouts": [item.model_dump() for item in layouts],
"tp2_dp4_throughput_gain_vs_tp8_x": round(
tp2_dp4.cluster_tokens_per_sec / tp8_nv.cluster_tokens_per_sec, 2
),
"tp2_dp4_cost_reduction_vs_tp8_x": round(
tp8_nv.cost_per_1m_tokens_usd / tp2_dp4.cost_per_1m_tokens_usd, 2
),
"pcie_mismatch_tpot_slowdown_vs_nvlink_x": round(tp8_pcie.tpot_ms / tp8_nv.tpot_ms, 2),
}
def evaluate_context_parallel_long_prefill(seq_len: int = 131_072) -> dict[str, Any]:
"""Compare TP8 vs CP4+TP2 Ring Attention on 128k long-context prefill across 8 GPUs."""
# With GQA-8 and 128k sequence, TP8 requires duplicating KV heads if TP>8 or high activation peak
tp8_act_mem_gb = round((seq_len / 131_072) * 38.4 / 8.0 + 9.2, 2)
cp4_tp2_act_mem_gb = round((seq_len / 131_072) * 38.4 / 8.0 + 4.9, 2)
tp8_ttft_ms = round(seq_len * 0.0112 + 48.0, 2)
cp4_tp2_ttft_ms = round(seq_len * 0.0104 + 26.0, 2)
return {
"seq_len": seq_len,
"tp8_prefill": {
"ttft_ms": tp8_ttft_ms,
"activation_peak_gb_per_gpu": tp8_act_mem_gb,
"allreduce_barriers": 160,
},
"cp4_tp2_ring": {
"ttft_ms": cp4_tp2_ttft_ms,
"activation_peak_gb_per_gpu": cp4_tp2_act_mem_gb,
"allreduce_barriers": 160 // 2,
"ring_kv_overlap_efficiency_pct": 88.5,
},
"activation_mem_reduction_x": round(tp8_act_mem_gb / cp4_tp2_act_mem_gb, 2),
}
# ---------------------------------------------------------------------------
# Experiment 2 (#31): MoE Serving Across GPUs (EP, All-to-All & Hot-Expert Skew)
# ---------------------------------------------------------------------------
def _simulate_zipf_expert_loads(
rng: np.random.Generator,
num_experts: int,
ep_degree: int,
total_assignments: int,
zipf_s: float,
redundant_hot_experts: int,
num_steps: int = 8,
dispatch_tile: int = 64,
) -> tuple[float, np.ndarray]:
"""Simulate Zipfian expert traffic with Greedy EPLB replicas & Power-of-Choice dispatch."""
ranks = np.arange(1, num_experts + 1, dtype=np.float64)
probs = ranks ** (-zipf_s) if zipf_s > 0.0 else np.ones_like(ranks)
probs /= probs.sum()
step_sz = max(ep_degree, total_assignments // max(1, num_steps))
base_owner = np.arange(num_experts, dtype=np.int64) // (num_experts // ep_degree)
if redundant_hot_experts == 0:
# Unmitigated contiguous placement: correlated hot experts collide on low ranks.
step_ratios: list[float] = []
tot_loads = np.zeros(ep_degree, dtype=np.float64)
for _ in range(max(1, num_steps)):
chosen = rng.choice(num_experts, size=step_sz, p=probs)
sl = np.bincount(base_owner[chosen], minlength=ep_degree).astype(np.float64)
tot_loads += sl
step_ratios.append(float(sl.max() / max(1e-9, sl.mean())))
return float(np.mean(step_ratios)), tot_loads
# 1. Trailing telemetry window estimate (models periodic N=200 EPLB rebalance without oracle)
tel_window = rng.choice(num_experts, size=max(8192, step_sz * 4), p=probs)
hist_counts = np.bincount(tel_window, minlength=num_experts).astype(np.float64)
est_probs = (hist_counts + 0.5) / (hist_counts.sum() + 0.5 * num_experts)
# 2. Greedy Hot-Expert Replica Allocation: iteratively assign extra slot to argmax(load / replicas)
rep_cnt = np.ones(num_experts, dtype=np.int64)
for _ in range(redundant_hot_experts):
scores = np.where(rep_cnt < ep_degree, est_probs / rep_cnt, -1.0)
e_hot = int(np.argmax(scores))
if scores[e_hot] <= 0.0:
break
rep_cnt[e_hot] += 1
# 3. Greedy LPT balanced slot packing across EP GPUs (respecting <= slots_per_gpu & uniqueness)
slots = [
(float(est_probs[e] / rep_cnt[e]), int(e))
for e in range(num_experts)
for _ in range(int(rep_cnt[e]))
]
slots.sort(reverse=True)
slots_per_gpu = (len(slots) + ep_degree - 1) // ep_degree
gpu_exp = np.zeros(ep_degree, dtype=np.float64)
gpu_slots = np.zeros(ep_degree, dtype=np.int64)
expert_replicas: list[list[int]] = [[] for _ in range(num_experts)]
for weight, e in slots:
cands = [
g for g in range(ep_degree) if g not in expert_replicas[e] and gpu_slots[g] < slots_per_gpu
]
if not cands:
cands = [g for g in range(ep_degree) if g not in expert_replicas[e]]
tgt = min(cands, key=lambda g: (gpu_exp[g], gpu_slots[g], g))
expert_replicas[e].append(tgt)
gpu_exp[tgt] += weight
gpu_slots[tgt] += 1
# 4. Per-step All-to-All barrier simulation with independent DP-rank Power-of-Choice dispatch
step_ratios = []
tot_loads = np.zeros(ep_degree, dtype=np.float64)
per_dp = max(1, step_sz // ep_degree)
for _ in range(max(1, num_steps)):
chosen = rng.choice(num_experts, size=step_sz, p=probs)
sl = np.zeros(ep_degree, dtype=np.float64)
dl = np.zeros((ep_degree, ep_degree), dtype=np.float64)
pending = np.zeros((ep_degree, ep_degree), dtype=np.float64)
for idx, e_idx in enumerate(chosen):
r_id = min(ep_degree - 1, idx // per_dp)
reps = expert_replicas[int(e_idx)]
if len(reps) == 1:
g = reps[0]
elif len(reps) == 2:
g1, g2 = reps[0], reps[1]
g = g1 if dl[r_id, g1] <= dl[r_id, g2] else g2
else:
i1, i2 = rng.choice(len(reps), size=2, replace=False)
g1, g2 = reps[int(i1)], reps[int(i2)]
g = g1 if dl[r_id, g1] <= dl[r_id, g2] else g2
pending[r_id, g] += 1.0
sl[g] += 1.0
if (idx + 1) % dispatch_tile == 0:
dl += pending
pending.fill(0.0)
tot_loads += sl
step_ratios.append(float(sl.max() / max(1e-9, sl.mean())))
return float(np.mean(step_ratios)), tot_loads
def simulate_moe_ep_serving(seed: int = 42, zipf_s: float = 1.15) -> dict[str, Any]:
"""Simulate Sparse MoE (256 routed experts, Top-K=8) across TP8, DP8+EP8 & Wide-EP32 (#31)."""
rng = np.random.default_rng(seed)
num_layers = 61
num_experts = 256
top_k = 8
d_model = 7168
shared_compute_base_ms = 5.4
attention_base_ms = 4.2
# 1. TP8_DenseStyle (8 GPUs, batch=128 replicated KV)
b_tp8 = 128
# Tiny per-expert M_e split by TP8 causes severe Tensor Core under-utilization
avg_m_tp8 = (b_tp8 * top_k) / num_experts
tp8_expert_ms = 11.8 # low MFU fragmented GEMM + full weight reads
tp8_allreduce_ms = num_layers * 2.0 * _hockney_allreduce_ms(8, 2.0 * b_tp8 * d_model, 900.0, 1.8)
tp8_step_ms = attention_base_ms + shared_compute_base_ms + tp8_expert_ms + tp8_allreduce_ms
tp8_tok_s = (b_tp8 * 1000.0) / tp8_step_ms
# 2. DP8_EP8_Skewed (8 GPUs, DP=8 Attention = 8x KV, EP=8 Experts, no replication)
b_ep8 = 256 # DP8 frees 8x KV space, allowing 2x+ higher effective decode batch comfortably
skew_unmitigated, _ = _simulate_zipf_expert_loads(
rng,
num_experts=num_experts,
ep_degree=8,
total_assignments=b_ep8 * top_k * 8,
zipf_s=zipf_s,
redundant_hot_experts=0,
)
# EPLB-style modulo scatter baseline still shows heavy straggler when hot experts collide
avg_m_ep8 = (b_ep8 * top_k) / num_experts
ep8_a2a_ms = num_layers * 2.0 * (0.015 + (b_ep8 * top_k * d_model / 8.0) / (900e9) * 1000.0)
ep8_expert_base_ms = 4.8
ep8_skew_step_ms = (
attention_base_ms
+ shared_compute_base_ms
+ ep8_expert_base_ms * skew_unmitigated
+ ep8_a2a_ms * (0.75 + 0.25 * skew_unmitigated)
)
ep8_skew_tok_s = (b_ep8 * 1000.0) / ep8_skew_step_ms
# 3. DP8_EP8_RedundantHotExperts (8 GPUs + 48 redundant hot-expert slots EPLB)
skew_balanced, _ = _simulate_zipf_expert_loads(
rng,
num_experts=num_experts,
ep_degree=8,
total_assignments=b_ep8 * top_k * 8,
zipf_s=zipf_s,
redundant_hot_experts=48,
num_steps=8,
)
ep8_bal_step_ms = (
attention_base_ms
+ shared_compute_base_ms
+ ep8_expert_base_ms * skew_balanced
+ ep8_a2a_ms
)
ep8_bal_tok_s = (b_ep8 * 1000.0) / ep8_bal_step_ms
# 4. WideEP32_Pipelined (32 GPUs: DP=32, EP=32, global batch=1024, dual-microbatch A2A overlap)
b_wide = 1024
skew_wide, _ = _simulate_zipf_expert_loads(
rng,
num_experts=num_experts,
ep_degree=32,
total_assignments=b_wide * top_k * 4,
zipf_s=zipf_s,
redundant_hot_experts=64,
num_steps=4,
)
avg_m_wide = (b_wide * top_k) / num_experts # 32 tokens/expert -> saturates FP8 Tensor Cores!
wide_a2a_raw_ms = num_layers * 2.0 * (0.022 + (b_wide * top_k * d_model / 32.0) / (400e9) * 1000.0)
# Dual-microbatch overlap hides ~68% of All-to-All behind attention + shared expert
wide_a2a_exposed_ms = wide_a2a_raw_ms * 0.32
wide_step_ms = (
attention_base_ms * 0.92
+ shared_compute_base_ms * 0.90
+ 4.1 * skew_wide
+ wide_a2a_exposed_ms
)
wide_tok_s = (b_wide * 1000.0) / wide_step_ms
strategies = [
MoEServingMetrics(
strategy_name="TP8_DenseStyle",
num_gpus=8,
dp_degree=1,
ep_degree=1,
tp_degree=8,
redundant_hot_experts=0,
global_decode_batch=b_tp8,
avg_tokens_per_expert_invocation=round(avg_m_tp8, 2),
skew_straggler_ratio=1.0,
all_to_all_comm_ms=round(tp8_allreduce_ms, 2),
step_latency_ms=round(tp8_step_ms, 2),
kv_capacity_multiplier_vs_tp8=1.0,
cluster_decode_tokens_per_sec=round(tp8_tok_s, 1),
per_gpu_tokens_per_sec=round(tp8_tok_s / 8.0, 1),
),
MoEServingMetrics(
strategy_name="DP8_EP8_Skewed",
num_gpus=8,
dp_degree=8,
ep_degree=8,
tp_degree=1,
redundant_hot_experts=0,
global_decode_batch=b_ep8,
avg_tokens_per_expert_invocation=round(avg_m_ep8, 2),
skew_straggler_ratio=round(skew_unmitigated, 2),
all_to_all_comm_ms=round(ep8_a2a_ms, 2),
step_latency_ms=round(ep8_skew_step_ms, 2),
kv_capacity_multiplier_vs_tp8=8.0,
cluster_decode_tokens_per_sec=round(ep8_skew_tok_s, 1),
per_gpu_tokens_per_sec=round(ep8_skew_tok_s / 8.0, 1),
),
MoEServingMetrics(
strategy_name="DP8_EP8_RedundantHotExperts",
num_gpus=8,
dp_degree=8,
ep_degree=8,
tp_degree=1,
redundant_hot_experts=48,
global_decode_batch=b_ep8,
avg_tokens_per_expert_invocation=round(avg_m_ep8, 2),
skew_straggler_ratio=round(skew_balanced, 2),
all_to_all_comm_ms=round(ep8_a2a_ms, 2),
step_latency_ms=round(ep8_bal_step_ms, 2),
kv_capacity_multiplier_vs_tp8=8.0,
cluster_decode_tokens_per_sec=round(ep8_bal_tok_s, 1),
per_gpu_tokens_per_sec=round(ep8_bal_tok_s / 8.0, 1),
),
MoEServingMetrics(
strategy_name="WideEP32_Pipelined",
num_gpus=32,
dp_degree=32,
ep_degree=32,
tp_degree=1,
redundant_hot_experts=64,
global_decode_batch=b_wide,
avg_tokens_per_expert_invocation=round(avg_m_wide, 2),
skew_straggler_ratio=round(skew_wide, 2),
all_to_all_comm_ms=round(wide_a2a_exposed_ms, 2),
step_latency_ms=round(wide_step_ms, 2),
kv_capacity_multiplier_vs_tp8=32.0,
cluster_decode_tokens_per_sec=round(wide_tok_s, 1),
per_gpu_tokens_per_sec=round(wide_tok_s / 32.0, 1),
),
]
by_name = {s.strategy_name: s for s in strategies}
return {
"model": "DeepSeek-V3-Scale-MoE (256 routed, Top-K=8, 1 shared, FP8)",
"zipf_s": zipf_s,
"strategies": [s.model_dump() for s in strategies],
"ep8_balanced_vs_tp8_per_gpu_gain_x": round(
by_name["DP8_EP8_RedundantHotExperts"].per_gpu_tokens_per_sec
/ by_name["TP8_DenseStyle"].per_gpu_tokens_per_sec,
2,
),
"wide_ep32_vs_tp8_per_gpu_gain_x": round(
by_name["WideEP32_Pipelined"].per_gpu_tokens_per_sec
/ by_name["TP8_DenseStyle"].per_gpu_tokens_per_sec,
2,
),
"hot_expert_skew_reduction_x": round(
by_name["DP8_EP8_Skewed"].skew_straggler_ratio
/ by_name["DP8_EP8_RedundantHotExperts"].skew_straggler_ratio,
2,
),
}
def sweep_moe_zipf_skew(seed: int = 42) -> list[dict[str, Any]]:
"""Sweep Zipfian expert skew parameter s to verify EPLB straggler protection."""
rows: list[dict[str, Any]] = []
for s_val in (0.0, 0.7, 1.15, 1.5):
res = simulate_moe_ep_serving(seed=seed, zipf_s=s_val)
by_name = {item["strategy_name"]: item for item in res["strategies"]}
skewed = by_name["DP8_EP8_Skewed"]
balanced = by_name["DP8_EP8_RedundantHotExperts"]
rows.append(
{
"zipf_s": s_val,
"unmitigated_straggler_ratio": skewed["skew_straggler_ratio"],
"eplb_straggler_ratio": balanced["skew_straggler_ratio"],
"unmitigated_tok_s": skewed["cluster_decode_tokens_per_sec"],
"eplb_tok_s": balanced["cluster_decode_tokens_per_sec"],
}
)
return rows
# ---------------------------------------------------------------------------
# Experiment 3 (#33): Cache-Aware Prefix Routing Across 8 LLM Replicas
# ---------------------------------------------------------------------------
def _generate_skewed_cluster_trace(
seed: int = 42,
num_requests: int = 240,
arrival_rate_req_s: float = 28.0,
) -> list[ClusterRequest]:
"""Generate skewed enterprise multi-tenant traffic sharing 6 RAG/Agent prefixes."""
rng = np.random.default_rng(seed)
prefixes = [
("prefix_tenant_hot", 1536),
("prefix_rag_fin", 1536),
("prefix_code_agent", 1536),
("prefix_legal_doc", 1536),
("prefix_support_kb", 1536),
("prefix_sql_schema", 1536),
]
# Heavy hot-prefix skew: tenant_hot receives 46% of total traffic
weights = np.array([0.46, 0.16, 0.13, 0.10, 0.08, 0.07], dtype=np.float64)
t_ms = 0.0
mean_iat_ms = 1000.0 / arrival_rate_req_s
reqs: list[ClusterRequest] = []
for idx in range(num_requests):
t_ms += float(rng.exponential(mean_iat_ms))
p_idx = int(rng.choice(len(prefixes), p=weights))
pid, p_toks = prefixes[p_idx]
u_toks = int(rng.integers(128, 257))
out_toks = int(rng.integers(64, 129))
reqs.append(
ClusterRequest(
req_id=idx,
arrival_ms=t_ms,
prefix_id=pid,
prefix_tokens=p_toks,
unique_tokens=u_toks,
output_tokens=out_toks,
)
)
return reqs
def _consistent_hash_ring_candidates(prefix_id: str, num_replicas: int) -> list[int]:
"""Deterministic preference order of replicas for a prefix via SHA-256 Rendezvous hashing."""
scored: list[tuple[int, int]] = []
for r in range(num_replicas):
digest = hashlib.sha256(f"{prefix_id}:replica:{r}".encode()).digest()
val = int.from_bytes(digest[:8], "big")
scored.append((val, r))
scored.sort(reverse=True)
return [r for _, r in scored]
def _run_routing_policy(
requests: list[ClusterRequest],
policy: str,
num_replicas: int = 8,
capacity_blocks: int = 192,
load_bound_factor: float = 1.25,
ttft_slo_ms: float = 550.0,
) -> dict[str, Any]:
replicas = [
_ReplicaState(i, capacity_blocks=capacity_blocks, block_size=16) for i in range(num_replicas)
]
ttfts: list[float] = []
total_prefix_toks = 0
total_cache_hits = 0
for idx, req in enumerate(requests):
now_ms = req.arrival_ms
inflights = [r.inflight_count(now_ms) for r in replicas]
mean_inflight = max(1.0, sum(inflights) / num_replicas)
candidates = _consistent_hash_ring_candidates(req.prefix_id, num_replicas)
if policy == "round_robin":
chosen_id = idx % num_replicas
elif policy == "least_loaded":
chosen_id = min(
range(num_replicas),
key=lambda i: (inflights[i], replicas[i].worker_free_at_ms, i),
)
elif policy == "prefix_aware_unbounded":
chosen_id = candidates[0]
elif policy == "cache_aware_load_bounded":
bound_cap = max(1.0, load_bound_factor * mean_inflight)
chosen_id = candidates[0]
wait_ms = max(0.0, replicas[chosen_id].worker_free_at_ms - now_ms)
if inflights[chosen_id] > bound_cap or wait_ms > 90.0:
within_bound = [
c
for c in candidates
if inflights[c] <= bound_cap
and max(0.0, replicas[c].worker_free_at_ms - now_ms) <= 90.0
]
if within_bound:
chosen_id = within_bound[0]
else:
chosen_id = min(
range(num_replicas),
key=lambda i: (replicas[i].worker_free_at_ms, inflights[i], i),
)
else:
raise ValueError(f"Unknown routing policy: {policy}")
rep = replicas[chosen_id]
hits, misses = rep.access_prefix(req.prefix_id, req.prefix_tokens)
total_prefix_toks += req.prefix_tokens
total_cache_hits += hits
# Prefill runs at ~0.088 ms / uncached token, decode steps interleave cleanly
prefill_ms = 8.0 + (misses + req.unique_tokens) * 0.088 + hits * 0.0025
decode_ms = req.output_tokens * 0.24
start_ms = max(now_ms, rep.worker_free_at_ms)
ttft_ms = (start_ms - now_ms) + prefill_ms
finish_ms = start_ms + prefill_ms + decode_ms
rep.worker_free_at_ms = finish_ms
rep.request_count += 1
rep.compute_busy_ms += prefill_ms + decode_ms
rep.pending_end_times.append(finish_ms)
ttfts.append(ttft_ms)
ttft_arr = np.array(ttfts, dtype=np.float64)
counts = np.array([r.request_count for r in replicas], dtype=np.float64)
busy_ms = np.array([r.compute_busy_ms for r in replicas], dtype=np.float64)
max_load_ratio = float(busy_ms.max() / max(1e-9, busy_ms.mean()))
hit_rate_pct = 100.0 * total_cache_hits / max(1, total_prefix_toks)
slo_attain_pct = 100.0 * float(np.mean(ttft_arr <= ttft_slo_ms))
wall_s = max(1e-6, (max(r.worker_free_at_ms for r in replicas) - requests[0].arrival_ms) / 1000.0)
goodput_req_s = float(np.sum(ttft_arr <= ttft_slo_ms)) / wall_s
return {
"policy": policy,
"global_kv_hit_rate_pct": round(hit_rate_pct, 2),
"avg_ttft_ms": round(float(ttft_arr.mean()), 2),
"p99_ttft_ms": round(float(np.percentile(ttft_arr, 99)), 2),
"max_replica_load_ratio": round(max_load_ratio, 2),
"replica_request_counts": [int(c) for c in counts],
"slo_attainment_pct": round(slo_attain_pct, 2),
"goodput_req_s": round(goodput_req_s, 2),
}
def simulate_cache_aware_routing(
seed: int = 42,
load_bound_factor: float = 1.25,
) -> dict[str, Any]:
"""Evaluate 4 cluster prefix-routing policies across 8 LLM replicas under skewed load (#33)."""
requests = _generate_skewed_cluster_trace(seed=seed, num_requests=240, arrival_rate_req_s=62.0)
policies = [
_run_routing_policy(requests, "round_robin", load_bound_factor=load_bound_factor),
_run_routing_policy(requests, "least_loaded", load_bound_factor=load_bound_factor),
_run_routing_policy(requests, "prefix_aware_unbounded", load_bound_factor=load_bound_factor),
_run_routing_policy(requests, "cache_aware_load_bounded", load_bound_factor=load_bound_factor),
]
by_pol = {p["policy"]: p for p in policies}
rr = by_pol["round_robin"]
unb = by_pol["prefix_aware_unbounded"]
bnd = by_pol["cache_aware_load_bounded"]
return {
"num_replicas": 8,
"num_requests": len(requests),
"ttft_slo_ms": 550.0,
"load_bound_factor": load_bound_factor,
"policies": policies,
"bounded_vs_rr_hit_gain_pp": round(
bnd["global_kv_hit_rate_pct"] - rr["global_kv_hit_rate_pct"], 2
),
"bounded_vs_unbounded_p99_ttft_speedup_x": round(
unb["p99_ttft_ms"] / max(1e-6, bnd["p99_ttft_ms"]), 2
),
}
"""Exp 4-5 (#34, #35): Trace-to-Kernel Profiling, PyTorch Profiler, OTel & CUDA Graphs."""
from __future__ import annotations
import argparse
import json
import re
import time
from collections import deque
from pathlib import Path
from typing import Any
import numpy as np
import torch
import torch.nn.functional as F
import yaml
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import ReadableSpan, TracerProvider
from opentelemetry.sdk.trace.export import (
SimpleSpanProcessor,
SpanExporter,
SpanExportResult,
)
from torch.profiler import ProfilerActivity, profile
_DEFAULT_LAB_ROOT = Path(__file__).resolve().parents[2]
_SECRET_LITERAL_PATTERNS: tuple[tuple[str, re.Pattern[str]], ...] = (
("private_key_block", re.compile(r"-----BEGIN\s+(?:RSA|EC|OPENSSH|DSA)?\s*PRIVATE KEY-----")),
("hf_token_literal", re.compile(r"\bhf_[A-Za-z0-9]{16,}\b")),
("openai_key_literal", re.compile(r"\bsk-[A-Za-z0-9]{20,}\b")),
(
"inline_credential_assignment",
re.compile(
r"(?im)^[ \t]*(?:password|passwd|api_key|client_secret|hf_token|access_token)"
r'\s*[:=]\s*["\']?[A-Za-z0-9_./+@-]{6,}'
),
),
)
_IMAGE_REF_RE = re.compile(
r"(?:vllm/vllm-openai|lmsysorg/sglang|nvcr\.io/nvidia/[a-z0-9/_-]+):([A-Za-z0-9._-]+)"
)
# ---------------------------------------------------------------------------
# OpenTelemetry Bounded In-Memory Telemetry
# ---------------------------------------------------------------------------
class BoundedInMemorySpanExporter(SpanExporter):
"""Thread-safe bounded in-memory OpenTelemetry exporter retaining latest `maxlen` spans."""
def __init__(self, maxlen: int = 512) -> None:
self._spans: deque[ReadableSpan] = deque(maxlen=maxlen)
def export(self, spans: Any) -> SpanExportResult:
for span in spans:
self._spans.append(span)
return SpanExportResult.SUCCESS
def shutdown(self) -> None:
return None
def force_flush(self, timeout_millis: int = 30000) -> bool:
return True
def get_finished_spans(self) -> list[ReadableSpan]:
return list(self._spans)
def create_in_memory_telemetry(
service_name: str = "multi-gpu-profiling-cudagraph-lab",
maxlen: int = 512,
) -> tuple[Any, BoundedInMemorySpanExporter]:
"""Create an offline OpenTelemetry TracerProvider paired with BoundedInMemorySpanExporter."""
exporter = BoundedInMemorySpanExporter(maxlen=maxlen)
provider = TracerProvider(resource=Resource.create({"service.name": service_name}))
provider.add_span_processor(SimpleSpanProcessor(exporter))
return provider.get_tracer(service_name), exporter
def summarize_finished_spans(exporter: BoundedInMemorySpanExporter) -> dict[str, Any]:
"""Serialize finished spans and verify zero plaintext tokens or raw prompt leaks."""
spans = exporter.get_finished_spans()
forbidden_markers = ("hf_", "sk-", "BEGIN PRIVATE KEY", "password=", "raw_prompt:")
clean_attributes = True
serialized: list[dict[str, Any]] = []
for sp in spans:
attrs = dict(sp.attributes or {})
for v in attrs.values():
sval = str(v)
if any(marker in sval for marker in forbidden_markers):
clean_attributes = False
serialized.append(
{
"name": sp.name,
"status": sp.status.status_code.name,
"has_parent": sp.parent is not None,
"attributes": attrs,
}
)
return {
"span_count": len(serialized),
"clean_attributes": clean_attributes,
"spans": serialized,
}
# ---------------------------------------------------------------------------
# Experiment 4 (#34): Real PyTorch CPU Profiler & Request-to-Kernel Waterfall
# ---------------------------------------------------------------------------
def run_pytorch_cpu_op_profiling(seed: int = 42) -> dict[str, Any]:
"""Profile real PyTorch CPU Transformer steps: Fragmented Eager Ops vs Fused Batched Ops."""
torch.manual_seed(seed)
batch, hidden, num_heads, num_layers = 8, 256, 8, 4
head_dim = hidden // num_heads
x = torch.randn((batch, hidden), dtype=torch.float32)
wq_list = [torch.randn((hidden, hidden), dtype=torch.float32) * 0.04 for _ in range(num_layers)]
w1_list = [torch.randn((hidden, hidden * 2), dtype=torch.float32) * 0.04 for _ in range(num_layers)]
w2_list = [torch.randn((hidden * 2, hidden), dtype=torch.float32) * 0.04 for _ in range(num_layers)]
gamma_list = [torch.ones((hidden,), dtype=torch.float32) for _ in range(num_layers)]
def forward_fragmented(inp: torch.Tensor) -> torch.Tensor:
h = inp
for l_idx in range(num_layers):
rms = torch.sqrt(torch.mean(h * h, dim=-1, keepdim=True) + 1e-6)
h_norm = (h / rms) * gamma_list[l_idx]
wq = wq_list[l_idx]
head_outs: list[torch.Tensor] = []
for hd in range(num_heads):
w_slice = wq[:, hd * head_dim : (hd + 1) * head_dim]
head_outs.append(torch.matmul(h_norm, w_slice))
proj = torch.cat(head_outs, dim=-1)
h = h + proj
# Split FFN into small slices to mirror fragmented kernel dispatches
w1 = w1_list[l_idx]
w2 = w2_list[l_idx]
ff_parts: list[torch.Tensor] = []
chunk = hidden // 2
for part_idx in range(4):
w1_sub = w1[:, part_idx * chunk : (part_idx + 1) * chunk]
w2_sub = w2[part_idx * chunk : (part_idx + 1) * chunk, :]
act = F.silu(torch.matmul(h, w1_sub))
ff_parts.append(torch.matmul(act, w2_sub))
h = h + ff_parts[0] + ff_parts[1] + ff_parts[2] + ff_parts[3]
return h
def forward_fused(inp: torch.Tensor) -> torch.Tensor:
h = inp
for l_idx in range(num_layers):
rms = torch.rsqrt(h.pow(2).mean(dim=-1, keepdim=True) + 1e-6)
h_norm = (h * rms) * gamma_list[l_idx]
h = h + torch.matmul(h_norm, wq_list[l_idx])
h = h + torch.matmul(F.silu(torch.matmul(h, w1_list[l_idx])), w2_list[l_idx])
return h
with torch.no_grad():
out_frag = forward_fragmented(x)
out_fused = forward_fused(x)
max_abs_diff = float(torch.max(torch.abs(out_frag - out_fused)).item())
with profile(activities=[ProfilerActivity.CPU], record_shapes=False) as prof_frag:
for _ in range(3):
_ = forward_fragmented(x)
frag_events = prof_frag.key_averages()
frag_op_count = int(sum(ev.count for ev in frag_events))
with profile(activities=[ProfilerActivity.CPU], record_shapes=False) as prof_fused:
for _ in range(3):
_ = forward_fused(x)
fused_events = prof_fused.key_averages()
fused_op_count = int(sum(ev.count for ev in fused_events))
# Timed loop verifies real CPU speedup without injecting jittery floats into deterministic JSON
t0 = time.perf_counter()
for _ in range(25):
_ = forward_fragmented(x)
frag_s = time.perf_counter() - t0
t1 = time.perf_counter()
for _ in range(25):
_ = forward_fused(x)
fused_s = time.perf_counter() - t1
top_fused_ops = [
{"op": ev.key, "calls": int(ev.count)}
for ev in sorted(fused_events, key=lambda e: (-int(e.count), e.key))[:4]
]
return {
"max_abs_diff_vs_fragmented": round(max_abs_diff, 7),
"fragmented_cpu_aten_ops_3iters": frag_op_count,
"fused_cpu_aten_ops_3iters": fused_op_count,
"aten_op_count_reduction_x": round(frag_op_count / max(1, fused_op_count), 2),
"live_fused_faster_than_fragmented": fused_s < frag_s,
"top_fused_aten_ops": top_fused_ops,
}
def classify_waterfall_bottleneck(stages_ms: dict[str, float]) -> dict[str, Any]:
"""Classify dominant serving bottleneck regime from 6-stage waterfall spans."""
total_ms = max(1e-6, sum(stages_ms.values()))
cpu_launch_ms = stages_ms.get("cuda_launch_cpu", 0.0) + stages_ms.get("scheduler_queue", 0.0)
hbm_ms = stages_ms.get("gpu_hbm_kv_read", 0.0)
comm_ms = stages_ms.get("nccl_allreduce", 0.0)
compute_ms = stages_ms.get("gpu_compute_kernel", 0.0)
gateway_tok_ms = stages_ms.get("api_gateway", 0.0) + stages_ms.get("tokenizer", 0.0)
shares = {k: round(100.0 * v / total_ms, 2) for k, v in stages_ms.items()}
cpu_share = 100.0 * cpu_launch_ms / total_ms
hbm_share = 100.0 * hbm_ms / total_ms
comm_share = 100.0 * comm_ms / total_ms
# GPU sits idle during CPU launch gaps, tokenizer, and gateway stalls
gpu_bubble_pct = round(100.0 * (cpu_launch_ms + gateway_tok_ms * 0.5) / total_ms, 2)
if comm_share >= 45.0:
regime = "nccl_comm_bound"
fix = "Restore NVLink P2P topology or shift TP8 -> TP2+DP4 / Wide-EP overlap."
elif cpu_share >= 42.0:
regime = "cpu_launch_bound"
fix = "Enable Piecewise CUDA Graphs and zero-overhead scheduler separation."
elif hbm_share >= 48.0:
regime = "hbm_bandwidth_bound"
fix = "Apply FP8/INT4-AWQ quantization, MLA/FP8 KV-Cache, or larger decode batch."
else:
regime = "balanced_optimized_step"
fix = "Healthy regime: GPU compute/memory balanced with minimal CPU launch bubble."
dominant_stage = max(stages_ms, key=lambda k: stages_ms[k])
return {
"total_step_ms": round(total_ms, 2),
"dominant_stage": dominant_stage,
"predicted_regime": regime,
"gpu_bubble_pct": gpu_bubble_pct,
"useful_compute_pct": round(100.0 * compute_ms / total_ms, 2),
"stage_shares_pct": shares,
"recommended_fix": fix,
}
def run_request_to_kernel_profiling(
seed: int = 42,
tracer: Any | None = None,
) -> dict[str, Any]:
"""Run PyTorch CPU op profiling + emit OTel waterfall spans across 4 failure profiles (#34)."""
pytorch_ops = run_pytorch_cpu_op_profiling(seed=seed)
local_exporter: BoundedInMemorySpanExporter | None = None
if tracer is None:
tracer, local_exporter = create_in_memory_telemetry("lab18-waterfall-profiler")
profiles: dict[str, dict[str, float]] = {
"cpu_launch_bound": {
"api_gateway": 0.45,
"tokenizer": 0.65,
"scheduler_queue": 1.35,
"cuda_launch_cpu": 5.18,
"gpu_compute_kernel": 1.65,
"gpu_hbm_kv_read": 1.42,
"nccl_allreduce": 0.40,
},
"hbm_bandwidth_bound": {
"api_gateway": 0.40,
"tokenizer": 0.55,
"scheduler_queue": 0.45,
"cuda_launch_cpu": 0.38,
"gpu_compute_kernel": 1.45,
"gpu_hbm_kv_read": 11.80,
"nccl_allreduce": 0.65,
},
"nccl_comm_bound": {
"api_gateway": 0.45,
"tokenizer": 0.55,
"scheduler_queue": 0.50,
"cuda_launch_cpu": 0.42,
"gpu_compute_kernel": 2.30,
"gpu_hbm_kv_read": 2.95,
"nccl_allreduce": 16.40,
},
"balanced_optimized_step": {
"api_gateway": 0.40,
"tokenizer": 0.48,
"scheduler_queue": 0.28,
"cuda_launch_cpu": 0.38,
"gpu_compute_kernel": 3.40,
"gpu_hbm_kv_read": 2.85,
"nccl_allreduce": 0.45,
},
}
analyzed_profiles: dict[str, dict[str, Any]] = {}
for prof_name, stage_map in profiles.items():
classification = classify_waterfall_bottleneck(stage_map)
with tracer.start_as_current_span(f"trace.waterfall.{prof_name}") as parent_span:
parent_span.set_attribute("profile.name", prof_name)
parent_span.set_attribute("profile.regime", classification["predicted_regime"])
parent_span.set_attribute("profile.total_ms", classification["total_step_ms"])
for stage_name, dur_ms in stage_map.items():
with tracer.start_as_current_span(f"stage.{stage_name}") as child_span:
child_span.set_attribute("stage.name", stage_name)
child_span.set_attribute("stage.duration_ms", dur_ms)
analyzed_profiles[prof_name] = {
"stages_ms": stage_map,
**classification,
}
result: dict[str, Any] = {
"pytorch_cpu_profiler": pytorch_ops,
"waterfall_profiles": analyzed_profiles,
}
if local_exporter is not None:
result["local_otel_summary"] = summarize_finished_spans(local_exporter)
return result
# ---------------------------------------------------------------------------
# Experiment 5 (#35): CUDA Graphs & Piecewise Capture Bucketing Simulator
# ---------------------------------------------------------------------------
def simulate_cuda_graph_bucketing(seed: int = 42, num_steps: int = 120) -> dict[str, Any]:
"""Compare Eager, Monolithic 2D, Power-of-2 & Piecewise Hybrid CUDA Graph buckets (#35)."""
rng = np.random.default_rng(seed)
# Dynamic continuous-batching step trace: variable active batches B_t & ragged seq lengths
active_batches = rng.choice(
np.array([2, 4, 7, 11, 15, 19, 24, 30, 35, 44, 53, 68, 84, 102], dtype=np.int64),
size=num_steps,
p=np.array([0.08, 0.12, 0.12, 0.12, 0.10, 0.10, 0.08, 0.07, 0.06, 0.05, 0.04, 0.03, 0.02, 0.01]),
)
active_seq_lens = rng.integers(256, 3840, size=num_steps)
# 280 small kernels per layer-stack decode step at 18.5 us/launch when eager
eager_launch_ms = 280 * 0.0185 # 5.18 ms/step!
compute_ms_per_tok = 0.062
def eval_strategy(mode: str) -> dict[str, Any]:
if mode == "eager_no_graphs":
pad_ratios: list[float] = []
step_times: list[float] = []
for b, s in zip(active_batches, active_seq_lens, strict=True):
pad_ratios.append(0.0)
attn_ms = (b * s * 1e-5) + 0.55
step_times.append(eager_launch_ms + b * compute_ms_per_tok + attn_ms)
graph_pool_vram_gib = 0.0
avg_launch_ms = eager_launch_ms
kv_seq_pad_pct = 0.0
captured_graphs = 0
elif mode == "monolithic_2d_capture":
b_buckets = [1, 4, 16, 32, 64, 128]
s_buckets = [512, 1024, 2048, 4096]
captured_graphs = len(b_buckets) * len(s_buckets) # 24 monolithic graphs!
graph_pool_vram_gib = round(captured_graphs * 0.36, 2) # 8.64 GiB -> explodes VRAM!
avg_launch_ms = 0.06
pad_ratios = []
seq_pad_ratios: list[float] = []
step_times = []
for b, s in zip(active_batches, active_seq_lens, strict=True):
b_cap = next(bk for bk in b_buckets if bk >= b)
s_cap = next(sk for sk in s_buckets if sk >= s)
pad_ratios.append((b_cap - b) / b_cap)
seq_pad_ratios.append((s_cap - s) / s_cap)
attn_ms = (b_cap * s_cap * 1e-5) + 0.45
step_times.append(avg_launch_ms + b_cap * compute_ms_per_tok + attn_ms)
kv_seq_pad_pct = 100.0 * float(np.mean(seq_pad_ratios))
elif mode == "power2_coarse_buckets":
b_buckets = [1, 2, 4, 8, 16, 32, 64, 128]
captured_graphs = len(b_buckets)
graph_pool_vram_gib = round(captured_graphs * 0.16, 2) # 1.28 GiB
# Piecewise splits around attention: ~14 small attention launches + 2 graph launches
avg_launch_ms = 0.38
kv_seq_pad_pct = 0.0
pad_ratios = []
step_times = []
for b, s in zip(active_batches, active_seq_lens, strict=True):
b_cap = next(bk for bk in b_buckets if bk >= b)
pad_ratios.append((b_cap - b) / b_cap)
attn_ms = (b * s * 1e-5) + 0.45 # varlen attention uses exact b & s!
step_times.append(avg_launch_ms + b_cap * compute_ms_per_tok + attn_ms)
elif mode == "piecewise_hybrid_buckets":
b_buckets = [1, 2, 4, 8, 16, 24, 32, 48, 64, 96, 128]
captured_graphs = len(b_buckets)
graph_pool_vram_gib = round(captured_graphs * 0.16, 2) # 1.76 GiB <= 3.5 GiB budget!
avg_launch_ms = 0.38
kv_seq_pad_pct = 0.0
pad_ratios = []
step_times = []
for b, s in zip(active_batches, active_seq_lens, strict=True):
b_cap = next(bk for bk in b_buckets if bk >= b)
pad_ratios.append((b_cap - b) / b_cap)
attn_ms = (b * s * 1e-5) + 0.45
step_times.append(avg_launch_ms + b_cap * compute_ms_per_tok + attn_ms)
else:
raise ValueError(f"Unknown CUDA graph mode: {mode}")
avg_step_ms = float(np.mean(step_times))
mean_active_b = float(np.mean(active_batches))
eff_tok_s = (mean_active_b * 1000.0) / avg_step_ms
return {
"mode": mode,
"captured_graphs_count": captured_graphs,
"cpu_launch_overhead_ms": round(avg_launch_ms, 2),
"batch_compute_pad_waste_pct": round(100.0 * float(np.mean(pad_ratios)), 2),
"kv_seq_pad_waste_pct": round(kv_seq_pad_pct, 2),
"graph_pool_vram_gib": graph_pool_vram_gib,
"within_3_5gib_vram_budget": graph_pool_vram_gib <= 3.5,
"avg_step_ms": round(avg_step_ms, 2),
"p99_step_ms": round(float(np.percentile(step_times, 99)), 2),
"effective_decode_tokens_per_sec": round(eff_tok_s, 1),
}
results = [
eval_strategy("eager_no_graphs"),
eval_strategy("monolithic_2d_capture"),
eval_strategy("power2_coarse_buckets"),
eval_strategy("piecewise_hybrid_buckets"),
]
by_mode = {r["mode"]: r for r in results}
eager = by_mode["eager_no_graphs"]
p2 = by_mode["power2_coarse_buckets"]
piecewise = by_mode["piecewise_hybrid_buckets"]
return {
"num_steps": num_steps,
"vram_budget_gib": 3.5,
"strategies": results,
"cpu_launch_reduction_vs_eager_x": round(
eager["cpu_launch_overhead_ms"] / piecewise["cpu_launch_overhead_ms"], 2
),
"piecewise_speedup_vs_eager_x": round(
piecewise["effective_decode_tokens_per_sec"] / eager["effective_decode_tokens_per_sec"], 2
),
"pad_waste_reduction_vs_power2_x": round(
p2["batch_compute_pad_waste_pct"] / max(0.01, piecewise["batch_compute_pad_waste_pct"]), 2
),
}
# ---------------------------------------------------------------------------
# Tier-1 Static Config Security & Policy Audit
# ---------------------------------------------------------------------------
def audit_lab18_configs(lab_root: Path | None = None) -> dict[str, Any]:
"""Audit Tier-1 YAML configs for pinned images, zero plaintext secrets & SOTA policies."""
root = lab_root or _DEFAULT_LAB_ROOT
cfg_dir = root / "configs"
yaml_files = sorted(cfg_dir.glob("*.yaml"))
violations: list[str] = []
pinned_images_count = 0
plaintext_secrets_count = 0
latest_tags_count = 0
for yfile in yaml_files:
raw_text = yfile.read_text(encoding="utf-8")
for label, pat in _SECRET_LITERAL_PATTERNS:
if pat.search(raw_text):
plaintext_secrets_count += 1
violations.append(f"{yfile.name}: secret pattern '{label}'")
if "0.0.0.0" in raw_text:
violations.append(f"{yfile.name}: unrestricted 0.0.0.0 bind")
if ":latest" in raw_text:
latest_tags_count += 1
violations.append(f"{yfile.name}: forbidden ':latest' container tag")
for m in _IMAGE_REF_RE.finditer(raw_text):
tag = m.group(1)
if tag == "latest":
violations.append(f"{yfile.name}: unpinned image tag ':latest'")
else:
pinned_images_count += 1
parsed = yaml.safe_load(raw_text)
if not isinstance(parsed, dict):
violations.append(f"{yfile.name}: YAML root must be a mapping")
continue
spec = parsed.get("spec", {})
if yfile.name == "moe_wide_ep_vllm_config.yaml":
wide = spec.get("parallelism", {}).get("moe_decode_wide_ep", {})
if int(wide.get("ep_size", 0)) < 16 or int(wide.get("redundant_hot_experts", 0)) <= 0:
violations.append(f"{yfile.name}: Wide-EP or redundant hot experts disabled")
if spec.get("network", {}).get("bind_host") != "127.0.0.1":
violations.append(f"{yfile.name}: network.bind_host must be 127.0.0.1")
elif yfile.name == "cuda_graph_and_router_config.yaml":
router = spec.get("router", {})
cg = spec.get("cuda_graphs", {})
prof = spec.get("profiling", {})
if router.get("policy") != "cache_aware_load_bounded":
violations.append(f"{yfile.name}: router.policy must be cache_aware_load_bounded")
if float(router.get("load_bound_factor", 99.0)) > 2.0:
violations.append(f"{yfile.name}: load_bound_factor too loose")
if cg.get("mode") != "piecewise_hybrid_buckets":
violations.append(f"{yfile.name}: cuda_graphs.mode must be piecewise_hybrid_buckets")
if not prof.get("redact_prompt_text", False):
violations.append(f"{yfile.name}: redact_prompt_text must be true")
return {
"scanned_files_count": len(yaml_files),
"pinned_images_count": pinned_images_count,
"plaintext_secrets_count": plaintext_secrets_count,
"latest_tags_count": latest_tags_count,
"violations": violations,
"all_passed": len(yaml_files) >= 2 and len(violations) == 0,
}
def main(argv: list[str] | None = None) -> None:
parser = argparse.ArgumentParser(
description="Run Lab 18 Profiling, CUDA Graph Bucketing & Config Audit"
)
parser.add_argument("--seed", type=int, default=42)
args = parser.parse_args(argv if argv is not None else [])
tracer, exporter = create_in_memory_telemetry()
prof = run_request_to_kernel_profiling(seed=args.seed, tracer=tracer)
cg = simulate_cuda_graph_bucketing(seed=args.seed)
audit = audit_lab18_configs(_DEFAULT_LAB_ROOT)
otel = summarize_finished_spans(exporter)
print(
json.dumps(
{
"pytorch_cpu_profiler": prof["pytorch_cpu_profiler"],
"cuda_graphs": cg,
"config_audit": audit,
"otel_spans": otel["span_count"],
},
indent=2,
)
)
if __name__ == "__main__":
main()
"""Deterministic CLI runner generating artifacts/t2_ch23_lab18_results.json."""
from __future__ import annotations
import argparse
import json
from pathlib import Path
from typing import Any
from multi_gpu_profiling_cudagraph_lab.multi_gpu_moe_and_routing import (
evaluate_context_parallel_long_prefill,
evaluate_multi_gpu_layouts,
simulate_cache_aware_routing,
simulate_moe_ep_serving,
sweep_moe_zipf_skew,
)
from multi_gpu_profiling_cudagraph_lab.trace_profiling_and_cudagraphs import (
audit_lab18_configs,
create_in_memory_telemetry,
run_request_to_kernel_profiling,
simulate_cuda_graph_bucketing,
summarize_finished_spans,
)
LAB_ROOT = Path(__file__).resolve().parents[1]
def run_full_benchmark_suite(seed: int = 42) -> dict[str, Any]:
"""Execute all Lab 18 multi-GPU, MoE, routing, profiling & CUDA graph benchmarks."""
tracer, exporter = create_in_memory_telemetry("multi-gpu-profiling-cudagraph-lab")
with tracer.start_as_current_span("lab18.benchmark.suite") as root_span:
root_span.set_attribute("lab.seed", seed)
with tracer.start_as_current_span("lab18.multi_gpu_layouts") as sp:
layout_eval = evaluate_multi_gpu_layouts()
cp_eval = evaluate_context_parallel_long_prefill()
sp.set_attribute(
"layout.tp2_dp4_gain_vs_tp8_x",
layout_eval["tp2_dp4_throughput_gain_vs_tp8_x"],
)
sp.set_attribute(
"layout.pcie_slowdown_x",
layout_eval["pcie_mismatch_tpot_slowdown_vs_nvlink_x"],
)
with tracer.start_as_current_span("lab18.moe_wide_ep_serving") as sp:
moe_eval = simulate_moe_ep_serving(seed=seed)
moe_skew_sweep = sweep_moe_zipf_skew(seed=seed)
sp.set_attribute(
"moe.wide_ep32_per_gpu_gain_x",
moe_eval["wide_ep32_vs_tp8_per_gpu_gain_x"],
)
sp.set_attribute(
"moe.skew_reduction_x",
moe_eval["hot_expert_skew_reduction_x"],
)
with tracer.start_as_current_span("lab18.cache_aware_prefix_routing") as sp:
routing_eval = simulate_cache_aware_routing(seed=seed)
by_pol = {p["policy"]: p for p in routing_eval["policies"]}
sp.set_attribute(
"router.bounded_kv_hit_pct",
by_pol["cache_aware_load_bounded"]["global_kv_hit_rate_pct"],
)
sp.set_attribute(
"router.bounded_p99_ttft_ms",
by_pol["cache_aware_load_bounded"]["p99_ttft_ms"],
)
with tracer.start_as_current_span("lab18.trace_to_kernel_profiling") as sp:
prof_eval = run_request_to_kernel_profiling(seed=seed, tracer=tracer)
sp.set_attribute(
"prof.aten_op_reduction_x",
prof_eval["pytorch_cpu_profiler"]["aten_op_count_reduction_x"],
)
with tracer.start_as_current_span("lab18.cuda_graph_bucketing") as sp:
cg_eval = simulate_cuda_graph_bucketing(seed=seed)
sp.set_attribute(
"cg.cpu_launch_reduction_x",
cg_eval["cpu_launch_reduction_vs_eager_x"],
)
sp.set_attribute(
"cg.piecewise_speedup_x",
cg_eval["piecewise_speedup_vs_eager_x"],
)
with tracer.start_as_current_span("lab18.static_config_audit") as sp:
config_audit = audit_lab18_configs(LAB_ROOT)
sp.set_attribute("audit.all_passed", config_audit["all_passed"])
sp.set_attribute("audit.scanned_files", config_audit["scanned_files_count"])
telemetry_summary = summarize_finished_spans(exporter)
layouts_map = {item["layout_name"]: item for item in layout_eval["layouts"]}
tp8_nv = layouts_map["TP8_NVLink"]
tp8_pcie = layouts_map["TP8_PCIe_Mismatch"]
tp2_dp4 = layouts_map["TP2_DP4_NVLink_FP8"]
moe_map = {item["strategy_name"]: item for item in moe_eval["strategies"]}
moe_tp8 = moe_map["TP8_DenseStyle"]
moe_ep8_skew = moe_map["DP8_EP8_Skewed"]
moe_ep8_bal = moe_map["DP8_EP8_RedundantHotExperts"]
moe_wide = moe_map["WideEP32_Pipelined"]
pol_map = {item["policy"]: item for item in routing_eval["policies"]}
r_rr = pol_map["round_robin"]
r_unb = pol_map["prefix_aware_unbounded"]
r_bnd = pol_map["cache_aware_load_bounded"]
pt_prof = prof_eval["pytorch_cpu_profiler"]
wf_cpu = prof_eval["waterfall_profiles"]["cpu_launch_bound"]
wf_nccl = prof_eval["waterfall_profiles"]["nccl_comm_bound"]
wf_bal = prof_eval["waterfall_profiles"]["balanced_optimized_step"]
cg_map = {item["mode"]: item for item in cg_eval["strategies"]}
cg_eager = cg_map["eager_no_graphs"]
cg_p2 = cg_map["power2_coarse_buckets"]
cg_pw = cg_map["piecewise_hybrid_buckets"]
tp2_cost_red = layout_eval["tp2_dp4_cost_reduction_vs_tp8_x"]
pcie_slow = layout_eval["pcie_mismatch_tpot_slowdown_vs_nvlink_x"]
moe_gain = moe_eval["wide_ep32_vs_tp8_per_gpu_gain_x"]
cg_launch_cut = cg_eval["cpu_launch_reduction_vs_eager_x"]
cg_pad_cut = cg_eval["pad_waste_reduction_vs_power2_x"]
workbench_panels = {
"kpis": [
{
"id": "kpi_multigpu_tp2_dp4_vs_pcie",
"label": "TP2+DP4 NVLink vs TP8 NVLink & PCIe",
"value": f"{tp2_dp4['cluster_tokens_per_sec']} tok/s",
"unit": (
f"({layout_eval['tp2_dp4_throughput_gain_vs_tp8_x']}x vs TP8, "
f"${tp2_dp4['cost_per_1m_tokens_usd']}/1M)"
),
"status": "ok",
"detail": (
f"TP2+DP4 cuts cost {tp2_cost_red}x vs TP8; "
f"PCIe mismatch slows TP8 TPOT {pcie_slow}x ({tp8_pcie['tpot_ms']} ms)."
),
},
{
"id": "kpi_moe_wide_ep_scaling",
"label": "MoE Wide-EP32 & Hot-Expert Replication",
"value": f"{moe_wide['per_gpu_tokens_per_sec']} tok/s/GPU",
"unit": f"({moe_gain}x vs TP8)",
"status": "ok",
"detail": (
"Redundant hot experts drop Zipf straggler ratio "
f"{moe_ep8_skew['skew_straggler_ratio']}x -> "
f"{moe_ep8_bal['skew_straggler_ratio']}x "
f"({moe_eval['hot_expert_skew_reduction_x']}x tighter)."
),
},
{
"id": "kpi_cache_aware_load_bounded",
"label": "Cache-Aware Load-Bounded Routing (8 Replicas)",
"value": f"{r_bnd['global_kv_hit_rate_pct']}% hit | {r_bnd['p99_ttft_ms']} ms p99",
"unit": f"({routing_eval['bounded_vs_unbounded_p99_ttft_speedup_x']}x vs Unbounded)",
"status": "ok",
"detail": (
f"Hits {r_bnd['global_kv_hit_rate_pct']}% (vs {r_rr['global_kv_hit_rate_pct']}% RR) "
f"while avoiding {r_unb['p99_ttft_ms']} ms hot-spot overload "
f"(max load {r_bnd['max_replica_load_ratio']}x vs "
f"{r_unb['max_replica_load_ratio']}x)."
),
},
{
"id": "kpi_pytorch_otel_waterfall",
"label": "PyTorch CPU Ops & OTel Waterfall Classifier",
"value": f"{pt_prof['aten_op_count_reduction_x']}x fewer ATen ops",
"unit": f"({wf_cpu['gpu_bubble_pct']}% -> {wf_bal['gpu_bubble_pct']}% bubble)",
"status": "ok",
"detail": (
"Fusing fragmented ops drops CPU ATen calls "
f"{pt_prof['fragmented_cpu_aten_ops_3iters']} -> "
f"{pt_prof['fused_cpu_aten_ops_3iters']}; "
f"OTel waterfall isolates {wf_nccl['predicted_regime']}."
),
},
{
"id": "kpi_piecewise_cuda_graphs",
"label": "Piecewise CUDA Graphs + Hybrid Buckets",
"value": (
f"{cg_pw['cpu_launch_overhead_ms']} vs "
f"{cg_eager['cpu_launch_overhead_ms']} ms launch"
),
"unit": (
f"({cg_launch_cut}x launch cut, "
f"{cg_eval['piecewise_speedup_vs_eager_x']}x tok/s)"
),
"status": "ok",
"detail": (
f"Hybrid buckets cut batch pad waste {cg_pad_cut}x vs P2 "
f"({cg_pw['batch_compute_pad_waste_pct']}% vs "
f"{cg_p2['batch_compute_pad_waste_pct']}%) "
f"inside {cg_pw['graph_pool_vram_gib']} GiB VRAM."
),
},
{
"id": "kpi_config_audit_and_otel",
"label": "Tier-1 YAML Audit & Bounded OTel Spans",
"value": f"{config_audit['scanned_files_count']} YAMLs clean",
"unit": f"({telemetry_summary['span_count']} OTel spans)",
"status": "ok",
"detail": (
f"0 secrets, 0 :latest tags ({config_audit['pinned_images_count']} pinned images), "
f"0 raw prompts leaked in {telemetry_summary['span_count']} spans."
),
},
],
"bars": [
{
"id": "bar_multigpu_throughput",
"title": "8x H100 70B FP8 Cluster Throughput (tokens/s)",
"metric_label": "tokens/s",
"items": [
{
"label": "TP2_DP4_NVLink_FP8",
"value": tp2_dp4["cluster_tokens_per_sec"],
"display": (
f"{tp2_dp4['cluster_tokens_per_sec']} tok/s "
f"(${tp2_dp4['cost_per_1m_tokens_usd']}/1M)"
),
"css_class": "is-fast",
},
{
"label": "TP8_NVLink",
"value": tp8_nv["cluster_tokens_per_sec"],
"display": (
f"{tp8_nv['cluster_tokens_per_sec']} tok/s "
f"(${tp8_nv['cost_per_1m_tokens_usd']}/1M)"
),
"css_class": "is-fast",
},
{
"label": "TP8_PCIe_Mismatch",
"value": tp8_pcie["cluster_tokens_per_sec"],
"display": (
f"{tp8_pcie['cluster_tokens_per_sec']} tok/s "
f"(TPOT={tp8_pcie['tpot_ms']} ms)"
),
"css_class": "is-slow",
},
],
},
{
"id": "bar_moe_per_gpu_throughput",
"title": "Sparse MoE Decode Per-GPU Throughput (tokens/s/GPU)",
"metric_label": "tokens/s/GPU",
"items": [
{
"label": "WideEP32_Pipelined",
"value": moe_wide["per_gpu_tokens_per_sec"],
"display": f"{moe_wide['per_gpu_tokens_per_sec']} tok/s/GPU ({moe_gain}x)",
"css_class": "is-fast",
},
{
"label": "DP8_EP8_RedundantHot",
"value": moe_ep8_bal["per_gpu_tokens_per_sec"],
"display": (
f"{moe_ep8_bal['per_gpu_tokens_per_sec']} tok/s/GPU "
f"(skew {moe_ep8_bal['skew_straggler_ratio']}x)"
),
"css_class": "is-fast",
},
{
"label": "TP8_DenseStyle",
"value": moe_tp8["per_gpu_tokens_per_sec"],
"display": f"{moe_tp8['per_gpu_tokens_per_sec']} tok/s/GPU (1x KV cap)",
"css_class": "is-slow",
},
],
},
{
"id": "bar_router_p99_ttft",
"title": "8-Replica Cluster p99 TTFT (ms) Under Hot-Prefix Skew",
"metric_label": "p99 TTFT (ms)",
"items": [
{
"label": "prefix_aware_unbounded",
"value": r_unb["p99_ttft_ms"],
"display": (
f"{r_unb['p99_ttft_ms']} ms "
f"(hot-spot {r_unb['max_replica_load_ratio']}x!)"
),
"css_class": "is-slow",
},
{
"label": "cache_aware_load_bounded",
"value": r_bnd["p99_ttft_ms"],
"display": (
f"{r_bnd['p99_ttft_ms']} ms "
f"({r_bnd['global_kv_hit_rate_pct']}% hit)"
),
"css_class": "is-fast",
},
],
},
{
"id": "bar_cuda_graph_step_ms",
"title": "Dynamic Batch Decode Step Latency (ms): Eager vs Piecewise CUDA Graphs",
"metric_label": "avg step (ms)",
"items": [
{
"label": "eager_no_graphs",
"value": cg_eager["avg_step_ms"],
"display": (
f"{cg_eager['avg_step_ms']} ms "
f"({cg_eager['cpu_launch_overhead_ms']} ms launch)"
),
"css_class": "is-slow",
},
{
"label": "piecewise_hybrid_buckets",
"value": cg_pw["avg_step_ms"],
"display": (
f"{cg_pw['avg_step_ms']} ms "
f"({cg_pw['cpu_launch_overhead_ms']} ms launch)"
),
"css_class": "is-fast",
},
],
},
],
"tables": [
{
"id": "table_multigpu_layouts",
"title": "Exp 1 (#32): 8x H100 Multi-GPU Parallelism Layouts (70B FP8)",
"columns": ["layout", "ttft_and_tpot", "comm_and_bubble", "throughput_and_cost"],
"rows": [
[
item["layout_name"],
f"{item['ttft_ms']} ms | {item['tpot_ms']} ms (SLO={item['slo_met']})",
f"comm={item['comm_overhead_pct']}% | bubble={item['pp_bubble_pct']}%",
f"{item['cluster_tokens_per_sec']} tok/s (${item['cost_per_1m_tokens_usd']}/1M)",
]
for item in layout_eval["layouts"]
],
},
{
"id": "table_moe_ep_strategies",
"title": "Exp 2 (#31): Sparse MoE Serving Across TP8, DP8+EP8 & Wide-EP32",
"columns": ["strategy", "skew_and_comm", "kv_cap_and_m_e", "per_gpu_and_cluster_tok_s"],
"rows": [
[
item["strategy_name"],
f"skew={item['skew_straggler_ratio']}x | comm={item['all_to_all_comm_ms']} ms",
(
f"{item['kv_capacity_multiplier_vs_tp8']}x KV | "
f"m_e={item['avg_tokens_per_expert_invocation']}"
),
(
f"{item['per_gpu_tokens_per_sec']} /GPU "
f"({item['cluster_decode_tokens_per_sec']} total)"
),
]
for item in moe_eval["strategies"]
],
},
{
"id": "table_cache_aware_routing",
"title": "Exp 3 (#33): 8-Replica Cluster Routing Under Zipfian Prefix Skew",
"columns": ["routing_policy", "kv_hit_rate", "p99_ttft_and_load", "slo_and_goodput"],
"rows": [
[
item["policy"],
f"{item['global_kv_hit_rate_pct']}%",
f"{item['p99_ttft_ms']} ms | load={item['max_replica_load_ratio']}x",
f"{item['slo_attainment_pct']}% ({item['goodput_req_s']} req/s)",
]
for item in routing_eval["policies"]
],
},
{
"id": "table_cuda_graph_bucketing",
"title": "Exp 5 (#35): CUDA Graph Capture & Piecewise Bucketing Trade-offs",
"columns": ["capture_mode", "launch_and_pad_waste", "graph_vram", "step_ms_and_tok_s"],
"rows": [
[
item["mode"],
(
f"{item['cpu_launch_overhead_ms']} ms | "
f"batch_pad={item['batch_compute_pad_waste_pct']}% | "
f"seq_pad={item['kv_seq_pad_waste_pct']}%"
),
f"{item['graph_pool_vram_gib']} GiB (ok={item['within_3_5gib_vram_budget']})",
f"{item['avg_step_ms']} ms | {item['effective_decode_tokens_per_sec']} tok/s",
]
for item in cg_eval["strategies"]
],
},
],
}
return {
"unit_id": "T2-P4-U04",
"lab_id": "lab-18-trace-to-kernel-profiling-and-cuda-graphs",
"seed": seed,
"multi_gpu_layout_eval": layout_eval,
"context_parallel_long_prefill": cp_eval,
"moe_ep_serving_eval": moe_eval,
"moe_zipf_skew_sweep": moe_skew_sweep,
"cache_aware_routing_eval": routing_eval,
"trace_profiling_eval": prof_eval,
"cuda_graph_bucketing_eval": cg_eval,
"config_security_audit": config_audit,
"telemetry": telemetry_summary,
"workbench_panels": workbench_panels,
}
def main() -> None:
parser = argparse.ArgumentParser(description="Run Lab 18 Multi-GPU, Routing & Profiling Benchmarks")
parser.add_argument("--seed", type=int, default=42)
parser.add_argument(
"--output",
type=Path,
default=LAB_ROOT / "artifacts" / "t2_ch23_lab18_results.json",
)
args = parser.parse_args()
results = run_full_benchmark_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")
print(f"Wrote {args.output} cleanly.")
if __name__ == "__main__":
main()
"""Automated verification suite (28 tests, 0 skips) for Lab 18 Multi-GPU, Routing & Profiling."""
from __future__ import annotations
import ast
import io
import json
import shutil
import tokenize
from pathlib import Path
import pytest
import torch
from hypothesis import given, settings
from hypothesis import strategies as st
from multi_gpu_profiling_cudagraph_lab.multi_gpu_moe_and_routing import (
evaluate_context_parallel_long_prefill,
evaluate_multi_gpu_layouts,
simulate_cache_aware_routing,
simulate_moe_ep_serving,
sweep_moe_zipf_skew,
)
from multi_gpu_profiling_cudagraph_lab.trace_profiling_and_cudagraphs import (
BoundedInMemorySpanExporter,
audit_lab18_configs,
classify_waterfall_bottleneck,
create_in_memory_telemetry,
run_pytorch_cpu_op_profiling,
run_request_to_kernel_profiling,
simulate_cuda_graph_bucketing,
summarize_finished_spans,
)
from multi_gpu_profiling_cudagraph_lab.trace_profiling_and_cudagraphs import (
main as cli_main,
)
from scripts.run_lab_demo import run_full_benchmark_suite
LAB_ROOT = Path(__file__).resolve().parents[1]
def _copy_configs_to_tmp(tmp_path: Path) -> Path:
shutil.copytree(LAB_ROOT / "configs", tmp_path / "configs")
return tmp_path
def test_01_ast_safety_no_pickle_eval_exec_or_type_ignore() -> 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) >= 4
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:
assert alias.name.split(".")[0] not in forbidden_modules
elif isinstance(node, ast.ImportFrom) and node.module:
assert node.module.split(".")[0] not in forbidden_modules
elif isinstance(node, ast.Call) and isinstance(node.func, ast.Name):
assert node.func.id not in forbidden_calls
for ext in ("*.png", "*.parquet", "*.duckdb*"):
assert not list(LAB_ROOT.rglob(ext))
def test_02_multi_gpu_layouts_tp2_dp4_beats_tp8_on_throughput_and_cost() -> None:
res = evaluate_multi_gpu_layouts()
by_name = {item["layout_name"]: item for item in res["layouts"]}
assert set(by_name) == {
"TP8_NVLink",
"TP8_PCIe_Mismatch",
"PP8_NVLink",
"TP4_PP2_NVLink",
"TP2_DP4_NVLink_FP8",
}
tp8_nv = by_name["TP8_NVLink"]
tp2_dp4 = by_name["TP2_DP4_NVLink_FP8"]
assert tp8_nv["slo_met"] is True
assert tp2_dp4["slo_met"] is True
assert tp2_dp4["cluster_tokens_per_sec"] > tp8_nv["cluster_tokens_per_sec"]
assert tp2_dp4["cost_per_1m_tokens_usd"] < tp8_nv["cost_per_1m_tokens_usd"]
assert res["tp2_dp4_throughput_gain_vs_tp8_x"] > 1.2
def test_03_multi_gpu_pcie_mismatch_and_pp8_fail_tpot_slo() -> None:
res = evaluate_multi_gpu_layouts()
by_name = {item["layout_name"]: item for item in res["layouts"]}
pcie = by_name["TP8_PCIe_Mismatch"]
pp8 = by_name["PP8_NVLink"]
assert pcie["slo_met"] is False
assert pcie["tpot_ms"] > 25.0
assert pcie["comm_overhead_pct"] > 70.0
assert res["pcie_mismatch_tpot_slowdown_vs_nvlink_x"] >= 4.0
assert pp8["slo_met"] is False
assert pp8["pp_bubble_pct"] > 25.0
def test_04_context_parallel_long_prefill_reduces_activation_memory() -> None:
cp = evaluate_context_parallel_long_prefill(seq_len=131_072)
assert (
cp["cp4_tp2_ring"]["activation_peak_gb_per_gpu"]
< cp["tp8_prefill"]["activation_peak_gb_per_gpu"]
)
assert cp["cp4_tp2_ring"]["ttft_ms"] < cp["tp8_prefill"]["ttft_ms"]
assert cp["activation_mem_reduction_x"] >= 1.4
@given(batch=st.integers(min_value=8, max_value=64))
@settings(max_examples=12, deadline=None)
def test_05_hypothesis_multi_gpu_gpu_count_conservation(batch: int) -> None:
res = evaluate_multi_gpu_layouts(batch_per_replica=batch)
for item in res["layouts"]:
assert item["tp"] * item["pp"] * item["dp"] * item["cp"] == 8
assert item["cluster_tokens_per_sec"] > 0.0
assert item["cost_per_1m_tokens_usd"] > 0.0
def test_06_moe_ep_wide_ep32_and_redundant_hot_experts() -> None:
res = simulate_moe_ep_serving(seed=42, zipf_s=1.15)
by_name = {item["strategy_name"]: item for item in res["strategies"]}
tp8 = by_name["TP8_DenseStyle"]
skewed = by_name["DP8_EP8_Skewed"]
balanced = by_name["DP8_EP8_RedundantHotExperts"]
wide = by_name["WideEP32_Pipelined"]
assert skewed["skew_straggler_ratio"] > 3.0
assert balanced["skew_straggler_ratio"] < 1.3
assert res["hot_expert_skew_reduction_x"] >= 3.0
assert balanced["per_gpu_tokens_per_sec"] > skewed["per_gpu_tokens_per_sec"]
assert wide["per_gpu_tokens_per_sec"] > tp8["per_gpu_tokens_per_sec"] * 2.5
assert wide["kv_capacity_multiplier_vs_tp8"] == 32.0
def test_07_moe_zipf_sweep_shows_monotone_skew_protection() -> None:
rows = sweep_moe_zipf_skew(seed=42)
assert len(rows) == 4
for row in rows:
if row["zipf_s"] >= 0.7:
assert row["eplb_straggler_ratio"] < row["unmitigated_straggler_ratio"]
assert row["eplb_tok_s"] > row["unmitigated_tok_s"]
def test_08_cache_aware_routing_beats_rr_and_prevents_hotspot() -> None:
res = simulate_cache_aware_routing(seed=42, load_bound_factor=1.25)
by_pol = {p["policy"]: p for p in res["policies"]}
rr = by_pol["round_robin"]
ll = by_pol["least_loaded"]
unb = by_pol["prefix_aware_unbounded"]
bnd = by_pol["cache_aware_load_bounded"]
# Bounded beats RR & Least-Loaded on KV cache hit rate
assert bnd["global_kv_hit_rate_pct"] > rr["global_kv_hit_rate_pct"] + 15.0
assert bnd["global_kv_hit_rate_pct"] > ll["global_kv_hit_rate_pct"] + 15.0
# Unbounded creates catastrophic hot-spot replica overload
assert unb["max_replica_load_ratio"] > 3.0
assert unb["p99_ttft_ms"] > 1500.0
assert unb["slo_attainment_pct"] < 70.0
# Load-bounded eliminates hot-spot while preserving 100% SLO
assert bnd["max_replica_load_ratio"] < 1.6
assert bnd["p99_ttft_ms"] < 400.0
assert bnd["slo_attainment_pct"] == 100.0
assert res["bounded_vs_unbounded_p99_ttft_speedup_x"] >= 5.0
@given(bound=st.floats(min_value=1.10, max_value=1.50))
@settings(max_examples=8, deadline=None)
def test_09_hypothesis_cache_aware_load_bound_stability(bound: float) -> None:
res = simulate_cache_aware_routing(seed=42, load_bound_factor=bound)
bnd = next(p for p in res["policies"] if p["policy"] == "cache_aware_load_bounded")
assert sum(bnd["replica_request_counts"]) == 240
assert bnd["slo_attainment_pct"] >= 95.0
def test_10_pytorch_cpu_op_profiler_real_tensors_and_aten_reduction() -> None:
prof = run_pytorch_cpu_op_profiling(seed=42)
diff_t = torch.tensor([prof["max_abs_diff_vs_fragmented"]])
assert bool(torch.isfinite(diff_t).all().item())
assert prof["max_abs_diff_vs_fragmented"] < 1e-4
assert prof["fragmented_cpu_aten_ops_3iters"] > prof["fused_cpu_aten_ops_3iters"]
assert prof["aten_op_count_reduction_x"] >= 3.0
assert len(prof["top_fused_aten_ops"]) == 4
def test_11_request_to_kernel_waterfall_classifier_all_four_regimes() -> None:
res = run_request_to_kernel_profiling(seed=42)
wf = res["waterfall_profiles"]
assert wf["cpu_launch_bound"]["predicted_regime"] == "cpu_launch_bound"
assert wf["cpu_launch_bound"]["gpu_bubble_pct"] > 50.0
assert wf["hbm_bandwidth_bound"]["predicted_regime"] == "hbm_bandwidth_bound"
assert wf["nccl_comm_bound"]["predicted_regime"] == "nccl_comm_bound"
assert wf["balanced_optimized_step"]["predicted_regime"] == "balanced_optimized_step"
assert wf["balanced_optimized_step"]["gpu_bubble_pct"] < 20.0
assert res["local_otel_summary"]["span_count"] == 32 # 4 profiles * (1 parent + 7 stages)
def test_12_waterfall_classifier_edge_cases() -> None:
c = classify_waterfall_bottleneck(
{"cuda_launch_cpu": 9.0, "scheduler_queue": 1.0, "gpu_compute_kernel": 2.0}
)
assert c["predicted_regime"] == "cpu_launch_bound"
assert c["dominant_stage"] == "cuda_launch_cpu"
def test_13_cuda_graph_bucketing_piecewise_wins_and_monolithic_exceeds_budget() -> None:
cg = simulate_cuda_graph_bucketing(seed=42, num_steps=120)
by_mode = {item["mode"]: item for item in cg["strategies"]}
eager = by_mode["eager_no_graphs"]
mono = by_mode["monolithic_2d_capture"]
p2 = by_mode["power2_coarse_buckets"]
pw = by_mode["piecewise_hybrid_buckets"]
assert eager["cpu_launch_overhead_ms"] > 4.5
assert mono["within_3_5gib_vram_budget"] is False
assert mono["graph_pool_vram_gib"] > 3.5
assert pw["within_3_5gib_vram_budget"] is True
assert pw["kv_seq_pad_waste_pct"] == 0.0
assert pw["batch_compute_pad_waste_pct"] < p2["batch_compute_pad_waste_pct"]
assert pw["effective_decode_tokens_per_sec"] > eager["effective_decode_tokens_per_sec"] * 2.0
assert cg["cpu_launch_reduction_vs_eager_x"] >= 10.0
@given(steps=st.integers(min_value=40, max_value=140))
@settings(max_examples=8, deadline=None)
def test_14_hypothesis_cuda_graph_piecewise_always_beats_eager(steps: int) -> None:
cg = simulate_cuda_graph_bucketing(seed=42, num_steps=steps)
by_mode = {item["mode"]: item for item in cg["strategies"]}
assert (
by_mode["piecewise_hybrid_buckets"]["effective_decode_tokens_per_sec"]
> by_mode["eager_no_graphs"]["effective_decode_tokens_per_sec"]
)
def test_15_static_yaml_config_audit_passes_clean_configs() -> None:
audit = audit_lab18_configs(LAB_ROOT)
assert audit["all_passed"] is True
assert audit["violations"] == []
assert audit["scanned_files_count"] == 2
assert audit["plaintext_secrets_count"] == 0
assert audit["latest_tags_count"] == 0
assert audit["pinned_images_count"] == 3
def test_16_tamper_detection_plaintext_secret_in_yaml(tmp_path: Path) -> None:
root = _copy_configs_to_tmp(tmp_path)
cfg = root / "configs" / "moe_wide_ep_vllm_config.yaml"
cfg.write_text(
cfg.read_text(encoding="utf-8") + "\n hf_token: hf_secret1234567890abcdef\n",
encoding="utf-8",
)
audit = audit_lab18_configs(root)
assert audit["all_passed"] is False
assert audit["plaintext_secrets_count"] >= 1
def test_17_tamper_detection_latest_tag_and_0_0_0_0_bind(tmp_path: Path) -> None:
root = _copy_configs_to_tmp(tmp_path)
cfg = root / "configs" / "moe_wide_ep_vllm_config.yaml"
txt = cfg.read_text(encoding="utf-8")
txt = txt.replace("vllm/vllm-openai:v0.8.5", "vllm/vllm-openai:latest")
txt = txt.replace("bind_host: 127.0.0.1", "bind_host: 0.0.0.0")
cfg.write_text(txt, encoding="utf-8")
audit = audit_lab18_configs(root)
assert audit["all_passed"] is False
assert audit["latest_tags_count"] >= 1
def test_18_tamper_detection_unbounded_router_and_non_piecewise_cg(tmp_path: Path) -> None:
root = _copy_configs_to_tmp(tmp_path)
cfg = root / "configs" / "cuda_graph_and_router_config.yaml"
txt = cfg.read_text(encoding="utf-8")
txt = txt.replace("policy: cache_aware_load_bounded", "policy: prefix_aware_unbounded")
txt = txt.replace("mode: piecewise_hybrid_buckets", "mode: eager_no_graphs")
cfg.write_text(txt, encoding="utf-8")
audit = audit_lab18_configs(root)
assert audit["all_passed"] is False
assert len(audit["violations"]) >= 2
def test_19_otel_bounded_exporter_ring_buffer_and_leak_detection() -> None:
tracer, exporter = create_in_memory_telemetry("lab18-test", maxlen=8)
assert isinstance(exporter, BoundedInMemorySpanExporter)
for i in range(12):
with tracer.start_as_current_span(f"op.{i}") as sp:
sp.set_attribute("step", i)
summary = summarize_finished_spans(exporter)
assert summary["span_count"] == 8 # ring buffer bounded to 8
assert summary["clean_attributes"] is True
with tracer.start_as_current_span("bad.op") as sp:
sp.set_attribute("token", "sk-1234567890abcdefghijklmnop")
bad_summary = summarize_finished_spans(exporter)
assert bad_summary["clean_attributes"] is False
def test_20_cli_main_runs_cleanly(capsys: pytest.CaptureFixture[str]) -> None:
cli_main([])
captured = capsys.readouterr()
parsed = json.loads(captured.out)
assert parsed["config_audit"]["all_passed"] is True
assert parsed["otel_spans"] == 32
def test_21_full_benchmark_suite_determinism_seed_42() -> None:
r1 = run_full_benchmark_suite(seed=42)
r2 = run_full_benchmark_suite(seed=42)
assert r1 == r2
def test_22_full_suite_telemetry_span_count_and_cleanliness() -> None:
res = run_full_benchmark_suite(seed=42)
tel = res["telemetry"]
# 1 root + 6 experiment spans + 4*(1 parent + 7 stage child spans) = 39 spans
assert tel["span_count"] == 39
assert tel["clean_attributes"] is True
def test_23_workbench_panels_schema_and_counts() -> None:
res = run_full_benchmark_suite(seed=42)
wb = res["workbench_panels"]
assert len(wb["kpis"]) == 6
assert len(wb["bars"]) == 4
assert len(wb["tables"]) == 4
for kpi in wb["kpis"]:
assert {"id", "label", "value", "unit", "status", "detail"} <= set(kpi)
for bar in wb["bars"]:
assert {"id", "title", "metric_label", "items"} <= set(bar)
assert len(bar["items"]) >= 2
for tbl in wb["tables"]:
assert {"id", "title", "columns", "rows"} <= set(tbl)
assert len(tbl["rows"]) >= 3
def test_24_committed_artifact_matches_fresh_run() -> None:
art_path = LAB_ROOT / "artifacts" / "t2_ch23_lab18_results.json"
assert art_path.is_file()
committed = json.loads(art_path.read_text(encoding="utf-8"))
fresh = run_full_benchmark_suite(seed=42)
assert committed == fresh
def test_25_pyproject_contains_expected_dependencies_and_indices() -> None:
pyproject_txt = (LAB_ROOT / "pyproject.toml").read_text(encoding="utf-8")
for dep in ("numpy", "opentelemetry-sdk", "pydantic", "pyyaml", "torch", "pytorch-cpu"):
assert dep in pyproject_txt
def test_26_configs_pin_valid_endpoints_and_no_secrets() -> None:
moe_cfg = (LAB_ROOT / "configs" / "moe_wide_ep_vllm_config.yaml").read_text(encoding="utf-8")
cg_cfg = (LAB_ROOT / "configs" / "cuda_graph_and_router_config.yaml").read_text(encoding="utf-8")
assert "127.0.0.1" in moe_cfg
assert "127.0.0.1" in cg_cfg
assert "vault-hf-credentials" in moe_cfg
def test_27_pp_stage_decode_allreduce_scaling_consistency() -> None:
res = evaluate_multi_gpu_layouts(batch_per_replica=32)
by_name = {item["layout_name"]: item for item in res["layouts"]}
tp4_pp2 = by_name["TP4_PP2_NVLink"]
pp8 = by_name["PP8_NVLink"]
# TP4_PP2 runs only num_layers / pp = 40 TP All-Reduces per stage -> sub-10ms TPOT.
assert tp4_pp2["slo_met"] is True
assert tp4_pp2["tpot_ms"] < 9.5
# PP8 has tp=1 -> zero TP All-Reduce overhead; all comm% comes from P2P stage handoffs.
assert pp8["comm_overhead_pct"] > 50.0
def test_28_eplb_unclamped_genuine_skew_reduction_across_seeds() -> None:
observed_balanced: set[float] = set()
observed_wide: set[float] = set()
for seed in (7, 13, 42, 99):
res = simulate_moe_ep_serving(seed=seed, zipf_s=1.15)
by_name = {item["strategy_name"]: item for item in res["strategies"]}
skewed = by_name["DP8_EP8_Skewed"]
balanced = by_name["DP8_EP8_RedundantHotExperts"]
wide = by_name["WideEP32_Pipelined"]
assert skewed["skew_straggler_ratio"] > 5.0
assert balanced["skew_straggler_ratio"] < 1.25
assert wide["skew_straggler_ratio"] < 1.25
# Verify genuine statistical variation (never silence-clamped to 1.18 or 1.15).
assert balanced["skew_straggler_ratio"] != 1.18
assert wide["skew_straggler_ratio"] != 1.15
observed_balanced.add(balanced["skew_straggler_ratio"])
observed_wide.add(wide["skew_straggler_ratio"])
assert len(observed_wide) >= 2
assert len(observed_balanced) >= 1
8x H100 phục vụ mô hình 70B FP8 (SLO TTFT <= 500 ms, TPOT <= 25 ms) trong Lab 18 (Tests 02–03), vì sao TP8 qua PCIe và PP8 trên NVLink đều vỡ SLO trong khi TP2+DP4 lại đạt hiệu quả cao nhất?Tests 02–03: TP8 đòi hỏi 160 lần All-Reduce mỗi token; khi rơi xuống PCIe (64 GB/s), giao tiếp chiếm 84.81% đẩy TPOT lên 28.91 ms (5.03x chậm hơn 5.75 ms trên NVLink). PP8 chịu 30.43% bong bóng đường ống và truyền tuần tự 8 giai đoạn (27.92 ms TPOT). TP2+DP4 trên NVLink giữ TPOT = 16.36 ms <= 25 ms, nâng thông lượng cụm lên 7,790.5 tok/s (1.41x vs TP8 NVLink) và hạ chi phí xuống $0.8557/1M.
131,072 token (128k) trong Lab 18 (Test 04), kết hợp CP4 + TP2 Ring Attention mang lại lợi ích nào so với dùng TP8 đơn thuần?Test 04: CP4+TP2 chia chuỗi 131,072 token dọc theo chiều độ dài chuỗi (seq_len) và gối đầu truyền các khối KV theo vòng (88.5% overlap), giúp giảm 1.44x bộ nhớ kích hoạt đỉnh (14.0 -> 9.7 GiB/GPU), giảm một nửa số rào All-Reduce (160 -> 80), và hạ TTFT từ 1,516.01 ms xuống 1,389.15 ms mà không bị giới hạn bởi số đầu KV ít của GQA-8.
Sparse MoE (256 chuyên gia, Top-K=8, FP8) của Lab 18 (Tests 06, 28), vì sao Wide-EP32 (DP32+EP32) lại vượt trội TP8_DenseStyle tới 3.10x thông lượng mỗi GPU?Tests 06, 28: TP8_DenseStyle cắt nhỏ từng chuyên gia vốn đã thưa (m_e = 4.0 token/chuyên gia) và nhân bản KV-Cache trên 8 GPU (725.5 tok/s/GPU). Wide-EP32 chạy Attention theo DP=32 (32x sức chứa KV-Cache) và gom lô toàn cụm qua EP=32 (m_e = 32.0 token bão hòa Tensor Core, 64 khe nóng) kết hợp gối đầu DeepEP/DualPipe All-to-All (1.04 ms lộ ra, 1.09x skew), đạt 2,246.8 tok/s/GPU (71,898.3 tok/s cụm, 14.24 ms/step, 3.10x mỗi GPU).
MoE bị lệch theo luật Zipf (s = 1.15) trên DP8+EP8 (Tests 06–07, 28), chuyện gì xảy ra nếu không nhân bản chuyên gia nóng và EPLB + LPT + Power-of-Choice khắc phục thế nào?Tests 06–07, 28: Dưới lệch tải Zipfian (s=1.15), DP8+EP8 không nhân bản tạo ra straggler gấp 6.09x mức trung bình (7.28x ở s=1.5), buộc 7 GPU còn lại chờ ở rào All-to-All Combine (43.55 ms/step, 734.8 tok/s/GPU). Bổ sung 48 khe bản sao nóng bằng bộ lập lịch thực nghiệm EPLB tham lam, đóng gói LPT và điều phối kép Power-of-Choice khóa chặt tỷ số straggler ở 1.05x (5.80x cân bằng hơn), cắt bước xuống 16.7 ms và đạt 1,916.3 tok/s/GPU (15,330.2 tok/s cụm).
8 bản sao nhận tải lệch Zipfian (46% chung tiền tố nóng, TTFT SLO <= 550 ms) của Lab 18 (Test 08), kết quả so sánh Prefix-Aware Unbounded và Cache-Aware Load-Bounded chỉ ra bài học gì?Test 08: Round-Robin phá vỡ tính cục bộ cache (50.83% hit, p99 TTFT = 831.83 ms, vỡ SLO). Prefix-Aware Unbounded đạt 97.5% hit nhưng dồn 118/240 yêu cầu vào duy nhất Replica 1 (max_load = 3.77x), khiến p99 TTFT nổ lên 2,261.66 ms (58.33% SLO). Cache-Aware Load-Bounded (c_bound = 1.25) giữ 74.17% hit (+23.34 pp vs RR) bằng cách tràn có kiểm soát sang bản sao phụ, khóa tải ở 1.41x, hạ p99 TTFT 8.21x xuống 275.49 ms và đạt 100.0% SLO.
Lab 18 (Tests 10–11), tổ hợp PyTorch CPU Profiler và thác OpenTelemetry giúp phân biệt chế độ cpu_launch_bound với hai chế độ nghẽn phần cứng còn lại như thế nào?Tests 10–11: Chạy torch.profiler.profile thực tế trên PyTorch CPU chứng minh hợp nhất tác vụ giảm 3.76x lệnh ATen (1,668 -> 444, sai khác 2.6e-06). Trên thác OTel 6 tầng (39 spans sạch không lộ prompt), cpu_launch_bound bộc lộ 63.78% GPU idle bubble do CPU phóng lệnh chậm, tách biệt hoàn toàn với hbm_bandwidth_bound (75.26% đọc HBM/KV) và nccl_comm_bound (69.58% giao tiếp All-Reduce).
CUDA Graphs trên 120 bước batch & chiều dài chuỗi biến thiên của Lab 18 (Test 13), vì sao chụp Monolithic 2D thất bại và Piecewise CUDA Graphs (vLLM v1) giải quyết ra sao?Test 13: Eager đốt 5.18 ms/step cho chi phí CPU launch (2,698.5 tok/s). Monolithic 2D chụp 24 đồ thị đầy đủ theo lưới (batch, seq) làm bể đồ thị phình lên 8.64 GiB (vượt ngân sách 3.5 GiB) và vẫn phải đệm 26.08% batch + 26.78% seq. Piecewise CUDA Graphs chỉ chụp các đoạn tuyến tính vào đồ thị và cho phép varlen PagedAttention chạy Eager bên ngoài, giữ 0.0% đệm chiều dài KV và cắt launch xuống 0.38 ms (13.63x).
Lab 18 (Tests 13, 15–22), việc nâng cấp từ xô lũy thừa 2 sang xô hỗn hợp [1,2,4,8,16,24,32,48,64,96,128] cùng kiểm toán YAML/OTel mang lại kết quả định lượng nào?Tests 13, 15–22: Thêm các mức trung gian 24, 48, 96 trong piecewise_hybrid_buckets giảm 1.67x lãng phí padding batch so với Power-of-2 (11.05% vs 18.48%), giữ VRAM bể đồ thị ở 1.76 GiB <= 3.5 GiB, cắt launch overhead 13.63x (5.18 -> 0.38 ms) và đạt 7,450.3 tok/s (2.76x nhanh hơn Eager). Đồng thời kiểm toán quét sạch 2/2 YAML (0 bí mật, 0 :latest, 3 image ghim, 127.0.0.1) và 39 span OTel sạch.
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 — Phân tích Bố cục Đa GPU TP/PP/DP/CP và Bẫy PCIe 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Kiểm tra công thức _hockney_allreduce_ms trong evaluate_multi_gpu_layouts khi chuyển băng thông hiệu dụng từ 900 GB/s (NVLink) xuống PCIe và tác động của pp_bubble_frac lên PP8_NVLink.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy pytest -k "test_02 or test_03 or test_04 or test_05" -v và đối chiếu multi_gpu_layout_eval với context_parallel_long_prefill trong artifacts/t2_ch23_lab18_results.json.
Tiêu chí Đáp án & Số đối chứng
TP8 PCIe chịu 84.81% giao tiếp kéo TPOT lên 28.91 ms (5.03x chậm hơn 5.75 ms NVLink, vỡ SLO); PP8 chịu 30.43% bong bóng (27.92 ms TPOT, vỡ SLO). TP2+DP4 NVLink FP8 đạt 7,790.5 tok/s (1.41x vs TP8), 16.36 ms TPOT, $0.8557/1M. Trên prefill 128k, CP4+TP2 Ring giảm 1.44x RAM kích hoạt (14.0 -> 9.7 GiB/GPU).
Bài tập 2 — Phục vụ MoE Wide-EP và Chống Lệch Tải Zipfian (EPLB + LPT) 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Theo dõi bộ mô phỏng MoE khi redundant_hot_experts = 0 vs 48 (lập lịch thực nghiệm EPLB + đóng gói LPT + chọn kép Power-of-Choice) và hiệu ứng gối đầu DeepEP/DualPipe All-to-All ở WideEP32_Pipelined.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy pytest -k "test_06 or test_07 or test_28" -v và kiểm tra moe_ep_serving_eval cùng moe_zipf_skew_sweep.
Tiêu chí Đáp án & Số đối chứng
TP8_DenseStyle chỉ đạt m_e = 4.0 và 725.5 tok/s/GPU (1x KV). Dưới lệch tải Zipf s=1.15, DP8+EP8 thuần bị straggler 6.09x (43.55 ms/step, 734.8 tok/s/GPU); thêm 48 khe chuyên gia nóng qua EPLB + LPT + Power-of-Choice kéo skew xuống 1.05x (5.80x cân bằng hơn, 16.7 ms, 1,916.3 tok/s/GPU, 15,330.2 cụm). Wide-EP32 (DeepEP/DualPipe, 64 khe nóng) giữ 1.09x skew (14.24 ms), đạt 2,246.8 tok/s/GPU (71,898.3 cụm, 3.10x vs TP8, 32x KV).
Bài tập 3 — Định tuyến Nhận thức KV-Cache Có Giới hạn Tải Trên 8 Bản sao 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Quan sát lớp _ReplicaState (LRU 192 khối) và nhánh tràn wait_ms > 90.0 / inflights > bound_cap trong _run_routing_policy.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy pytest -k "test_08 or test_09" -v và đối chiếu cache_aware_routing_eval trên cả 4 chính sách định tuyến.
Tiêu chí Đáp án & Số đối chứng
Round-Robin chỉ trúng 50.83% (p99 TTFT = 831.83 ms, 92.08% SLO). Prefix-Aware Unbounded trúng 97.5% nhưng dồn 118/240 yêu cầu vào Replica 1 (max_load = 3.77x), làm p99 TTFT = 2,261.66 ms (58.33% SLO). Cache-Aware Load-Bounded (1.25x) giữ 74.17% hit (+23.34 pp), khóa tải 1.41x, hạ p99 TTFT 8.21x xuống 275.49 ms (100.0% SLO).
Bài tập 4 — Phân tích Hồ sơ PyTorch CPU Profiler và Thác OpenTelemetry 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Đối chiếu forward_fragmented vs forward_fused dưới torch.profiler.profile trong run_pytorch_cpu_op_profiling và ngưỡng phân loại của classify_waterfall_bottleneck.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy pytest -k "test_10 or test_11 or test_12" -v và kiểm tra trace_profiling_eval trong file JSON.
Tiêu chí Đáp án & Số đối chứng
Hợp nhất phép tính PyTorch cắt 3.76x lệnh ATen (1,668 -> 444 trong 3 vòng lặp, sai khác tối đa 2.6e-06). Thác OTel (39 spans sạch) phân loại chuẩn xác 4 chế độ: cpu_launch_bound (63.78% GPU bubble), hbm_bandwidth_bound (75.26% HBM read), nccl_comm_bound (69.58% NCCL), và balanced_optimized_step (13.35% bubble, 41.26% compute).
Bài tập 5 — CUDA Graphs Cho Hình dạng Biến thiên và Piecewise Hybrid Buckets 20%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Xem cách simulate_cuda_graph_bucketing tính padding theo (batch, seq) cho monolithic_2d_capture vs chỉ padding batch với varlen Attention ngoài đồ thị cho piecewise_hybrid_buckets.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy pytest -k "test_13 or test_14" -v và đọc cuda_graph_bucketing_eval trong artifacts/t2_ch23_lab18_results.json.
Tiêu chí Đáp án & Số đối chứng
Eager tốn 5.18 ms/step launch overhead (2,698.5 tok/s). Monolithic 2D cần 24 đồ thị ngốn 8.64 GiB VRAM (vượt trần 3.5 GiB) và đệm 26.08% batch + 26.78% seq. Piecewise Hybrid ([1,2,4,8,16,24,32,48,64,96,128]) hạ launch xuống 0.38 ms (13.63x), giữ 0.0% seq pad, cắt batch pad 1.67x vs Power-of-2 (11.05% vs 18.48%) trong 1.76 GiB, đạt 7,450.3 tok/s (2.76x).
Bài tập 6 — Kiểm toán Cấu hình YAML, Truy vết Bounded OTel và Tính Xác định 20%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Kiểm tra các quy tắc trong audit_lab18_configs (cấm hf_/sk-, :latest, 0.0.0.0, bắt buộc Wide-EP + EPLB, cache_aware_load_bounded, piecewise_hybrid_buckets, redact_prompt_text) và BoundedInMemorySpanExporter.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy run_lab_demo.py, ruff check src scripts tests, mypy src tests, pytest -p no:cacheprovider -v, và uv lock --check.
Tiêu chí Đáp án & Số đối chứng
Kiểm toán quét sạch 2/2 YAML (0 bí mật tĩnh, 0 :latest, 3 image ghim, 127.0.0.1) và bắt trọn cấu hình giả mạo qua tmp_path; BoundedInMemorySpanExporter ghi nhận 39 span OpenTelemetry sạch (clean_attributes=True); 28/28 pytest pass (0 skip, 0 # type: ignore), ruff và mypy strict 0 lỗi, uv.lock xác thực sạch.