Chương 26 — Kiến trúc Phần cứng GPU, Phân cấp Bộ nhớ CUDA & Mô hình Roofline
Từ truy cập HBM phân mảnh 32x (128B cache line, hiệu suất 3.12% vs coalesced 100%) & xung đột 32-way SRAM bank ([32][32] vs [32][33] 1-way) đến Occupancy (6.25% -> 100.0%), Tensor Cores (WMMA -> WGMMA+TMA -> tcgen05+NVFP4), điểm uốn Roofline H100 BF16 (I=295.22, B=310), CUDA Graphs (4.10x decode speedup) & kiểm chứng thực nghiệm trên PyTorch 2.15+cpu (1.90x transpose penalty, 20.15x GEMM scaling).
Đơn vị học phần (
Unit ID):T1-P6-U01(Phần 6: Kiến trúc Phần cứng GPU, Lập trình NhânCUDA&Triton— Mục lục Phần 6)
Phòng thí nghiệm Thực hành (Workbench): WB-Ch26 — Xưởng Kiến trúc Phần cứng GPU, Bộ nhớ CUDA & Mô hình Roofline (gpu_cuda_roofline_lab)
Truy xuất nguồn & kế thừa: Chương 14 — Mạng Nơ-ron & Nội tại PyTorch, Chương 19 — Cơ chế Attention, Kiến trúc Transformer & Giải phẫu LLM Hiện đại, Chương 25 — Đánh giá Hệ thống LLM, RAG & Agent Theo Chế độ Lỗi, Chương trình gốc DSAI (R54), và Đề cương SOTA 2026 (Chương 26). Chương kế tiếp làChương 27(Lập trình Nhân Triton Từ Gốc) và liên thông trực tiếp lênTrack 2 Phần 4(35 Bài viết Chuyên sâu#18–#35).
Bốn Thảm họa Hiệu năng GPU Mở màn: Vì sao Viết Đúng Công thức Vẫn Chậm 10x–32x#
Nhiều kỹ sư AI khi chuyển từ code PyTorch mức cao sang viết nhân GPU tùy biến thường tin rằng chỉ cần "song song hóa lên hàng chục nghìn luồng CUDA" là sẽ đạt gần đỉnh 989 TFLOPS của H100. Thực tế sản xuất hoàn toàn ngược lại: nếu bỏ qua vật lý bộ nhớ và bộ lập lịch phần cứng, nhân CUDA viết đúng toán học vẫn dễ dàng mất 75%–97% thông lượng! Bốn ca thất bại định lượng dưới đây — được kiểm chứng trong WB-Ch26 (gpu_cuda_roofline_lab, seed = 42) qua mô hình giải tích phần cứng chuẩn xác kết hợp kiểm toán nhân CUDA C++ (01_memory_and_gemm_kernels.cu) và đo đạc thực nghiệm trên PyTorch 2.15.0+cpu — phơi bày bốn cái bẫy cốt lõi:
-
Ca 1 — Truy cập Bộ nhớ Toàn cục Rải bước (
AoS/stride=32) Khuếch đại Giao dịch32x(WB-Ch26,Tests 04, 12):Một nhân CUDA đọc mảng
float32(4 byte) theo cấu trúc Array-of-Structures (stride = 32) thay vì Structure-of-Arrays liền kề (stride = 1). Dù cả hai nhân yêu cầu đúng128 bytedữ liệu hữu ích cho mộtWarp32luồng, bộ điều khiển L1/HBM phải cấp phát theo dòng cache128 byte(4sector32BL2): nhân rải bước kích hoạt32dòng cache riêng biệt (4,096 bytetải xuống cho128 bytedùng thật) — khuếch đại giao dịch32.0x(8.0xkhuếch đại sector L2), đẩy hiệu suất băng thông hữu ích trênH100 SXM(3,350 GB/s) rơi thẳng xuống3.12%(104.7 GB/smức cache-line /418.8 GB/smức sector)! Trên CPU cục bộ, thí nghiệmPyTorch 2.15.0+cputhật với phép cộng dồnsum(dim=1)trên ma trận2048×2048xác nhận bản chuyển vị không liên tụcstride=[1, 2048]chậm hơn1.90x(1.000 msvs0.526 ms). -
Ca 2 — Xung đột
32Ngân hàng Bộ nhớ Chia sẻ ([32][32]vs[32][33],Tests 05–06):Để tránh đọc rải bước trực tiếp từ HBM, kỹ sư đưa khối
32×32float32vào bộ nhớ chia sẻ siêu nhanh trên chip (Shared Memory/ SRAM) qua khai báo__shared__ float tile[32][32];. Ở pha ghi theo hàng (tile[ty][tx]),32luồng trúng32ngân hàng SRAM khác nhau (1-way, không xung đột). Nhưng ở pha đọc theo cột để chuyển vị (tile[tx][ty]), khoảng bước theo cột bằng đúng32từ4-byte— nên cả32luồng của Warp đâm sầm vào duy nhất một ngân hàng SRAM ((lane * 32 + col) % 32 == col)! Kết quả là xung đột ngân hàng32-way (tuần tự hóa32chu kỳ liên tiếp, hiệu suất SRAM chỉ còn3.12%). Chỉ một thay đổi nhỏ[32][33](+1cột đệm) làm \(\gcd(33, 32) = 1\), biến pha đọc cột thành1-way (0xung đột,100.0%hiệu suất)! -
Ca 3 — Phân kỳ
Warp, Sụp đổSM Occupancy(6.25%) & Nghịch lý Decode vs Prefill trên Roofline (Tests 07–10, 13):Viết câu lệnh rẽ nhánh
if (threadIdx.x % 2 == 0)buộc mộtWarp32luồng thực thi tuần tự cả hai nhánh theo khóa đồng bộSIMT, cắt đôi hiệu suất xuống50.0%; còn nhánh đuôi lệch pha (threadIdx.x == 31chạy148chu kỳ) kéo hiệu suất SIMT rơi thảm hại xuống10.16%(160chu kỳ). Tệ hơn, nếu lập trình viên cấp phát phung phí128 KBShared Memory cho block128luồng (4warps), mỗiSMtrênH100(228 KBSMEM) chỉ nạp được đúng1block \(\implies\)4/64warps =6.25%SM Occupancy (so với mức tối ưu256luồng,32thanh ghi,16 KBSMEM đạt100.0%,64/64warps), làm bộ lập lịchWarpchết đói không thể che giấu độ trễ HBM~500chu kỳ theo Định luật Little (4 < 32warps cần thiết)! Song song, trên đường cong RooflineH100 SXM(BF16,989 TFLOPS,3,350 GB/s, điểm gãy \(I^* = 295.22\ \text{FLOP/Byte}\)), suy luận LLM Decode (B = 1) có cường độ số học chỉAI = 1.00nên chỉ đạt3.35 TFLOPS(0.34%đỉnh tính toán) — nằm kẹt ở sườn băng thông cho tới tận ngưỡng lôB* ≈ 310token, trong khi Prefill (S = 2048) đạtAI = 1,549.8khai thác trọn989.0 TFLOPS(100%)! -
Ca 4 — Bong bóng Khởi chạy Host CPU (
Launch Overhead) & Lời giảiCUDA Graphs(Test 11):Trong pha Decode
B=1của một LLM32tầng, đường ống giải mã tung ra hàng trăm vi nhân CUDA siêu nhỏ (RMSNorm,RoPE,Residual Add,SwiGLUmỗi nhân chỉ chạy2.0 ustrên GPU). Nhưng mỗi lệnh phóng nhân từ CPU qua driver mất8.0 us(5–15 usthực tế). Trên180vi nhân, GPU chạy xong nhân trước và ngồi không6.0 uschờ CPU gửi nhân kế tiếp: tổng thời gian vọt lên1,442.0 usvới75.03%bong bóng chờ CPU (24.97%hiệu dụng GPU)! Gom trọn180nút thành mộtCUDA Graphphóng1lần (12.0 us) cắt thời gian bước xuống416.8 us(3.46xnhanh hơn,86.38%GPU util), và kết hợp dung hợp nhân (64nút) hạ tiếp còn351.8 us(4.10x).
Mục tiêu Học tập (Learning Objectives)#
Sau khi hoàn tất Chương 26 và vượt qua 18/18 bài kiểm thử của WB-Ch26 (gpu_cuda_roofline_lab), học viên nắm vững 5 năng lực kỹ nghệ phần cứng GPU chuẩn SOTA 2025–2026:
- Giải phẫu Silicon GPU Hiện đại (
Ada\(\to\)Hopper\(\to\)Blackwell): Phân biệt kiến trúc tối ưu độ trễ (CPU) vs tối ưu thông lượng (GPU); giải thích cấu trúcSM,Warp Scheduler, và lộ trình tiến hóaTensor CoretừWMMA\(\to\) HopperWGMMA+TMA+ Clusters \(\to\) Blackwelltcgen05.mma+TMEM+NVFP4/MXFP4. - Làm chủ Bậc thang Bộ nhớ & Tối ưu Truy cập CUDA: Tính chính xác tỷ lệ lãng phí dòng cache
128B/ sector32Bcho truy cập hợp nhất vs rải bước, triệt tiêu xung đột32ngân hàng SRAM bằng quy tắc đồng nguyên \(\gcd(\text{stride}, 32) = 1\), và dùng__shfl_down_syncrút gọn trong thanh ghi. - Phân tích Bộ lập lịch
Warp, Phân kỳSIMT& Vách đáSM Occupancy: Định lượng suy giảm thông lượng do rẽ nhánh lệch pha, tính giới hạn số block đồng thời theo thanh ghi (256-reg/warp) / SMEM / giới hạn phần cứng, và áp dụng Định luật Little che trễ HBM. - Tính toán Chuẩn xác Mô hình Roofline Cho LLM (
PrefillvsDecode): Dẫn xuất cường độ số học (\(\text{FLOP/Byte}\)) cho Elementwise/RMSNorm, Decode GEMV/GEMM, GQA Attention Decode vs Prefill FlashAttention, tìm điểm gãy \(I^*\) và điểm cắt lô \(B^*\). - Điều phối Thực thi Hiện đại & Hồ sơ Hóa (
Profiling): Ứng dụng CUDA Streams, CUDA Graphs (bắc cầu sang Chuyên đề#35), đại số bố cụcCUTLASS 3.x/CuTe, chỉ sốNsight Compute(ncu) (SOL%,Warp Stall), và sẵn sàng viết nhân dung hợp ởChương 27 (Triton).
Truy xuất Nguồn & Ma trận Liên thông (R54 + SOTA 2026)#
Hạng mục Giáo trình (R54 & SOTA 2026) |
Nội dung Chuyên sâu trong Chương 26 | Sơ đồ / Mô phỏng Tương tác | Thực thi trong WB-Ch26 (gpu_cuda_roofline_lab) |
|---|---|---|---|
1. GPU Hardware Foundations |
CPU vs GPU, SM, Warp Scheduler, Tensor Cores (WMMA \(\to\) WGMMA+TMA \(\to\) tcgen05+TMEM+NVFP4) |
Mermaid 1 + tbl_gpu_silicon_specs |
hardware_and_roofline.py: GPU_HARDWARE_SPECS, get_gpu_spec (Test 03) |
| 2. Phân cấp Bộ nhớ & Coalescing/Banks | Thanh ghi, SMEM (32 banks, [32][32] vs [32][33]), L2 (32B sectors), HBM3/HBM3e (128B), __shfl_down_sync |
Widget 2 + Widget 3 (shared-memory-bank-conflict-lab) |
cuda_memory_and_occupancy.py + 01_memory_and_gemm_kernels.cu (Tests 04–08, 12, 14) |
| 3. Mô hình Roofline & LLM Prefill/Decode | Đường bao Compute vs HBM BW, điểm gãy \(I^*\), điểm cắt lô \(B^*\), GQA vs MHA, NVFP4 vs BF16 |
Mermaid 2 + Widget 1 (gpu-roofline-prefill-decode-explorer) |
hardware_and_roofline.py: compute_gemm_roofline, analyze_llm_decode_vs_prefill_roofline, torch.matmul (Tests 09–10, 13, 18) |
4. CUDA Programming Model & SOTA Toolchain |
grid/block/threadIdx, Streams, CUDA Graphs, CuTe/CUTLASS 3.x, Nsight Compute (ncu) & Cầu nối Ch 27 Triton / #18–#35 |
Mermaid 3 + tbl_cuda_graph_and_cpu_validation |
simulate_cuda_graph_launch_overhead, create_in_memory_otel_tracer (Tests 11, 15–17) |
Bảng Ký hiệu Phi Mơ hồ (Disambiguated Notation Contract)#
| Ký hiệu LaTeX | Miền / Đơn vị | Định nghĩa Chuẩn trong Chương 26 | Tên biến trong gpu_cuda_roofline_lab |
|---|---|---|---|
| \(\text{BW}_{\text{peak}}, \Pi_{\text{peak}}\) | \(\text{GB/s}, \text{TFLOPS}\) | Băng thông bộ nhớ đỉnh (HBM3/HBM3e/GDDR6X) và năng lực tính toán đỉnh |
hbm_bandwidth_gb_s, peak_tflops |
| \(I, I^*\) | \(\text{FLOP}/\text{Byte}\) | Cường độ số học \(\text{FLOPs}/\text{Bytes}\) và điểm gãy Roofline \(\Pi_{\text{peak}} / \text{BW}_{\text{peak}}\) | arithmetic_intensity, ridge_point |
| \(\Pi_{\text{att}}(I)\) | \(\text{TFLOPS}\) | Hiệu năng khả đạt trên Roofline: \(\min(\Pi_{\text{peak}}, I \cdot \text{BW}_{\text{peak}})\) | attainable_tflops |
| \(B, B^*\) | \(\text{tokens}\) | Kích thước lô giải mã và ngưỡng lô giao điểm để GEMM chạm \(I^*\) | m_batch, analytical_linear_crossover_batch |
| \(A_{128\text{B}}, \eta_{128\text{B}}\) | \(\ge 1, (0, 1]\) | Hệ số khuếch đại giao dịch dòng cache 128B và hiệu suất dữ liệu hữu ích |
cache_line_amplification, cache_line_efficiency |
| \(K_{\text{bank}}, p\) | \(\mathbb{Z}_{\ge 1}, \mathbb{Z}_{\ge 0}\) | Bội số xung đột ngân hàng SRAM (conflict_ways) và cột đệm [32][32+p] |
conflict_ways, padding |
| \(O_{\text{SM}}, W_{\text{act}}\) | \([0, 100\%], \mathbb{Z}_{\ge 0}\) | Tỷ lệ chiếm dụng Warp hoạt động trên SM và số Warp đồng thời đang nạp | occupancy_pct, active_warps_per_sm |
Trụ cột 1 — Kiến trúc Phần cứng GPU, Phân cấp Bộ nhớ CUDA & Mô hình Toán học Roofline#
1.1 CPU Tối ưu Độ trễ vs. GPU Tối ưu Thông lượng & Giải phẫu SM Hiện đại#
Sự khác biệt căn bản giữa CPU và GPU không nằm ở "số lượng nhân nhiều hơn", mà ở cách chi tiêu ngân sách bóng bán dẫn (transistor budget) trên silicon:
- CPU (Latency-Oriented Architecture): Dành phần lớn diện tích đế silicon cho bộ nhớ đệm
L1/L2/L3khổng lồ (hàng chục MB SRAM), bộ dự đoán rẽ nhánh (branch predictor), thực thi ngoại thứ tự (out-of-order execution) và dự đoán dữ liệu — mục tiêu tối thiểu hóa độ trễ của một luồng đơn lẻ (single-thread latency). - GPU (Throughput-Oriented Architecture): Loại bỏ bộ dự đoán nhánh phức tạp và phần lớn bộ đệm lớn cho từng luồng, dồn diện tích cho hàng nghìn đơn vị số học (
ALU/FP32/Tensor Core) và một tập thanh ghi (Register File) khổng lồ (256 KB = 65,536 thanh ghi 32-bittrên mỗiSM) để lưu trạng thái của hàng chụcWarpcùng lúc. Khi mộtWarpgửi lệnh đọc bộ nhớHBMdài~500chu kỳ, GPU không chờ mà chuyển ngay ngữ cảnh sangWarpkhác trong đúng0chu kỳ phí (zero-overhead context switch) — che giấu độ trễ bộ nhớ bằng song song quy mô lớn!
Một Streaming Multiprocessor (SM) hiện đại (như 132 SMs trên H100 SXM hay 148 SMs trên B200 SXM) bao gồm 4 phân vùng xử lý (processing blocks / sub-partitions), mỗi phân vùng có 1 Bộ lập lịch Warp (Warp Scheduler), 1 đơn vị cấp phát lệnh, 32 nhân FP32 CUDA Cores (128 CUDA Cores/SM), 1 Tensor Core (4 Tensor Cores/SM), nhóm hàm siêu việt SFU (Special Function Units cho exp, tanh, rsqrt), và chia sẻ chung khối L1 / Shared Memory.
Tiến hóa Tensor Cores & Hệ sinh thái Kiến trúc 2022–2026 (Ada \(\to\) Hopper \(\to\) Blackwell \(\to\) Blackwell Ultra)#
| Thế hệ & GPU Tiêu biểu | Kiến trúc Tensor Core & Độ chính xác | Cơ chế Nạp Dữ liệu & Bộ nhớ Đặc thù | Thông số Đỉnh Dense & Điểm gãy \(I^*\) (WB-Ch26, 2:4 Sparse = 2x) |
|---|---|---|---|
Ada Lovelace (RTX 4090) |
4th-Gen WMMA / mma.sync (warp-level, FP32, BF16, FP8 330.3 TF FP32 Acc vs 660.6 TF FP16 Acc) |
cp.async Global \(\to\) SMEM (100 KB SMEM/SM, 48 warps/SM max, 24 GB GDDR6X 1,008 GB/s) |
82.6 TF FP32, 165.2 TF BF16 (\(I^* = 163.9\)), 330.3 TF FP8 FP32-Acc (\(I^* = 327.7\)) / 660.6 TF FP16-Acc |
Hopper (H100 SXM) |
4th-Gen WGMMA (lệnh ma trận bất đồng bộ cấp Warpgroup 4 warp = 128 luồng) |
TMA (Tensor Memory Accelerator sao chép tensor 2D–5D bất đồng bộ vào SMEM không tốn thanh ghi địa chỉ) + Thread Block Clusters (228 KB SMEM, 80 GB HBM3 3,350 GB/s) |
67.0 TF FP32, 989.0 TF BF16 (\(I^* = \mathbf{295.22}\)), 1,979.0 TF FP8 (\(I^* = \mathbf{590.75}\)); 2:4 Sparse = 1,979 / 3,958 TF |
Blackwell (B200 SXM) |
5th-Gen tcgen05.mma (single-thread issue semantics: 1 luồng được bầu phát lệnh khối 1-SM/2-SM, không phải 1 warp!) + NVFP4 (16-elem FP8 E4M3 + FP32 scale) vs OCP MXFP4 (32-elem UE8M0) |
TMEM (Tensor Memory, 256 KB/SM): bộ nhớ tích lũy chuyên dụng tách khỏi tập thanh ghi RF, cộng TMA và 180 GB usable HBM3e (192 GB raw, 8192-bit, 8,000 GB/s) |
~75.0 TF FP32, 2,250 TF BF16 (\(I^* = 281.25\)), 4,500 TF FP8 (\(I^* = 562.5\)), 9,000 TF NVFP4 (\(I^* = \mathbf{1,125.00}\)); 2:4 Sparse = 18,000 TF NVFP4 |
Blackwell Rack & Ultra (GB200 NVL72 / B300–GB300) |
Kiến trúc rack-scale 72 GPUs dùng chung miền tcgen05.mma + NVFP4/MXFP4 (Blackwell Ultra nâng thông lượng NVFP4 thêm ~1.5x) |
GB200 NVL72: 130 TB/s NVLink fabric (1.8 TB/s hai chiều/GPU); Blackwell Ultra (B300/GB300): ~270–288 GB HBM3e (12-Hi) mỗi GPU |
Hợp nhất 72 GPUs thành một miền bộ nhớ tốc độ cao phục vụ MoE, KV-Cache ngữ cảnh siêu dài & Decode lô lớn |
Chuẩn hóa Ba Khái niệm Dễ Nhầm lẫn Trên Datasheet GPU:
- Dense vs.
2:4Structured Sparsity: Toàn bộ đỉnh Tensor Core trongWB-Ch26là Dense. Bật nén thưa phần cứng2:4(2 phần tử khác 0 trên mỗi khối 4 phần tử) nhân đôi FLOPS lý thuyết (2x:H100lên3,958 TFFP8,B200lên18,000 TFNVFP4), nhưng không tự tăng băng thông HBM nên không giúp các nhân Memory-Bound nếu không nén được byte thực đọc. - Ada
FP8Accumulate (RTX 4090): Tích lũyFP32đạt330.3 TFDense (660.6 TFvới2:4Sparse), còn tích lũyFP16đạt660.6 TFDense (1,321.2 TFvới2:4Sparse).WB-Ch26dùng mức330.3 TF(FP32 Acc) cho mô hình suy luận bảo toàn ổn định số học. NVFP4vs. OCPMXFP4: Cùng có payload danh nghĩa4 bit/phần tử(bpe = 0.5trong mô hình Roofline bậc nhất), nhưngNVFP4dùng khối16phần tử gắn hệ số vi môFP8 E4M3(có mantissa) cộng thêmFP32tensor scale, giữ chính xác vượt trội so với chuẩn mở OCPMXFP4vốn dùng khối lớn32phần tử gắn hệ số lũy thừaUE8M0.
1.2 Mô hình Toán học Roofline: Cường độ Số học, Điểm gãy \(I^*\) & Chuyển pha Decode -> Prefill#
Được đề xuất bởi Williams et al. (2009), Mô hình Roofline đặt trần tuyệt đối cho thông lượng hiệu dụng \(\Pi_{\text{att}}\) (tính bằng \(\text{TFLOPS}\)) của bất kỳ nhân tính toán nào chỉ từ hai đại lượng: phần cứng (\(\Pi_{\text{peak}}, \text{BW}_{\text{peak}}\)) và thuật toán (Cường độ Số học \(I = \frac{\text{FLOPs}}{\text{Bytes}}\)):
- Nếu \(I < I^*\): nhân nằm ở vùng Nghẽn Băng thông Bộ nhớ (Memory-Bandwidth-Bound) — tăng tốc độ tính toán không giúp nhanh hơn; chỉ có cách giảm dung lượng byte di chuyển (
Kernel Fusion, lượng tử hóaFP8/NVFP4, hoặc tăng tái sử dụng dữ liệu). - Nếu \(I \ge I^*\): nhân đạt vùng Nghẽn Tính toán (Compute-Bound) — bão hòa trọn vẹn nhân
Tensor Core.
Dẫn xuất Cường độ Số học Cho Lõi Transformer & Điểm Cắt Lô \(B^*\)#
Xét một lớp tuyến tính FFN của mô hình lớp 70B (K = 8192, N = 28672) ở định dạng \(b\) byte/phần tử (\(b = 2\) cho BF16, \(b = 1\) cho FP8, \(b = 0.5\) cho NVFP4 lý tưởng hóa) trên lô \(M = B\) token:
- Phép toán Phần tử /
RMSNorm: Mỗi phần tử đọc đầu vào, trọng số chuẩn hóa và ghi đầu ra (\(2\)–\(3\) lượt đi qua HBM) với chỉ \(\sim 4\) phép toán \(\implies I_{\text{RMSNorm}} = \mathbf{1.00}\ \text{FLOP/Byte}\) ởBF16(và4.00ởNVFP4,bpe = 0.5). TrênH100 BF16, phép toán này chỉ chạm trần3.35 TFLOPS(0.34%năng lực tính toán) — động lực cốt lõi để dung hợp toàn bộ các lớp chuẩn hóa vào một nhân ởChương 27. -
Phép nhân Ma trận GEMM \((M \times K) \cdot (K \times N)\): Số phép toán dấu phẩy động \(\text{FLOPs} = 2 M K N\), còn lượng dữ liệu đọc/ghi HBM tối thiểu bằng \(\text{Bytes} = b(M K + K N + M N)\), suy ra:
\[I_{\text{GEMM}}(M) = \frac{2 M K N}{b(M K + K N + M N)}.\]- Tại
Decode\(M = B = 1\) (GEMV): Trọng số \(W \in \mathbb{R}^{K \times N}\) (~469.8 MBở BF16) phải đọc toàn bộ từ HBM chỉ để phục vụ duy nhất1vector token! Khi \(M=1 \ll K, N\), tử số và mẫu số triệt tiêu \(K N\): \(I_{\text{Decode}}(1) \approx \frac{2}{b} = \mathbf{1.00}\ \text{FLOP/Byte}\) (BF16,3.35 TFLOPS=0.34%trênH100) và4.00(NVFP4,bpe = 0.5), ngay cả ởB = 8cũng chỉ đạt \(I = \mathbf{7.99}\ \text{FLOP/Byte}\) ởBF16(26.77 TFLOPS=2.71%) /31.96ởNVFP4! -
Giải phương trình Điểm Cắt Lô \(B^*\): Đặt \(I_{\text{GEMM}}(B^*) = I^*\), giải tìm \(B^*\):
\[B^* = \frac{I^* \, b \, K N}{2 K N - I^* \, b \, (K + N)}.\]Thay thông số
H100 BF16(\(I^* = 295.22, b=2, K=8192, N=28672\)) choB* = 309.57(~310token/bước)! Tại \(B = 320 > B^*\), cường độ đạt304.70\(\implies\) chạm trần989.0 TFLOPS(100.0%). -
Nghịch lý
GQAAttention ở Pha Decode: Với64Q heads /8KV heads (\(g = 8\), \(S_{\text{kv}} = 4096\), \(d_h = 128\)), mỗi nhóm8Q heads dùng chung1KV head nên \(I_{\text{GQA}}(B) \approx \frac{4 g S_{\text{kv}} d_h}{b(2 S_{\text{kv}} d_h + 2 g d_h)} \approx \mathbf{7.98}\ \text{FLOP/Byte}\) ởBF16và31.94ởNVFP4(bpe = 0.5) — gấp8xso với MHA thuần nhưng không tăng theo lô \(B\) vì mỗi yêu cầu mang KV-Cache riêng! Đây chính là lý do kỹ thuật Continuous Batching, PagedAttention & Chunked Prefill (Track 2 Phần 4, Chuyên đề#23–#25) phải ghép lô hàng trăm yêu cầu và phân táchPrefill–Decode! - Tại
Prefill(S = 2048): \(I_{\text{Prefill FFN}} = \mathbf{1,549.8}\ \text{FLOP/Byte}\) (BF16) /6,199.4(NVFP4), vàFlashAttentionnhân quả đạt \(I_{\text{FlashAttn}} = \mathbf{910.2}\ \text{FLOP/Byte}\) (BF16) /3,640.9(NVFP4,bpe = 0.5) — cả hai vượt xa điểm gãy \(I^*\) để bão hòa100%Tensor Cores!
- Tại
1.3 Bộ lập lịch Warp, Phân kỳ SIMT & Vách đá SM Occupancy#
Mỗi khối luồng (Thread Block) được cắt thành các đơn vị thực thi phần cứng bất biến gọi là Warp gồm 32 luồng liên tiếp (threadIdx.x = 0..31 tạo thành Warp 0). Tất cả 32 luồng trong một Warp chia sẻ một Bộ đếm Chương trình (PC) và hoạt động theo mô hình SIMT (Single Instruction, Multiple Threads):
- Phân kỳ Nhánh (
Warp Divergence): Khi gặp nhánhif (cond) { A } else { B }mà trong cùng một Warp có cả luồng thỏa mãn lẫn luồng không thỏa mãn, phần cứng dùng mặt nạ thực thi (active execution mask 32-bit) để chạy tuần tự nhánhA(khóa tạm các luồng sai) rồi mới chạy nhánhB(khóa tạm các luồng đúng). Nếu nhánh chẵn/lẻlane % 2 == 0cân bằng (40+40chu kỳ), hiệu suấtSIMTgiảm còn50.0%; nếu1luồng cuốilane == 31đi vào nhánh chậm (148chu kỳ so với12chu kỳ của31luồng kia), cả Warp mất160chu kỳ, đẩy hiệu suất hữu ích xuống10.16%(13.33xchậm hơn)! Lưu ý: từ kiến trúc Volta trở đi có Independent Thread Scheduling giúp tránh deadlock trên từng luồng, nhưng mất mát chu kỳ thực thi song song trên 1 Warp vẫn xảy ra hoàn toàn tương tự nếu không đồng bộ hóa luồng dữ liệu. - Vách đá
SM Occupancy& Định luật Little:SM Occupancylà tỷ số \(\frac{W_{\text{active}}}{W_{\text{max/SM}}}\) (64warps trênH100/B200,48warps trênRTX 4090). Số block đồng thời nạp được trên mộtSMbị khóa bởimincủa 4 trần phần cứng:\[N_{\text{blk/SM}} = \min\!\left(\left\lfloor\frac{W_{\text{max/SM}}}{W_{\text{blk}}}\right\rfloor,\; N_{\text{hw\_blk}},\; \left\lfloor\frac{R_{\text{SM}}}{W_{\text{blk}} \cdot \lceil 32 r / 256\rceil \cdot 256}\right\rfloor,\; \left\lfloor\frac{M_{\text{SMEM/SM}}}{M_{\text{SMEM/blk}}}\right\rfloor\right).\]Chú ý bội số cấp phát thanh ghi256thanh ghi/warp: chỉ cần kernel tràn từ32lên64thanh ghi/luồng, số block đồng thời trênH100rơi gãy bậc thang từ8xuống4(100% -> 50%); lên128thanh ghi/luồng tụt tiếp còn25%; và nếu một block128luồng đòi128 KBSMEM, mỗi SM chỉ chứa đúng1block =4/64warps =6.25%Occupancy! Theo Định luật Little, để che trễ HBM~500chu kỳ vớiILP = 2, SM cần ít nhất~32warps hoạt động — rơi xuống6.25%(4warps) khiến bộ lập lịch bị đói toàn phần (latency_hiding_ratio = 0.125)!
1.4 Phân cấp Bộ nhớ CUDA: Hợp nhất 128B, Ngân hàng SRAM 32-Way & Warp Shuffle#
| Cấp Bộ nhớ CUDA | Phạm vi Truy cập | Độ trễ Xấp xỉ | Băng thông / Cơ chế Tối ưu Hóa |
|---|---|---|---|
Thanh ghi (Registers) & TMEM |
Riêng từng luồng (hoặc Warp qua shuffle; TMEM cho MMA) |
< 1 chu kỳ |
256 KB/SM (65,536 thanh ghi 32-bit). Chia sẻ dữ liệu trong cùng Warp trực tiếp bằng __shfl_down_sync mà không cần ghi ra Shared Memory! |
Bộ nhớ Chia sẻ (Shared Memory / L1) |
Chung cho mọi luồng trong 1 Thread Block (hoặc Cluster DSM) |
~20–30 chu kỳ |
Chia thành 32 ngân hàng (banks) rộng 4 byte. Địa chỉ từ 4B ánh xạ theo công thức bank = (byte_addr // 4) % 32. Trùng ngân hàng trên nhiều luồng cùng lúc gây tuần tự hóa \(K\)-way! |
Bộ nhớ Đệm L2 |
Dùng chung toàn chip GPU (mọi SM) |
~200 chu kỳ |
Phục vụ các sector 32 byte. Tái sử dụng dữ liệu giữa các SM bằng kỹ thuật L2 Cache Swizzling (xem Chương 27). |
Bộ nhớ Toàn cục (Global HBM3 / HBM3e) |
Toàn bộ GPU & Host PCIe/NVLink | ~400–800 chu kỳ |
Giao dịch theo dòng cache 128 byte (hoặc sector 32B). Các luồng liền kề trong Warp bắt buộc đọc/ghi địa chỉ liền kề (Coalesced Access). |
Công thức Vàng Triệt tiêu Xung đột Ngân hàng SRAM & Ví dụ Chuyển vị [32][33]#
Khi một Warp đọc 32 phần tử 4-byte cách nhau \(s\) từ nhớ trong Shared Memory, số luồng đâm chung vào một ngân hàng đúng bằng:
- Ở ma trận chia sẻ
__shared__ float tile[32][32], đọc theo hàng có \(s = 1 \implies \gcd(1, 32) = 1\) (sạch1-way). Nhưng đọc theo cộttile[threadIdx.x][col]có khoảng bước giữa các hàng là \(s = 32 \implies K_{\text{bank}} = \gcd(32, 32) = \mathbf{32}\text{-way}\)! Toàn bộ32luồng xếp hàng vào1ngân hàng duy nhất (3.12%hiệu suất). - Chỉ cần đệm
+1cột thành__shared__ float tile[32][33], khoảng bước cột trở thành \(s = 33 \implies K_{\text{bank}} = \gcd(33, 32) = \mathbf{1}\text{-way}\) (32luồng trúng trọn32ngân hàng phân biệt,100.0%hiệu suất SRAM)!
Trụ cột 2 — Mô hình Lập trình CUDA, Ba Sơ đồ Kiến trúc & Công cụ Hệ sinh thái 2026#
2.1 Sơ đồ 1: Giải phẫu SM & Bậc thang Phân cấp Bộ nhớ GPU (Ada \(\to\) Hopper \(\to\) Blackwell)#
2.2 Sơ đồ 2: Bản đồ Chẩn đoán Roofline & Can thiệp Kỹ nghệ Nhân (Prefill vs Decode)#
2.3 Sơ đồ 3: Biểu đồ Tuần tự Thực thi Eager vs CUDA Graphs + Truy cập Hợp nhất#
2.4 Mô hình Lập trình CUDA, CUDA Graphs, CuTe/CUTLASS 3.x & Nsight Compute (ncu)#
- Phân cấp Lập chỉ mục Lưới & Luồng (
gridDim,blockDim,threadIdx):- Trong CUDA C++, một lần phóng nhân
kernel<<<gridDim, blockDim, smem_bytes, stream>>>(...)tạo ra lưới các Thread Block (blockIdx.{x,y,z}) và từng luồng bên trong block (threadIdx.{x,y,z}). Công thức chỉ mục 1D chuẩnconst int idx = blockIdx.x * blockDim.x + threadIdx.x;tự nhiên gán32luồng liên tiếp (threadIdx.x = 0..31) vào các địa chỉsrc[idx]kế nhau, đảm bảo hợp nhất128B. - Đồng bộ hóa theo Phân tầng:
__syncthreads()chỉ đồng bộ các luồng trong cùng 1 Thread Block qua bộ nhớ chia sẻ (tuyệt đối không dùng để đồng bộ giữa 2 Block khác nhau — muốn đồng bộ cluster cầncg::cluster_group::sync(), còn liên-block phải tách kernel hoặc dùngCUDA Streams/cudaEvent_t!).
- Trong CUDA C++, một lần phóng nhân
CUDA Graphs,Green Contexts&Programmatic Dependent Launch (PDL)(Track 2, Chuyên đề#35):- Khi mạng nơ-ron giải mã ở lô nhỏ (
gpu_exec < cpu_launch), chuỗi các lần gọicudaLaunchKerneltừ Python/C++ tạo ra các khoảng trống (launch bubbles).CUDA Graphstách quy trình thành hai pha sạch trong01_memory_and_gemm_kernels.cu:capture_decode_graph(cudaStreamBeginCapture\(\to\)cudaGetLastError()\(\to\)cudaStreamEndCapture\(\to\)cudaGraphInstantiate\(\to\)cudaGraphDestroy) vàreplay_decode_graph(vòng lặpcudaGraphLaunch\(\to\)cudaStreamSynchronize\(\to\)cudaGetLastError()trước khi hủycudaGraphExecDestroy). - Điều phối SOTA 2025–2026 (
Green Contexts&PDL):CUDA Green Contexts(CUDA 12.4+) phân vùng cứng số lượngSMở cấp driver để cô lập tảiPrefill(hoặc truyền thôngNCCL) khỏi luồngDecodenhạy độ trễ đuôi trên cùng một GPU; cònProgrammatic Dependent Launch (PDL)trên Hopper/Blackwell cho phép nhân con khởi động pha nạp trọng số sớm ngay khi nhân cha đang chạy phần đuôi (epilogue), triệt tiêu khoảng chết giữa hai nút kế tiếp.
- Khi mạng nơ-ron giải mã ở lô nhỏ (
Bốn Cái bẫy Sản xuất Kinh điển Khi Triển khai CUDA Graphs Trong vLLM / SGLang:
- Hình dáng Cố định &
Shape Bucketing: Đồ thị đóng bănggridDimvà kích thước tensor tại lúc ghi; các lô/độ dài động phải được đệm (padding) vào các bậc định sẵn (shape buckets, ví dụB ∈ {1, 2, 4, 8, 16, 32, 64}) và capture trước một đồ thị cho mỗi bậc. - VRAM Chết Trong
cudaGraphMemoryPool_t: Các tensor trung gian cấp phát bên trong pha capture bị neo vĩnh viễn vào bể bộ nhớ đồ thị riêng; sinh quá nhiều đồ thị không chia sẻ pool gâyOOMdù VRAM hoạt động thấp. - Tái cấp phát Con trỏ (
data_ptr()Reallocation):CUDA Graphgiữ địa chỉ con trỏ GPU thô từ lúc capture — nếu tensor I/O đổidata_ptr()ở bước sau, đồ thị sẽ đọc/ghi nhầm vùng nhớ cũ (silent corruption / lỗi truy cập bộ nhớ)! Luôn cấp phát trước buffer tĩnh và dùngcopy_()trước khi replay. - Xung đột
Python GCTrong Lúc Capture: Nếu bộ thu gom rác Python chạy đúng lúc đang mởcudaStreamBeginCapture, việc hủy đối tượng tạm có thể kích hoạtcudaFreegây sập capture — luôn bọc pha capture bằnggc.disable()(khôi phục trongfinally) và tách riêng vòng lặpreplaycócudaStreamSynchronize.
-
Hệ sinh thái Biên dịch & Hồ sơ Hóa SOTA 2025–2026 (
CUTLASS 3.x/CuTe&Nsight Compute):CUTLASS 3.x&CuTe: Thay vì tự viết tay công thức chỉ số lồng nhau dễ lỗi xung đột bank trên Tensor Core,CuTemô hình hóa bố cục bộ nhớ bằng cặp Đại số Hình dáng–Khoảng bước(Shape, Stride)và toán tử Swizzle tự động hóa ánh xạ không xung đột từ HBM (TMA) \(\to\) SMEM \(\to\) Thanh ghi/TMEM.Nsight Compute(ncu) & Bảng Chẩn đoán 5 Điểm NghẽnWarp Stall(Cầu nối Chuyên đề#34): Khi hồ sơ hóa nhân thực tế trên GPU, sau khi xemSOL%(Speed of Lightsm__throughputvsdram__throughput) và khuếch đại sector L1/L2, kỹ sư đối chiếu trực tiếp cộtWarp State / Stall Reasonssang hành động sửa nhân cụ thể:
Mã Nghẽn ncu(Warp Stall)Nguyên nhân Phần cứng Gốc rễ Can thiệp Kỹ nghệ Nhân CUDA / Triton Cụ thể long_scoreboardWarp chờ dữ liệu từ bộ nhớ độ trễ dài ( HBM/L2)Sửa Coalescing 128B(AoS -> SoA), tăngSM Occupancy, nạp trước bất đồng bộ (cp.async/TMA), hoặc dung hợp nhân (Ch 27)short_scoreboardWarp chờ toán hạng từ bộ nhớ độ trễ ngắn ( SMEM/SFU/ thanh ghi phụ thuộc)Triệt tiêu xung đột 32ngân hàng SRAM ([32][33],CuTeSwizzle), tách chuỗi phụ thuộc FMA tăngILPmio_throttleHàng đợi Memory Input/Output ( MIO) trênLSU/Shared Memoryquá tảiGiảm vòng đọc/ghi SMEMthừa, vector hóafloat4(128-bit), rút gọn qua__shfl_down_synchoặcTMEMbarrierCác luồng tới __syncthreads()lệch thời gian vì tải không đều hoặc phân kỳSIMTCân bằng tải giữa các Warp, gỡ nhánh điều kiện lệch ( if/else), tách nhỏ pha đồng bộno_eligibleWarp Scheduler không có bất kỳ Warp nào sẵn sàng phát lệnh ở chu kỳ hiện tại Sửa vách đá SM Occupancy(giảm thanh ghi/luồng<= 64, hạSMEM/blockdưới ngưỡng trần, tăngILP)Chương 27ngay sau đây sẽ dùngOpenAI Tritonđể tự động hóa toàn bộ tầng hợp nhất HBM, tile SRAM và L2 cache swizzling bằng Python!
Ghi chú Minh bạch & Thiết kế Thực nghiệm Hai Tầng trong WB-Ch26:
- Mô hình Phần cứng GPU & Kiểm toán
.cu: Do môi trường phòng lab.venvlà máy cục bộCPU-only(PyTorch 2.15.0+cpu), toàn bộ các phép tính về thông sốH100_SXM/B200_SXM/RTX_4090, giao dịch dòng cache128B, xung đột32ngân hàng SRAM, độ chiếm dụng SM và đường thời gianCUDA Graphđược tính bằng mô hình giải tích vật lý tất định khớp với tài liệu kiến trúc NVIDIA, đi kèm mã nguồn CUDA C++ thật tạicuda_kernels/01_memory_and_gemm_kernels.cuđược kiểm toán tự động. - Đo lường Thực nghiệm Thật trên
PyTorch 2.15.0+cpu: Để học viên tự tay quan sát tác động vật lý của bố cục bộ nhớ và cường độ số học ngay trên phần cứng thật,WB-Ch26đồng thời thực thi đo thời gian thực hai bài toánPyTorch(lưu ý độ trễ đo thực tế biến động nhẹ tùy tải CPU và số luồng OpenMP máy trạm): (1) giảm bậc liên tục vs chuyển vị sải bước (0.526 ms -> 1.000 ms, chậm1.90x) và (2) co giãntorch.matmultừ GEMVM=1(11.30 GFLOP/s) lên GEMMM=256(227.72 GFLOP/s,20.15x)!
Trụ cột 3 — Hệ sinh thái 2026 & Mã nguồn Thực thi Độc lập#
Đoạn mã độc lập dưới đây chạy trực tiếp 100% ngoại tuyến trong .venv (Python 3.12, PyTorch 2.15.0+cpu, Pydantic v2), tái hiện đầy đủ bốn cơ chế nền tảng của Chương 26: (1) Hợp nhất 128B vs rải bước stride=32, (2) Xung đột 32-way trên [32][32] vs 1-way trên [32][33], (3) Vách đá SM Occupancy (6.25% vs 100.0%), và (4) Điểm gãy Roofline H100 / B200 + điểm cắt lô \(B^* \approx 310\) + đo thật PyTorch CPU liên tục vs chuyển vị:
"""Pillar 3 Executable Specimen: 128B Coalescing, 32-Bank Padding, SM Occupancy & Roofline."""
from __future__ import annotations
import json
import math
import time
from typing import Any
import torch
from pydantic import BaseModel, ConfigDict, Field
class GPURooflineSpec(BaseModel):
model_config = ConfigDict(extra="forbid", strict=True)
name: str
hbm_bw_gb_s: float = Field(..., gt=0.0)
peak_tflops: float = Field(..., gt=0.0)
max_warps_per_sm: int = Field(default=64, ge=32)
registers_per_sm: int = Field(default=65536, ge=1024)
shared_mem_kb_per_sm: float = Field(default=228.0, gt=0.0)
def coalescing_128b_audit(stride_elems: int, elem_bytes: int = 4) -> dict[str, Any]:
addrs = [lane * stride_elems * elem_bytes for lane in range(32)]
lines_128b = len({a // 128 for a in addrs})
sectors_32b = len({a // 32 for a in addrs})
useful = 32 * elem_bytes
return {
"stride_elems": stride_elems,
"lines_128b": lines_128b,
"sectors_32b": sectors_32b,
"cache_line_amplification": round((lines_128b * 128) / useful, 2),
"efficiency_pct": round((useful / (lines_128b * 128)) * 100.0, 2),
}
def smem_column_bank_conflict(tile_dim: int = 32, padding: int = 0) -> dict[str, Any]:
banks = [(lane * (tile_dim + padding)) % 32 for lane in range(32)]
hits = [banks.count(b) for b in range(32)]
ways = max(hits)
return {
"layout": f"[{tile_dim}][{tile_dim + padding}]",
"conflict_ways": ways,
"distinct_banks_hit": sum(1 for c in hits if c > 0),
"bank_efficiency_pct": round((1.0 / ways) * 100.0, 2),
}
def h100_sm_occupancy(threads_per_block: int, regs_per_thread: int, smem_kb: float) -> float:
spec = GPURooflineSpec(name="H100_SXM", hbm_bw_gb_s=3350.0, peak_tflops=989.0)
warps_blk = math.ceil(threads_per_block / 32)
regs_blk = math.ceil((regs_per_thread * 32) / 256) * 256 * warps_blk
blocks = min(
spec.max_warps_per_sm // warps_blk,
32,
spec.registers_per_sm // regs_blk,
int(spec.shared_mem_kb_per_sm // smem_kb),
)
return round(((blocks * warps_blk) / spec.max_warps_per_sm) * 100.0, 2)
def run_ch26_specimen() -> dict[str, Any]:
"""Verify CUDA memory coalescing, SRAM padding, SM occupancy, Roofline & PyTorch CPU."""
h100 = GPURooflineSpec(name="H100_SXM_BF16", hbm_bw_gb_s=3350.0, peak_tflops=989.0)
b200_fp4 = GPURooflineSpec(name="B200_SXM_NVFP4", hbm_bw_gb_s=8000.0, peak_tflops=9000.0)
ridge_h100 = round((h100.peak_tflops * 1000.0) / h100.hbm_bw_gb_s, 2)
ridge_b200 = round((b200_fp4.peak_tflops * 1000.0) / b200_fp4.hbm_bw_gb_s, 2)
# FFN 8192 x 28672 BF16 (2 bytes): Decode B=1 vs B=320 vs Prefill S=2048
k_dim, n_dim, bpe = 8192, 28672, 2.0
crossover_b = round(
(ridge_h100 * bpe * k_dim * n_dim) / (2.0 * k_dim * n_dim - ridge_h100 * bpe * (k_dim + n_dim)),
2,
)
ai_b1 = (2 * 1 * k_dim * n_dim) / (bpe * (1 * k_dim + k_dim * n_dim + 1 * n_dim))
ai_s2048 = (2 * 2048 * k_dim * n_dim) / (bpe * (2048 * k_dim + k_dim * n_dim + 2048 * n_dim))
# Real PyTorch CPU contiguous vs strided transposed row sum
torch.manual_seed(42)
x = torch.randn((1024, 1024), dtype=torch.float32)
xt = x.t()
xc = xt.contiguous()
_ = xc.sum(dim=1)
_ = xt.sum(dim=1)
t0 = time.perf_counter_ns()
for _ in range(10):
_ = xc.sum(dim=1)
t1 = time.perf_counter_ns()
for _ in range(10):
_ = xt.sum(dim=1)
t2 = time.perf_counter_ns()
contig_ms = (t1 - t0) / 10_000_000.0
strided_ms = (t2 - t1) / 10_000_000.0
return {
"coalesced_stride_1": coalescing_128b_audit(1),
"strided_stride_32": coalescing_128b_audit(32),
"smem_naive_32x32": smem_column_bank_conflict(32, 0),
"smem_padded_32x33": smem_column_bank_conflict(32, 1),
"occupancy_crash_128kb_pct": h100_sm_occupancy(128, 128, 128.0),
"occupancy_optimal_pct": h100_sm_occupancy(256, 32, 16.0),
"h100_bf16_ridge": ridge_h100,
"b200_nvfp4_ridge": ridge_b200,
"h100_ffn_crossover_batch": crossover_b,
"decode_b1_ai": round(ai_b1, 3),
"prefill_s2048_ai": round(ai_s2048, 1),
"pytorch_cpu_contig_ms": round(contig_ms, 4),
"pytorch_cpu_strided_ms": round(strided_ms, 4),
"pytorch_cpu_strided_slowdown": round(strided_ms / max(1e-6, contig_ms), 2),
}
if __name__ == "__main__":
print(json.dumps(run_ch26_specimen(), indent=2))
Trụ cột 4 — Phòng thí nghiệm Thực chiến (WB-Ch26: gpu_cuda_roofline_lab) & Rubric Kiểm thử#
4.1 Kiến trúc Hai Tầng của WB-Ch26#
Toàn bộ mã nguồn và dữ liệu thực nghiệm được đóng gói tại labs/ch26-gpu-cuda-roofline-workbench/README.md dưới gói gpu_cuda_roofline_lab (Python 3.12, khóa 34 gói từ index pytorch-cpu trong uv.lock, 100% ngoại tuyến, tất định seed=42, cấm tuyệt đối pickle/joblib):
- Tầng 1 — Nhân CUDA C++ Tham chiếu (
cuda_kernels/01_memory_and_gemm_kernels.cu): Gồm6nhân__global__chuẩn CUDA C++ (coalesced_copy_kernel,strided_copy_kernel,transpose_naive_smem_kernel,transpose_padded_smem_kernel,warp_shuffle_reduce_sum_kernel,tiled_gemm_smem_kernel) và cặp hàm tách phacapture_decode_graph+replay_decode_graph(gọicudaStreamSynchronizevàcudaGetLastErrortrướccudaGraphExecDestroy), được kiểm toán tự động bởiaudit_cuda_kernel_file. - Tầng 2 — Động cơ Phân tích Phần cứng & Đối chứng
PyTorch 2.15+cpu(src/gpu_cuda_roofline_lab/):hardware_and_roofline.py: Danh mục thông số phần cứngGPU_HARDWARE_SPECS(RTX_4090,H100_SXM,B200_SXM) vàFP4_MICROSCALING_FORMATS(NVFP4vsMXFP4), mô hình Roofline cho GEMM / RMSNorm / GQA Decode vs Prefill, bộ giải điểm cắt lô \(B^*\), mô phỏng đường thời gianCUDA GraphvsEager, đo đạc thực nghiệm trênPyTorch 2.15.0+cpu(benchmark_pytorch_contiguity_vs_strided,benchmark_pytorch_cpu_gemm_scaling), và xuất6spanOpenTelemetry.cuda_memory_and_occupancy.py: Phân tích giao dịch128B/ sector32B(analyze_global_memory_coalescing), xung đột32ngân hàng SRAM (analyze_shared_memory_banks), suy giảmSIMTdo phân kỳ nhánh (simulate_warp_divergence), tính toánSM Occupancykèm vách đá thanh ghi/SMEM & Định luật Little (calculate_sm_occupancy), và bộ kiểm toán nhân.cu.
4.2 Bảng Kết quả Thực nghiệm Chuẩn hóa (seed=42, artifacts/ch26_wb26_results.json)#
A. Đăng ký Phần cứng & Mô hình Roofline LLM Decode vs Prefill (FFN 8192×28672, GQA 64/8 S_kv=4096):
| Giai đoạn / Tải Tính toán | Cường độ Số học \(I\) (BF16 / NVFP4, bpe=0.5) |
H100 SXM BF16 (\(I^* = 295.22\)) |
B200 SXM NVFP4 (\(I^* = 1,125.00\)) |
|---|---|---|---|
RMSNorm / Elementwise |
1.00 / 4.00 |
3.35 TFLOPS (0.34%, memory_bound) |
32.00 TFLOPS (memory_bound) |
Decode FFN (B = 1) |
1.00 / 4.00 |
3.35 TFLOPS (0.34%, memory_bound) |
32.00 TFLOPS (0.36%, memory_bound) |
Decode FFN (B = 8) |
7.99 / 31.96 |
26.77 TFLOPS (2.71%, memory_bound) |
255.68 TFLOPS (2.84%, memory_bound) |
Decode FFN (B = 64) |
63.36 / 253.45 |
212.27 TFLOPS (21.46%, memory_bound) |
2,027.63 TFLOPS (22.53%, memory_bound) |
Decode FFN (B = 256) |
246.11 / 984.45 |
824.47 TFLOPS (83.36%, memory_bound) |
7,875.57 TFLOPS (87.51%, memory_bound) |
Decode FFN (B = 320 > B*) |
304.70 / 1,218.79 |
989.00 TFLOPS (100.0%, compute_bound) |
9,000.00 TFLOPS (100.0%, compute_bound) |
Decode GQA 8x (B = 1..512) |
7.98 / 31.94 (bất biến theo \(B\)) |
26.75 TFLOPS (2.70%, memory_bound) |
255.50 TFLOPS (2.84%, memory_bound) |
Prefill FFN (S = 2048) |
1,549.8 / 6,199.4 |
989.0 TFLOPS (100.0%, compute_bound) |
9,000.0 TFLOPS (100.0%, compute_bound) |
Prefill FlashAttn (S = 2048) |
910.2 / 3,640.9 |
989.0 TFLOPS (100.0%, compute_bound) |
9,000.0 TFLOPS (100.0%, compute_bound) |
B. Tối ưu Bộ nhớ CUDA, Xung đột SRAM, Phân kỳ Warp & Vách đá SM Occupancy (H100 SXM):
| Cơ chế / Kịch bản Kiểm định | Chỉ số Phần cứng Đo được | Hiệu suất / Chiếm dụng | Biện pháp Khắc phục Tương ứng |
|---|---|---|---|
Global HBM Coalesced (stride=1) |
1 dòng 128B (4 sector 32B) |
100.0% (3,350 GB/s hiệu dụng) |
Bố cục SoA căn chỉnh thẳng hàng theo Warp |
Global HBM Strided (stride=32) |
32 dòng 128B (32.0x khuếch đại / 8x sector) |
3.12% (104.7 GB/s mức line / 418.8 GB/s sector) |
Đổi sang SoA hoặc đệm qua Shared Memory |
SMEM Transpose [32][32] (Cột) |
Xung đột 32-way (1 bank hứng 32 luồng) |
3.12% (tuần tự hóa 32x) |
Thay bằng đệm +1 cột: __shared__ float tile[32][33] |
SMEM Transpose [32][33] (Cột) |
1-way (0 xung đột), trúng đủ 32 banks |
100.0% (\(\gcd(33, 32) = 1\)) |
Bảo toàn trọn vẹn băng thông SRAM |
| SM Occupancy Crash vs Tuned | 4 warps (1 block) \(\to\) 64 warps (8 blocks) |
6.25% \(\to\) 100.0% (Little's Law 4 < 32) |
Giảm SMEM 128 KB -> 16 KB, 256 thr/blk, 32 regs |
SIMT Warp Divergence (mod2 / tail) |
80 chu kỳ (mod2) / 160 chu kỳ (lane==31) |
50.0% / 10.16% hiệu suất SIMT |
Gỡ rẽ nhánh phân kỳ hoặc dùng __shfl_down_sync |
C. Đường thời gian CUDA Graphs (Mô phỏng) & Đo kiểm Thực nghiệm Thật trên PyTorch 2.15.0+cpu:
| Thí nghiệm / Chế độ Chạy | Độ trễ / Thông lượng Đo được | Tăng tốc / Hệ số | Phạm vi Thực thi Minh bạch |
|---|---|---|---|
Eager Host Launch (180 vi nhân) |
1,442.0 us (24.97% GPU util) |
1.00x (75.03% bong bóng chờ CPU) |
Mô hình đường thời gian CUDA Host-GPU |
CUDA Graph Replay (180 nút) |
416.8 us (86.38% GPU util) |
3.46x nhanh hơn Eager |
Mô hình CUDA Graph 1 lần phóng 12.0 us |
CUDA Graph + Kernel Fusion (64 nút) |
351.8 us |
4.10x nhanh hơn Eager |
Mô hình Graph kết hợp dung hợp nhân |
PyTorch CPU sum(dim=1) (2048×2048) |
0.526 ms (31.88 GB/s) vs 1.000 ms (16.78 GB/s) |
1.90x chậm do stride [1, 2048] |
Đo thời gian thực trên PyTorch 2.15.0+cpu |
PyTorch CPU MatMul (1024×1024, M=1..256) |
11.30 GFLOP/s (M=1) \(\to\) 227.72 GFLOP/s (M=256) |
20.15x co giãn thông lượng |
Đo thời gian thực trên PyTorch 2.15.0+cpu |
4.3 Hợp đồng 18 Bài kiểm thử Tự động (tests/test_gpu_cuda_roofline_lab.py)#
| STT | Tên Hàm Kiểm thử Pytest |
Bất biến & Ngưỡng Nghiệm thu Bắt buộc |
|---|---|---|
1 |
test_01_ast_no_unsafe_deserializers |
Quét AST toàn bộ src/ và scripts/, cấm pickle, joblib, cloudpickle, dill, shelve, marshal |
2 |
test_02_pydantic_v2_strict_contracts_forbid_extra_fields |
Khóa chặt GPUHardwareSpec, CoalescingReport, RooflinePoint (extra="forbid", strict=True) |
3 |
test_03_gpu_spec_registry_and_sm_profile_parity |
Đồng bộ 100% thông số RTX_4090 (660.6 TF FP16 Acc), H100_SXM, B200_SXM (75.0 TF FP32, 180 GB usable, single-thread, NVFP4 vs MXFP4) |
4 |
test_04_global_coalescing_128b_and_32b_sector_exact_math |
Chứng minh stride=1 đạt 1 dòng 128B (100%), còn stride=32 phóng đại 32x (3.125%, 8x sector) |
5 |
test_05_shared_memory_32_bank_conflict_naive_vs_padded |
Chứng minh [32][32] cột nổ 32-way, còn [32][33] cột về 1-way (100% bank efficiency) |
6 |
test_06_hypothesis_padded_stride_coprime_conflict_free |
Kiểm định ngẫu nhiên Hypothesis (40 mẫu): chứng minh định lý conflict_ways == gcd(32 + padding, 32) |
7 |
test_07_simt_warp_divergence_lockstep_efficiency |
Định lượng phân kỳ mod2 (50.0% hiệu suất, 80 chu kỳ) và nhánh đuôi đơn (< 15%, 160 chu kỳ) |
8 |
test_08_sm_occupancy_register_and_smem_cliffs |
Kiểm chứng bậc thang 100% -> 50% -> 25% theo thanh ghi và sụp đổ 6.25% (4/64 warps) khi tràn 128 KB SMEM |
9 |
test_09_roofline_ridge_points_and_precision_support |
Kiểm tra điểm gãy \(I^*\) (H100 BF16 295.22, B200 NVFP4 1,125.00, RTX 4090 163.89) và chặn NVFP4 trên H100 |
10 |
test_10_llm_decode_vs_prefill_roofline_and_batch_crossover |
Kiểm định Decode B=1..8 kẹt memory_bound, điểm cắt lô \(B^* \in (300, 320)\), B=320 & Prefill chạm 100% |
11 |
test_11_cuda_graph_launch_overhead_and_fusion_speedup |
Chứng minh Eager mất > 74% launch bubble (1,442 us), CUDA Graph tăng > 3.0x (86.4% GPU util) |
12 |
test_12_pytorch_cpu_contiguous_vs_strided_real_measurement |
Chạy PyTorch CPU (2048×2048) ổn định dưới cả OMP_NUM_THREADS=1 lẫn đa luồng (strided_slowdown_factor > 1.0) |
13 |
test_13_pytorch_cpu_gemm_scaling_real_measurement |
Chạy torch.matmul (1024×1024) chứng minh GFLOP/s tăng từ M=1 lên M=256 bất biến theo cấu hình OpenMP |
14 |
test_14_tier1_cu_kernel_static_contract_audit |
Kiểm toán 01_memory_and_gemm_kernels.cu: đủ 6 nhân __global__, [kTileDim + 1], __shfl_down_sync, capture_decode_graph, replay_decode_graph, cudaStreamSynchronize, cudaGetLastError |
15 |
test_15_otel_in_memory_spans_recorded |
Xác nhận ghi nhận trọn vẹn 6 span OpenTelemetry qua InMemorySpanExporter |
16 |
test_16_full_benchmark_determinism_and_error_handling |
Kiểm tra tính tất định của mô hình phần cứng và báo lỗi ValueError với đầu vào sai miền |
17 |
test_17_cli_artifact_and_workbench_panels_schema |
CLI --quick xuất JSON hợp lệ gồm đúng 6 KPI, 4 biểu đồ cột và 4 bảng workbench_panels |
18 |
test_18_hypothesis_roofline_monotonic_with_batch_size |
Bất biến Hypothesis (30 mẫu): tăng lô \(M\) làm tăng đơn điệu cường độ số học và không vượt trần đỉnh GPU |
Trụ cột 5 — Văn liệu Nền tảng, Ôn tập Nhanh & Hệ thống Bài tập Chuyên sâu#
5.1 Mười Công trình Học thuật & Tiêu chuẩn Kỹ nghệ Nền tảng (2009–2026)#
- Williams, S., Waterman, A. & Patterson, D. (CACM 2009). Roofline: An Insightful Visual Performance Model for Multicore Architectures — đặt nền móng định lượng điểm gãy \(I^* = \Pi_{\text{peak}} / \text{BW}_{\text{peak}}\) phân biệt hai chế độ Memory-Bound và Compute-Bound.
- NVIDIA Corporation (2014–2026). CUDA C++ Programming Guide & CUDA Best Practices Guide — chuẩn đặc tả mô hình lập trình
grid/block/warp, hợp nhất128B/32B,32ngân hàng SRAM, nguyên thủy__shfl_down_sync,CUDA Graphs,Green ContextsvàProgrammatic Dependent Launch (PDL). - Harris, M. (NVIDIA Developer Blog). An Efficient Matrix Transpose in CUDA C/C++ — chứng minh chuẩn kinh điển về đệm
[32][33]để xóa bỏ xung đột32-way trên Shared Memory. - NVIDIA Hopper Architecture Whitepaper (GH100, 2022–2023). Giới thiệu
WGMMA(4-warp),TMA(Tensor Memory Accelerator), Thread Block Clusters vàHBM3 3.35 TB/s(989 TFLOPS BF16,1,979 TFLOPS FP8dense). - NVIDIA Blackwell Architecture,
GB200 NVL72&Blackwell Ultra(B300/GB300, 2024–2026). Đột phátcgen05.mma(single-threadissue semantics), bộ nhớ tích lũyTMEM(256 KB/SM),NVFP4(16-elemFP8 E4M3+FP32tensor scale) phân biệt với OCPMXFP4(32-elemUE8M0),9,000 TFLOPSdense (18,000 TF2:4sparse),180 GBusable HBM3e (192 GBraw,8.0 TB/s,~75 TFFP32), cùng kiến trúc rackGB200 NVL72(72GPUs,130 TB/sNVLink fabric) vàBlackwell Ultra(B300/GB300,~270–288 GBHBM3e). - Dao, T. et al. (NeurIPS 2022, ICLR 2024). FlashAttention & FlashAttention-2 — ứng dụng trực tiếp phân cấp bộ nhớ
HBMvsSRAMđể nâng cường độ số học Attention từ bậcO(1)lên bậcO(S)(tiền đề choChương 27). - NVIDIA
CUTLASS 3.x&CuTeLayout Algebra (2023–2026). Hệ thống đại số hình học tensor(Shape, Stride)và toán tử Swizzle tự động hóa cấp phát Tensor Core không xung đột ngân hàng. - NVIDIA
Nsight Compute(ncu) Kernel Profiling Guide (2024–2026). Chuẩn phân tích Speed of Light (SOL%), tỷ lệ khuếch đại sector L1/L2 và bảng chẩn đoánWarp Stall(long_scoreboard,short_scoreboard,mio_throttle,barrier,no_eligible). - Pope, R. et al. (MLSys 2023) & Kwon, W. et al. (SOSP 2023,
vLLM). Efficiently Scaling Transformer Inference — giải phẫu hai phaPrefill(Compute-Bound) vsDecode(Memory-Bandwidth-Bound), đặt nền tảng liên thông lênTrack 2 Phần 4(#18–#35). - Tillet, P., Kung, H. T. & Cox, D. (MAPL 2019, OpenAI Triton). Triton: An Intermediate Language and Compiler for Tiled Neural Network Computations — trừu tượng hóa
SPMDtheo khối (tile) tự động hóa hợp nhất bộ nhớ, đệm ngân hàng và lập lịch thanh ghi (trọng tâmChương 27).
5.2 Tám Câu hỏi Trắc nghiệm Kiểm tra Nhanh (Q1..Q8 — Khớp quiz_and_hints.json)#
Q1(CPU vs GPU & Tiến hóa Tensor Cores): GPU tối ưu thông lượng nhờ dùng tập thanh ghi khổng lồ (65,536 x 32-bit/SM) chuyểnWarpở0chu kỳ; AdaRTX 4090đạt330.3 TFFP8 (FP32 Acc) vs660.6 TF(FP16 Acc); Hopper bổ sungWGMMA (4-warp) + TMA; còn BlackwellB200 SXM(180 GBusable /192 GBraw HBM3e8 TB/s,~75 TFFP32) đưa thêmtcgen05.mma(single-threadissue) +TMEM (256 KB/SM)+NVFP4(16-elemFP8 E4M3vs OCPMXFP432-elemUE8M0,9,000 TFdense /18,000 TF2:4sparse).Q2(Hợp nhất128BCache-Line vs Rải bướcstride=32): Truy cậpfloat32stride=32chạm32dòng cache128Briêng rẽ (4,096 Btải xuống cho128 Bhữu ích), khuếch đại32.0xdòng cache (8.0xL2 sector) và hạ hiệu suất xuống3.12%; kiểm chứng trênPyTorch CPUthật (2048×2048) cũng chậm1.90x(0.526 msvs1.000 ms).Q3(Xung đột32Ngân hàng SRAM & Định lý Đồng nguyên):tile[32][32]đọc theo cột chostride = 32nên \(\gcd(32, 32) = 32\)-way bank conflict; đệm+1cột thànhtile[32][33]cho \(\gcd(33, 32) = 1\)-way (100%hiệu suất SRAM).Q4(Phân kỳWarp SIMT&Warp Shuffle): Nhánh rẽ lệch trên cùngWarpchạy tuần tự hai nhánh bằng mặt nạSIMT(mod2hạ hiệu suất xuống50.0%,lane==31tụt còn10.16%); trong khi__shfl_down_synctrao đổi trực tiếp giữa các thanh ghi cùng Warp mà không tốn vòng đọc/ghi Shared Memory.Q5(Vách đáSM Occupancy& Định luật Little): Nâng thanh ghi32 -> 64 -> 128/luồng cắt occupancy trênH100từ100% -> 50% -> 25%, còn cấp128 KBSMEM cho block128luồng ép SM chỉ nạp1block (4/64 = 6.25%), đói warp che trễ (4 < 32) theo Định luật Little.Q6(Mô hình Roofline & Điểm Cắt Lô \(B^*\)):H100 BF16có điểm gãy \(I^* = 295.22\) (B200 NVFP4\(I^* = 1,125.0\));Decode B=1(AI = 1.00BF16 /4.00NVFP4) kẹt vùng băng thông, chỉ vượt điểm gãy khi lô đạt \(B^* \approx 310\) token (B=320đạt989 TFLOPS),GQA 8x Decodecố định ở7.98(BF16) /31.94(NVFP4,bpe=0.5), cònPrefill FlashAttnđạt910.2(BF16) /3,640.9(NVFP4).Q7(CUDA Graphs,Green Contexts,PDL& Bẫy Production): Chuỗi180vi nhân2.0 usbị CPU launch8.0 ustạo75.03%bong bóng (1,442 us); táchcapture_decode_graph+replay_decode_graph(cudaStreamSynchronize) hạ xuống416.8 us(3.46x,4.10xvới Fusion), đồng thời kết hợpGreen Contextscô lập SM,PDLchồng lấp kernel và tránh4bẫy (shape bucketing,cudaGraphMemoryPool_t,data_ptr(), tắt Pythongckhi capture).Q8(Nsight ComputeStall Triage & Cầu nối LênTriton/Track 2): Bảng phản xạ 5 cột nghẽnncu:long_scoreboard\(\to\) sửa128Bcoalescing /TMA/ occupancy / fusion;short_scoreboard\(\to\) đệm SRAM[32][33]/CuTeswizzle;mio_throttle\(\to\) giảm vòng SMEM, dùngfloat4hoặc__shfl_down_sync;barrier\(\to\) gỡ phân kỳ nhánh lệch tải trước__syncthreads();no_eligible\(\to\) hạ thanh ghi/SMEM nâng Occupancy.
5.3 Sáu Bài tập Chuyên sâu & Thang chấm Rubric (ex1..ex6)#
- Bài tập 1 (
15%) — Kiểm toán Giao dịch128B& Thí nghiệm Chuyển vịPyTorch CPU: Chứng minh công thức dòng cache128Bvà sector32Bchostride = 1, 4, 32(Tests 04, 12) và giải thích vì saox.t().sum(dim=1)chậm1.90xso với bản liên tục. - Bài tập 2 (
15%) — Triệt tiêu Xung đột32Ngân hàng SRAM Bằng Đồng nguyên \(\gcd(s, 32)\): Tínhbank_idchotile[32][32]vstile[32][33]ở cả pha đọc hàng và cột; kiểm chứng định lýgcd(32 + padding, 32)quaTests 05–06, 14. - Bài tập 3 (
20%) — Định lượng Phân kỳSIMT& Bậc thangSM Occupancy: Tính số block tối đa trênH100_SXMvàRTX_4090với kích thước cấp phát256thanh ghi/warp; phân tích vì sao128 KBSMEM kéo occupancy xuống6.25%(Tests 07–08). - Bài tập 4 (
20%) — Dẫn xuất Roofline LLMDecode -> Prefill& Điểm Cắt Lô \(B^*\): Tính \(I^*\) choH100_SXM(BF16/FP8) vàB200_SXM(NVFP4), dẫn xuất phương trình bậc nhất tìm \(B^* \approx 309.6\), so sánh cường độ số họcNVFP4(4.00,31.94,3,640.9) vsBF16(1.00,7.98,910.2), đối chiếu vớitorch.matmul(Tests 09–10, 13, 18). - Bài tập 5 (
15%) — Thiết kế Đường ốngCUDA Graphs& Giải mã 5 Chỉ sốNsight Compute: Lập biểu đồ Gantt chứng minh75.03%bong bóng và cáchcapture_decode_graph/replay_decode_graphđạt3.46x(4.10xvới Fusion), kèm biện pháp chống4bẫy production (Tests 11, 14) và giải mã5stallncu. - Bài tập 6 (
15%) — Kiểm chứng Toàn trìnhWB-Ch26&OpenTelemetryTracing: Chạy trọn bộuv lock --check,ruff,mypy,18/18 pytest(cảOMP_NUM_THREADS=1và mặc định đa luồng) và xuấtartifacts/ch26_wb26_results.json(Tests 01–03, 15–17).
| Tiêu chí Rubric | Đạt (Pass, 60–74%) |
Khá (Merit, 75–84%) |
Xuất sắc (Distinction, 85–100%) |
|---|---|---|---|
Bộ nhớ CUDA & Occupancy (ex1, ex2, ex3) |
Tính đúng 128B coalescing & đệm [32][33] |
Giải thích chính xác gcd(s, 32) và SIMT divergence |
Định lượng đủ 4 giới hạn SM (256-reg granularity, Little's Law) & audit .cu |
Roofline, CUDA Graphs & CPU Bench (ex4, ex5) |
Tính đúng điểm gãy \(I^*\) và Decode vs Prefill |
Dẫn xuất đúng \(B^*\) và mô phỏng CUDA Graph 3.46x |
Đối chiếu sắc bén mô hình GPU với đo thật PyTorch CPU (1.90x stride, 20.15x GEMM) & ncu 5-stall triage |
Chất lượng Mã & Kiểm chứng (ex6, WB-Ch26) |
Vượt qua 18/18 pytest, xuất JSON artifact |
Đạt 0 lỗi ruff/mypy, khóa uv.lock & AST gate |
Xuất chuẩn 6 KPI, 4 bar, 4 bảng workbench_panels & 6 span OpenTelemetry |
H100 SXM (BF16, Peak=989 TFLOPS) Attainable Throughput: Decode Batch vs Prefill
Memory Transaction Amplification: Global 128B Coalescing & 32-Bank SRAM
SM Active Occupancy & SIMT Warp Divergence Efficiency (%)
Real PyTorch 2.15.0+cpu CPU MatMul Scaling (1024x1024, GFLOP/s)
GPU Hardware Architecture Registry: Ada RTX 4090 vs Hopper H100 vs Blackwell B200
| GPU & Architecture | SMs / Max Warps / TMEM | Memory Bandwidth | Dense Peak Compute & Ridge I* (FLOP/B) |
|---|---|---|---|
| RTX_4090 (Ada Lovelace (AD102)) | 128 SMs / 48 warps / 0 KB TMEM | 1,008 GB/s (24 GB GDDR6X (384-bit)) | FP32: 82.6 TF (I=81.9) | BF16: 165.2 TF (I=163.9) | FP8: 330.3 TF (I*=327.7) [Dense; FP8=330.3 TF FP32 Acc / 660.6 TF FP16 Acc; 2:4 Sparse=2x] |
| H100_SXM (Hopper (GH100 SXM5)) | 132 SMs / 64 warps / 0 KB TMEM | 3,350 GB/s (80 GB HBM3 (5120-bit)) | FP32: 67.0 TF (I=20.0) | BF16: 989.0 TF (I=295.2) | FP8: 1,979.0 TF (I*=590.7) [Dense; 2:4 Sparse=2x; wgmma 4-warp] |
| B200_SXM (Blackwell (GB100 SXM)) | 148 SMs / 64 warps / 256 KB TMEM | 8,000 GB/s (180 GB usable HBM3e (192 GB raw, 8192-bit)) | FP32: 75.0 TF (I=9.4) | BF16: 2,250.0 TF (I=281.2) | FP8: 4,500.0 TF (I=562.5) | NVFP4: 9,000.0 TF (I=1125.0) [Dense, ~75 TF FP32; 2:4 Sparse=2x; tcgen05.mma single-thread; NVFP4 16-elem FP8-E4M3 vs MXFP4 32-elem UE8M0] |
Roofline Model Analysis: LLM Decode (Batch 1..512) vs Prefill (H100 BF16 vs B200 NVFP4)
| Stage / Workload (FFN 8192x28672) | Arithmetic Intensity (BF16 vs NVFP4 bpe=0.5) | H100 BF16 (I*=295.2) | B200 NVFP4 (I*=1125.0) |
|---|---|---|---|
| RMSNorm / Elementwise | BF16=1.00 | NVFP4=4.00 | 3.35 TF (memory_bound) | 32.00 TF (memory_bound) |
| Decode_FFN_B=1 | BF16=1.00 | NVFP4=4.00 | 3.35 TF (0.3%, memory_bound) | 32.00 TF (0.4%, memory_bound) |
| Decode_FFN_B=8 | BF16=7.99 | NVFP4=31.96 | 26.77 TF (2.7%, memory_bound) | 255.68 TF (2.8%, memory_bound) |
| Decode_FFN_B=64 | BF16=63.36 | NVFP4=253.45 | 212.27 TF (21.5%, memory_bound) | 2027.63 TF (22.5%, memory_bound) |
| Decode_FFN_B=320 | BF16=304.70 | NVFP4=1218.79 | 989.00 TF (100.0%, compute_bound) | 9000.00 TF (100.0%, compute_bound) |
| Decode_FFN_B=512 | BF16=473.92 | NVFP4=1895.67 | 989.00 TF (100.0%, compute_bound) | 9000.00 TF (100.0%, compute_bound) |
| Decode GQA 8x (B=1..512, S_kv=4096) | BF16=7.98 | NVFP4=31.94 | 26.75 TF (2.7%, memory_bound) | 255.50 TF (2.8%, memory_bound) |
| Prefill FFN (S=2048) | BF16=1,549.8 | NVFP4=6,199.4 | 989.0 TF (100.0%, compute_bound) | 9000.0 TF (100.0%, compute_bound) |
| Prefill FlashAttention (S=2048) | BF16=910.2 | NVFP4=3,640.9 | 989.0 TF (compute_bound) | 9000.0 TF (compute_bound) |
CUDA Memory Coalescing, 32-Bank Shared Memory, Warp Divergence & SM Occupancy Audit
| Hardware Mechanism / Scenario | Measured Hardware Metric | Efficiency / Utilization | Root Cause & CUDA Cure |
|---|---|---|---|
| Global HBM Coalesced (stride=1) | 1 x 128B line (4 sectors) | 100.0% (3,350 GB/s) | Contiguous SoA warp alignment |
| Global HBM Strided (stride=32) | 32 x 128B lines (32x) | 3.12% (104.7 GB/s) | Convert AoS -> SoA or stage via SMEM tile |
| SMEM Transpose [32][32] Col | 32-way bank conflict | 3.12% (32x stall) | All 32 lanes hit same SRAM bank |
| SMEM Transpose [32][33] Col | 1-way (0 conflicts) | 100.0% (conflict-free) | +1 pad gives gcd(33, 32)=1 |
| SM Occupancy Crash vs Tuned | 4 -> 64 warps/SM | 6.25% -> 100.0% | Fix 128KB SMEM / reg spill via block tuning |
| SIMT Warp Divergence (mod2 / tail) | 80 / 160 cycles | 50.0% / 10.16% | Warp-uniform branch or warp shuffle |
CUDA Graph Launch Timeline (Simulated) & Real Offline PyTorch 2.15+cpu Measurements
| Experiment / Mode | Latency / Throughput | Speedup / Ratio | Execution Scope Note |
|---|---|---|---|
| Eager Host Launch (180 kernels) | 1442.0 us (24.97% GPU util) | 1.00x (75.0% launch bubble) | Analytical CUDA host-GPU dispatch model |
| CUDA Graph Replay (180 nodes) | 416.8 us (86.38% GPU util) | 3.46x vs Eager | Analytical CUDA Graph single launch |
| CUDA Graph + Kernel Fusion (64 nodes) | 351.8 us | 4.10x vs Eager | Analytical Graph + Fusion model |
| PyTorch CPU sum(dim=1) Contig vs Strided (2048x2048) | 0.526 ms vs 1.000 ms | 1.90x strided penalty | REAL CPU_PYTORCH measurement |
| PyTorch CPU MatMul M=1 vs M=256 (1024x1024) | 11.30 -> 227.72 GFLOP/s | 20.1x GFLOP/s scaling | REAL CPU_PYTORCH measurement |
02-track-1-data-science-and-ai/part-06-gpu-cuda-and-triton/labs/ch26-gpu-cuda-roofline-workbench
[build-system]
requires = ["setuptools>=68.0"]
build-backend = "setuptools.build_meta"
[project]
name = "gpu-cuda-roofline-lab"
version = "0.1.0"
description = "WB-Ch26: GPU Hardware Architecture, Roofline Analysis, 128B Coalesced Access, 32-Bank Shared Memory Conflicts, SM Occupancy, CUDA Graphs & PyTorch Contiguity/GEMM Microbenchmarks for T1-P6-U01."
readme = "README.md"
requires-python = ">=3.12"
dependencies = [
"numpy>=1.26",
"opentelemetry-sdk>=1.28",
"pydantic>=2.0",
"torch>=2.5",
]
[project.optional-dependencies]
dev = [
"hypothesis>=6.100",
"mypy>=1.11",
"pytest>=8.0",
"ruff>=0.6",
]
[[tool.uv.index]]
name = "pytorch-cpu"
url = "https://download.pytorch.org/whl/cpu"
explicit = true
[tool.uv.sources]
torch = { index = "pytorch-cpu" }
[tool.setuptools]
package-dir = {"" = "src"}
[tool.setuptools.packages.find]
where = ["src"]
[tool.pytest.ini_options]
pythonpath = ["src"]
testpaths = ["tests"]
addopts = "-v"
[tool.ruff]
line-length = 110
target-version = "py312"
[tool.ruff.lint]
select = ["E", "F", "I", "UP", "B"]
[tool.mypy]
python_version = "3.12"
ignore_missing_imports = true
warn_unused_ignores = true
// Tier-1 Reference CUDA C++ Kernels for WB-Ch26 (T1-P6-U01)
// Covers:
// 1. Coalesced vs. Strided Global HBM Memory Copy (128B cache-line sectors)
// 2. Naive [32][32] vs. Padded [32][33] Shared Memory Matrix Transpose (32-bank conflict removal)
// 3. Warp Shuffle Reduction (__shfl_down_sync) without shared-memory round-trips
// 4. 2D Shared-Memory Tiled GEMM Kernel (with SMEM staging & __syncthreads)
// 5. CUDA Graph Stream Capture Launch Template eliminating host dispatch bubbles
#include <cuda_runtime.h>
#include <stdint.h>
constexpr int kWarpSize = 32;
constexpr int kTileDim = 32;
constexpr int kBlockRows = 8;
// ---------------------------------------------------------------------------
// Kernel 1A: Coalesced Global Memory Copy (stride = 1, 1x 128B transaction/warp)
// ---------------------------------------------------------------------------
__global__ void coalesced_copy_kernel(
const float* __restrict__ src,
float* __restrict__ dst,
int n_elements
) {
const int idx = blockIdx.x * blockDim.x + threadIdx.x;
if (idx < n_elements) {
// Adjacent lanes (lane 0..31) read contiguous 4-byte floats -> single 128B cache line.
dst[idx] = src[idx] * 1.01f + 0.5f;
}
}
// ---------------------------------------------------------------------------
// Kernel 1B: Strided Global Memory Copy (e.g., stride = 32 -> 32x cache-line inflation)
// ---------------------------------------------------------------------------
__global__ void strided_copy_kernel(
const float* __restrict__ src,
float* __restrict__ dst,
int n_logical,
int stride
) {
const int idx = blockIdx.x * blockDim.x + threadIdx.x;
if (idx < n_logical) {
const int64_t strided_idx = static_cast<int64_t>(idx) * stride;
// Each thread in the warp touches a different 128B cache line when stride >= 32.
dst[idx] = src[strided_idx] * 1.01f + 0.5f;
}
}
// ---------------------------------------------------------------------------
// Kernel 2A: Naive Matrix Transpose (32-way Shared Memory Bank Conflict on Col Read)
// ---------------------------------------------------------------------------
__global__ void transpose_naive_smem_kernel(
const float* __restrict__ in_mat,
float* __restrict__ out_mat,
int width,
int height
) {
// WARNING: [32][32] maps column elements (tile[0..31][col]) onto the exact same SRAM bank!
__shared__ float tile[kTileDim][kTileDim];
int x = blockIdx.x * kTileDim + threadIdx.x;
int y = blockIdx.y * kTileDim + threadIdx.y;
for (int j = 0; j < kTileDim; j += kBlockRows) {
if (x < width && (y + j) < height) {
tile[threadIdx.y + j][threadIdx.x] = in_mat[(y + j) * width + x];
}
}
__syncthreads();
x = blockIdx.y * kTileDim + threadIdx.x;
y = blockIdx.x * kTileDim + threadIdx.y;
for (int j = 0; j < kTileDim; j += kBlockRows) {
if (x < height && (y + j) < width) {
// Column-wise read hits 32-way bank conflict across warp lanes!
out_mat[(y + j) * height + x] = tile[threadIdx.x][threadIdx.y + j];
}
}
}
// ---------------------------------------------------------------------------
// Kernel 2B: Conflict-Free Padded Matrix Transpose ([32][33] eliminates all 32-way conflicts)
// ---------------------------------------------------------------------------
__global__ void transpose_padded_smem_kernel(
const float* __restrict__ in_mat,
float* __restrict__ out_mat,
int width,
int height
) {
// +1 column padding shifts row stride to 33 words: gcd(33, 32) == 1 -> 1-way conflict-free!
__shared__ float tile[kTileDim][kTileDim + 1];
int x = blockIdx.x * kTileDim + threadIdx.x;
int y = blockIdx.y * kTileDim + threadIdx.y;
for (int j = 0; j < kTileDim; j += kBlockRows) {
if (x < width && (y + j) < height) {
tile[threadIdx.y + j][threadIdx.x] = in_mat[(y + j) * width + x];
}
}
__syncthreads();
x = blockIdx.y * kTileDim + threadIdx.x;
y = blockIdx.x * kTileDim + threadIdx.y;
for (int j = 0; j < kTileDim; j += kBlockRows) {
if (x < height && (y + j) < width) {
out_mat[(y + j) * height + x] = tile[threadIdx.x][threadIdx.y + j];
}
}
}
// ---------------------------------------------------------------------------
// Kernel 3: Intra-Warp Shuffle Reduction (__shfl_down_sync, zero shared mem inside warp)
// ---------------------------------------------------------------------------
__device__ __forceinline__ float warp_reduce_sum(float val) {
constexpr unsigned int kFullMask = 0xffffffffu;
for (int offset = kWarpSize / 2; offset > 0; offset >>= 1) {
val += __shfl_down_sync(kFullMask, val, offset);
}
return val;
}
__global__ void warp_shuffle_reduce_sum_kernel(
const float* __restrict__ input,
float* __restrict__ block_partial_sums,
int n_elements
) {
__shared__ float warp_sums[kWarpSize];
const int tid = threadIdx.x;
const int global_idx = blockIdx.x * blockDim.x + tid;
const int lane = tid & (kWarpSize - 1);
const int warp_id = tid >> 5;
float val = (global_idx < n_elements) ? input[global_idx] : 0.0f;
val = warp_reduce_sum(val);
if (lane == 0) {
warp_sums[warp_id] = val;
}
__syncthreads();
const int num_warps = (blockDim.x + kWarpSize - 1) / kWarpSize;
val = (tid < num_warps) ? warp_sums[tid] : 0.0f;
if (warp_id == 0) {
val = warp_reduce_sum(val);
if (tid == 0) {
block_partial_sums[blockIdx.x] = val;
}
}
}
// ---------------------------------------------------------------------------
// Kernel 4: 2D Shared-Memory Tiled GEMM (C = A * B)
// Modern Hopper WGMMA + TMA & Blackwell tcgen05.mma + TMEM extend this tiling
// asynchronously across warpgroups and dedicated Tensor Memory (TMEM).
// ---------------------------------------------------------------------------
__global__ void tiled_gemm_smem_kernel(
const float* __restrict__ A,
const float* __restrict__ B,
float* __restrict__ C,
int M,
int N,
int K
) {
__shared__ float As[kTileDim][kTileDim];
__shared__ float Bs[kTileDim][kTileDim + 1];
const int row = blockIdx.y * kTileDim + threadIdx.y;
const int col = blockIdx.x * kTileDim + threadIdx.x;
float acc = 0.0f;
const int num_tiles = (K + kTileDim - 1) / kTileDim;
for (int t = 0; t < num_tiles; ++t) {
const int a_col = t * kTileDim + threadIdx.x;
const int b_row = t * kTileDim + threadIdx.y;
As[threadIdx.y][threadIdx.x] = (row < M && a_col < K) ? A[row * K + a_col] : 0.0f;
Bs[threadIdx.y][threadIdx.x] = (b_row < K && col < N) ? B[b_row * N + col] : 0.0f;
__syncthreads();
#pragma unroll
for (int k = 0; k < kTileDim; ++k) {
acc = fmaf(As[threadIdx.y][k], Bs[k][threadIdx.x], acc);
}
__syncthreads();
}
if (row < M && col < N) {
C[row * N + col] = acc;
}
}
// ---------------------------------------------------------------------------
// Host Helpers: CUDA Graph Capture & Synchronized Multi-Step Replay
// ---------------------------------------------------------------------------
// Captures `num_micro_kernels` launches into `stream`, validates launch errors
// before ending capture, instantiates `out_graph_exec`, and releases the
// temporary `cudaGraph_t` template. Caller owns `out_graph_exec` across steps.
inline cudaError_t capture_decode_graph(
cudaStream_t stream,
const float* d_src,
float* d_dst,
int n_elements,
int num_micro_kernels,
cudaGraphExec_t* out_graph_exec
) {
if (out_graph_exec == nullptr || n_elements <= 0 || num_micro_kernels <= 0) {
return cudaErrorInvalidValue;
}
*out_graph_exec = nullptr;
cudaGraph_t graph = nullptr;
cudaError_t err = cudaStreamBeginCapture(stream, cudaStreamCaptureModeGlobal);
if (err != cudaSuccess) {
return err;
}
const int threads = 256;
const int blocks = (n_elements + threads - 1) / threads;
for (int k = 0; k < num_micro_kernels; ++k) {
coalesced_copy_kernel<<<blocks, threads, 0, stream>>>(d_src, d_dst, n_elements);
}
const cudaError_t launch_err = cudaGetLastError();
const cudaError_t end_err = cudaStreamEndCapture(stream, &graph);
if (launch_err != cudaSuccess) {
if (graph != nullptr) cudaGraphDestroy(graph);
return launch_err;
}
if (end_err != cudaSuccess) {
if (graph != nullptr) cudaGraphDestroy(graph);
return end_err;
}
err = cudaGraphInstantiate(out_graph_exec, graph, nullptr, nullptr, 0);
if (graph != nullptr) {
cudaGraphDestroy(graph);
}
return err;
}
// Replays an instantiated `graph_exec` for `num_decode_steps` iterations and
// synchronizes `stream` before returning so caller can safely inspect results
// or invoke `cudaGraphExecDestroy(graph_exec)` without premature destruction.
inline cudaError_t replay_decode_graph(
cudaGraphExec_t graph_exec,
cudaStream_t stream,
int num_decode_steps
) {
if (graph_exec == nullptr || num_decode_steps <= 0) {
return cudaErrorInvalidValue;
}
for (int step = 0; step < num_decode_steps; ++step) {
const cudaError_t launch_err = cudaGraphLaunch(graph_exec, stream);
if (launch_err != cudaSuccess) {
return launch_err;
}
}
const cudaError_t sync_err = cudaStreamSynchronize(stream);
if (sync_err != cudaSuccess) {
return sync_err;
}
return cudaGetLastError();
}
"""Public API for WB-Ch26 (`gpu_cuda_roofline_lab`, Unit `T1-P6-U01`)."""
from __future__ import annotations
from gpu_cuda_roofline_lab.cuda_memory_and_occupancy import (
SM_ARCHITECTURE_PROFILES,
BankConflictReport,
CoalescingReport,
CudaKernelStaticAudit,
SMArchitectureProfile,
SMOccupancyReport,
WarpDivergenceReport,
analyze_global_memory_coalescing,
analyze_shared_memory_banks,
audit_cuda_kernel_file,
calculate_sm_occupancy,
get_sm_profile,
simulate_warp_divergence,
)
from gpu_cuda_roofline_lab.hardware_and_roofline import (
FP4_MICROSCALING_FORMATS,
GPU_HARDWARE_SPECS,
PRECISION_BYTES,
BatchCrossoverReport,
CudaGraphLaunchReport,
GPUHardwareSpec,
PyTorchContiguityReport,
PyTorchGemmScaleRow,
PyTorchGemmScalingReport,
RooflinePoint,
analyze_llm_decode_vs_prefill_roofline,
benchmark_pytorch_contiguity_vs_strided,
benchmark_pytorch_cpu_gemm_scaling,
compute_elementwise_roofline,
compute_gemm_roofline,
compute_ridge_point,
create_in_memory_otel_tracer,
get_gpu_spec,
run_full_ch26_wb26_benchmark,
simulate_cuda_graph_launch_overhead,
solve_gemm_crossover_batch,
)
__all__ = [
"BatchCrossoverReport",
"BankConflictReport",
"CoalescingReport",
"CudaGraphLaunchReport",
"CudaKernelStaticAudit",
"FP4_MICROSCALING_FORMATS",
"GPUHardwareSpec",
"GPU_HARDWARE_SPECS",
"PRECISION_BYTES",
"PyTorchContiguityReport",
"PyTorchGemmScaleRow",
"PyTorchGemmScalingReport",
"RooflinePoint",
"SMArchitectureProfile",
"SMOccupancyReport",
"SM_ARCHITECTURE_PROFILES",
"WarpDivergenceReport",
"analyze_global_memory_coalescing",
"analyze_llm_decode_vs_prefill_roofline",
"analyze_shared_memory_banks",
"audit_cuda_kernel_file",
"benchmark_pytorch_contiguity_vs_strided",
"benchmark_pytorch_cpu_gemm_scaling",
"calculate_sm_occupancy",
"compute_elementwise_roofline",
"compute_gemm_roofline",
"compute_ridge_point",
"create_in_memory_otel_tracer",
"get_gpu_spec",
"get_sm_profile",
"run_full_ch26_wb26_benchmark",
"simulate_cuda_graph_launch_overhead",
"simulate_warp_divergence",
"solve_gemm_crossover_batch",
]
"""GPU Hardware Spec Registry (H100 SXM, B200 SXM, RTX 4090), Exact Roofline Calculator,
LLM Decode-vs-Prefill Batch Crossover, CUDA Graph Launch Simulator, Real PyTorch CPU
Contiguity/GEMM Microbenchmarks, and OpenTelemetry Span Instrumentation (`T1-P6-U01`).
"""
from __future__ import annotations
import time
from pathlib import Path
from typing import Any, Literal
import numpy as np
import torch
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
from opentelemetry.trace import Status, StatusCode, Tracer
from pydantic import BaseModel, ConfigDict, Field
try:
from opentelemetry.sdk.trace.export import ( # type: ignore[attr-defined]
InMemorySpanExporter,
)
except ImportError: # opentelemetry-sdk >= 1.45
from opentelemetry.sdk.trace.export.in_memory_span_exporter import (
InMemorySpanExporter,
)
from gpu_cuda_roofline_lab.cuda_memory_and_occupancy import (
analyze_global_memory_coalescing,
analyze_shared_memory_banks,
audit_cuda_kernel_file,
calculate_sm_occupancy,
simulate_warp_divergence,
)
PrecisionMode = Literal["FP32", "BF16", "FP8", "NVFP4"]
# ---------------------------------------------------------------------------
# OpenTelemetry Helper (Compatible with opentelemetry-sdk >= 1.45)
# ---------------------------------------------------------------------------
def create_in_memory_otel_tracer(
instrumentation_name: str = "gpu_cuda_roofline_lab",
) -> tuple[TracerProvider, InMemorySpanExporter, Tracer]:
"""Create an isolated TracerProvider + InMemorySpanExporter for deterministic span auditing."""
exporter = InMemorySpanExporter()
provider = TracerProvider()
provider.add_span_processor(SimpleSpanProcessor(exporter))
tracer = provider.get_tracer(instrumentation_name)
return provider, exporter, tracer
# ---------------------------------------------------------------------------
# Strict Pydantic v2 Schemas
# ---------------------------------------------------------------------------
class GPUHardwareSpec(BaseModel):
"""Immutable hardware architecture specification for modern NVIDIA GPUs."""
model_config = ConfigDict(extra="forbid", strict=True)
gpu_name: str
architecture: str
tensor_core_isa: str
memory_tech: str
sm_count: int = Field(..., ge=1)
cuda_cores_per_sm: int = Field(..., ge=32)
tensor_cores_per_sm: int = Field(..., ge=1)
max_threads_per_sm: int = Field(..., ge=32)
max_blocks_per_sm: int = Field(..., ge=1)
registers_per_sm: int = Field(..., ge=1024)
shared_mem_per_sm_kb: float = Field(..., gt=0.0)
tmem_per_sm_kb: float = Field(default=0.0, ge=0.0)
hbm_bandwidth_gb_s: float = Field(..., gt=0.0)
l2_bandwidth_gb_s: float = Field(..., gt=0.0)
peak_tflops: dict[str, float]
supports_tma: bool = False
supports_nvfp4: bool = False
issue_semantics: str = ""
dense_vs_sparse_note: str = ""
fp4_format_note: str = ""
class RooflinePoint(BaseModel):
"""Exact Roofline analytical performance point for a kernel or Transformer stage."""
model_config = ConfigDict(extra="forbid", strict=True)
workload_name: str
gpu_name: str
precision: PrecisionMode
total_flops: int = Field(..., ge=1)
bytes_moved: int = Field(..., ge=1)
arithmetic_intensity: float = Field(..., gt=0.0)
ridge_point: float = Field(..., gt=0.0)
bandwidth_ceiling_tflops: float = Field(..., gt=0.0)
peak_compute_tflops: float = Field(..., gt=0.0)
attainable_tflops: float = Field(..., gt=0.0)
compute_utilization_pct: float = Field(..., gt=0.0, le=100.0)
regime: Literal["memory_bound", "compute_bound"]
class BatchCrossoverReport(BaseModel):
"""LLM Decode batch sweep vs Prefill Roofline analysis and ridge-point crossover."""
model_config = ConfigDict(extra="forbid", strict=True)
gpu_name: str
precision: PrecisionMode
bytes_per_elem: float = Field(..., gt=0.0)
ridge_point_flop_per_byte: float = Field(..., gt=0.0)
analytical_linear_crossover_batch: float = Field(..., gt=0.0)
decode_linear_points: list[RooflinePoint]
decode_attention_points: list[RooflinePoint]
prefill_linear_point: RooflinePoint
prefill_flash_attention_point: RooflinePoint
rmsnorm_point: RooflinePoint
class CudaGraphLaunchReport(BaseModel):
"""Event-timeline comparison between Eager host launch, CUDA Graph, and Graph + Fusion."""
model_config = ConfigDict(extra="forbid", strict=True)
num_eager_kernels: int = Field(..., ge=1)
num_fused_kernels: int = Field(..., ge=1)
cpu_launch_us: float = Field(..., gt=0.0)
gpu_kernel_exec_us: float = Field(..., gt=0.0)
graph_launch_us: float = Field(..., gt=0.0)
graph_node_gap_us: float = Field(..., ge=0.0)
useful_gpu_work_us: float = Field(..., gt=0.0)
eager_total_us: float = Field(..., gt=0.0)
eager_gpu_utilization_pct: float = Field(..., gt=0.0, le=100.0)
eager_launch_bubble_pct: float = Field(..., ge=0.0, le=100.0)
cuda_graph_total_us: float = Field(..., gt=0.0)
cuda_graph_gpu_utilization_pct: float = Field(..., gt=0.0, le=100.0)
cuda_graph_speedup: float = Field(..., gt=0.0)
graph_plus_fusion_total_us: float = Field(..., gt=0.0)
graph_plus_fusion_speedup: float = Field(..., gt=0.0)
class PyTorchContiguityReport(BaseModel):
"""Real offline PyTorch CPU measurement of contiguous vs non-contiguous strided access."""
model_config = ConfigDict(extra="forbid", strict=True)
execution_environment: Literal["CPU_PYTORCH_LOCAL_MEMORY_AND_GEMM_BENCHMARK"]
torch_version: str
rows: int = Field(..., ge=1)
cols: int = Field(..., ge=1)
repeats: int = Field(..., ge=1)
contiguous_is_contiguous: bool
strided_is_contiguous: bool
contiguous_strides: list[int]
strided_strides: list[int]
contiguous_mean_ms: float = Field(..., gt=0.0)
strided_mean_ms: float = Field(..., gt=0.0)
strided_slowdown_factor: float = Field(..., gt=0.0)
contiguous_gb_s: float = Field(..., gt=0.0)
strided_gb_s: float = Field(..., gt=0.0)
numerical_max_abs_diff: float = Field(..., ge=0.0)
class PyTorchGemmScaleRow(BaseModel):
"""Single measured CPU PyTorch matmul throughput row for batch size M."""
model_config = ConfigDict(extra="forbid", strict=True)
m_batch: int = Field(..., ge=1)
k_dim: int = Field(..., ge=1)
n_dim: int = Field(..., ge=1)
flops: int = Field(..., ge=1)
bytes_moved_fp32: int = Field(..., ge=1)
arithmetic_intensity_fp32: float = Field(..., gt=0.0)
mean_ms: float = Field(..., gt=0.0)
measured_gflops: float = Field(..., gt=0.0)
class PyTorchGemmScalingReport(BaseModel):
"""Real offline PyTorch CPU GEMV->GEMM throughput scaling across batch sizes."""
model_config = ConfigDict(extra="forbid", strict=True)
execution_environment: Literal["CPU_PYTORCH_LOCAL_MEMORY_AND_GEMM_BENCHMARK"]
torch_version: str
k_dim: int = Field(..., ge=1)
n_dim: int = Field(..., ge=1)
rows: list[PyTorchGemmScaleRow]
speedup_max_batch_vs_m1_gflops: float = Field(..., gt=0.0)
# ---------------------------------------------------------------------------
# Deterministic GPU Spec Registry
# ---------------------------------------------------------------------------
PRECISION_BYTES: dict[PrecisionMode, float] = {
"FP32": 4.0,
"BF16": 2.0,
"FP8": 1.0,
"NVFP4": 0.5,
}
FP4_MICROSCALING_FORMATS: dict[str, dict[str, Any]] = {
"NVFP4": {
"block_size_elements": 16,
"micro_scale_dtype": "FP8 E4M3",
"tensor_scale_dtype": "FP32",
"nominal_bytes_per_elem": 0.5,
"effective_bytes_per_elem_with_microscale": 0.5625,
"summary": "NVFP4: 16-element block with FP8 E4M3 micro-scale + FP32 tensor scale (bpe=0.5 nominal)",
},
"MXFP4": {
"block_size_elements": 32,
"micro_scale_dtype": "UE8M0",
"tensor_scale_dtype": "none",
"nominal_bytes_per_elem": 0.5,
"effective_bytes_per_elem_with_microscale": 0.53125,
"summary": "OCP MXFP4: 32-element block with UE8M0 power-of-2 scale",
},
}
GPU_HARDWARE_SPECS: dict[str, GPUHardwareSpec] = {
"RTX_4090": GPUHardwareSpec(
gpu_name="RTX_4090",
architecture="Ada Lovelace (AD102)",
tensor_core_isa=(
"4th-Gen Tensor Core (WMMA / mma.sync warp-level, "
"FP8 330.3 TF FP32 Acc vs 660.6 TF FP16 Acc)"
),
memory_tech="24 GB GDDR6X (384-bit)",
sm_count=128,
cuda_cores_per_sm=128,
tensor_cores_per_sm=4,
max_threads_per_sm=1536,
max_blocks_per_sm=24,
registers_per_sm=65536,
shared_mem_per_sm_kb=100.0,
tmem_per_sm_kb=0.0,
hbm_bandwidth_gb_s=1008.0,
l2_bandwidth_gb_s=5200.0,
peak_tflops={"FP32": 82.6, "BF16": 165.2, "FP8": 330.3},
supports_tma=False,
supports_nvfp4=False,
issue_semantics="warp-level mma.sync (32 threads/warp)",
dense_vs_sparse_note=(
"Dense peaks shown (BF16 165.2 TF, FP8 330.3 TF w/ FP32 Acc vs 660.6 TF w/ FP16 Acc); "
"2:4 Structured Sparsity doubles Tensor Core FLOPS (660.6 TF FP8 FP32-Acc / 1,321.2 TF FP16-Acc)."
),
fp4_format_note="No native FP4 Tensor Core (requires software dequantization to FP8/BF16).",
),
"H100_SXM": GPUHardwareSpec(
gpu_name="H100_SXM",
architecture="Hopper (GH100 SXM5)",
tensor_core_isa="4th-Gen Tensor Core (WGMMA 4-warp warpgroup + TMA + Thread Block Clusters)",
memory_tech="80 GB HBM3 (5120-bit)",
sm_count=132,
cuda_cores_per_sm=128,
tensor_cores_per_sm=4,
max_threads_per_sm=2048,
max_blocks_per_sm=32,
registers_per_sm=65536,
shared_mem_per_sm_kb=228.0,
tmem_per_sm_kb=0.0,
hbm_bandwidth_gb_s=3350.0,
l2_bandwidth_gb_s=12000.0,
peak_tflops={"FP32": 67.0, "BF16": 989.0, "FP8": 1979.0},
supports_tma=True,
supports_nvfp4=False,
issue_semantics="4-warp warpgroup wgmma.mma_async (128 threads)",
dense_vs_sparse_note=(
"Dense Tensor Core peaks shown (BF16 989.0 TF, FP8 1,979.0 TF); "
"2:4 Structured Sparsity doubles to 1,979.0 TF BF16 / 3,958.0 TF FP8."
),
fp4_format_note="No native FP4 Tensor Core; supports FP8 E4M3/E5M2.",
),
"B200_SXM": GPUHardwareSpec(
gpu_name="B200_SXM",
architecture="Blackwell (GB100 SXM)",
tensor_core_isa=(
"5th-Gen Tensor Core (tcgen05.mma single-thread issue + TMA + 256KB TMEM + "
"NVFP4 16-elem FP8-E4M3 / OCP MXFP4 32-elem UE8M0)"
),
memory_tech="180 GB usable HBM3e (192 GB raw, 8192-bit)",
sm_count=148,
cuda_cores_per_sm=128,
tensor_cores_per_sm=4,
max_threads_per_sm=2048,
max_blocks_per_sm=32,
registers_per_sm=65536,
shared_mem_per_sm_kb=228.0,
tmem_per_sm_kb=256.0,
hbm_bandwidth_gb_s=8000.0,
l2_bandwidth_gb_s=24000.0,
peak_tflops={"FP32": 75.0, "BF16": 2250.0, "FP8": 4500.0, "NVFP4": 9000.0},
supports_tma=True,
supports_nvfp4=True,
issue_semantics=(
"single-thread issue semantics (1 elected thread for 1-SM/2-SM CTA vs Hopper wgmma 4-warp)"
),
dense_vs_sparse_note=(
"Dense peaks shown (~75 TF FP32 CUDA, 2,250 TF BF16, 4,500 TF FP8, 9,000 TF NVFP4); "
"2:4 Structured Sparsity doubles Tensor Core FLOPS "
"(4,500 TF BF16 / 9,000 TF FP8 / 18,000 TF NVFP4)."
),
fp4_format_note=(
"NVFP4 (16-elem block, FP8 E4M3 micro-scale + FP32 tensor scale, bpe=0.5) vs "
"OCP MXFP4 (32-elem block, UE8M0 scale)."
),
),
}
def get_gpu_spec(gpu_name: str) -> GPUHardwareSpec:
"""Return an immutable GPUHardwareSpec for the requested GPU identifier."""
if gpu_name not in GPU_HARDWARE_SPECS:
valid = ", ".join(sorted(GPU_HARDWARE_SPECS))
raise ValueError(f"Unknown GPU '{gpu_name}'. Expected one of: {valid}")
return GPU_HARDWARE_SPECS[gpu_name]
# ---------------------------------------------------------------------------
# Exact Roofline Model & LLM Decode vs Prefill Analysis
# ---------------------------------------------------------------------------
def compute_ridge_point(spec: GPUHardwareSpec, precision: PrecisionMode) -> float:
"""Compute hardware Roofline ridge point I* = Peak_FLOPS / Bandwidth (FLOP/Byte)."""
if precision not in spec.peak_tflops:
raise ValueError(f"Precision '{precision}' is not supported natively by '{spec.gpu_name}'")
peak_tflops = spec.peak_tflops[precision]
return (peak_tflops * 1000.0) / spec.hbm_bandwidth_gb_s
def _evaluate_roofline(
workload_name: str,
spec: GPUHardwareSpec,
precision: PrecisionMode,
total_flops: int,
bytes_moved: int,
) -> RooflinePoint:
if total_flops < 1 or bytes_moved < 1:
raise ValueError("total_flops and bytes_moved must be >= 1")
if precision not in spec.peak_tflops:
raise ValueError(f"Precision '{precision}' is not supported on '{spec.gpu_name}'")
peak_tflops = spec.peak_tflops[precision]
ridge = compute_ridge_point(spec, precision)
ai = total_flops / bytes_moved
bw_ceiling = (ai * spec.hbm_bandwidth_gb_s) / 1000.0
attainable = min(peak_tflops, bw_ceiling)
util_pct = (attainable / peak_tflops) * 100.0
regime: Literal["memory_bound", "compute_bound"] = "memory_bound" if ai < ridge else "compute_bound"
return RooflinePoint(
workload_name=workload_name,
gpu_name=spec.gpu_name,
precision=precision,
total_flops=total_flops,
bytes_moved=bytes_moved,
arithmetic_intensity=round(ai, 4),
ridge_point=round(ridge, 2),
bandwidth_ceiling_tflops=round(bw_ceiling, 4),
peak_compute_tflops=peak_tflops,
attainable_tflops=round(attainable, 4),
compute_utilization_pct=round(util_pct, 2),
regime=regime,
)
def compute_gemm_roofline(
m_dim: int,
n_dim: int,
k_dim: int,
spec: GPUHardwareSpec,
precision: PrecisionMode = "BF16",
workload_name: str | None = None,
bytes_per_elem: float | None = None,
) -> RooflinePoint:
"""Evaluate exact Roofline point for GEMM (M, K) @ (K, N) -> (M, N)."""
if min(m_dim, n_dim, k_dim) < 1:
raise ValueError("Matrix dimensions M, N, K must all be >= 1")
bpe = PRECISION_BYTES[precision] if bytes_per_elem is None else bytes_per_elem
total_flops = 2 * m_dim * n_dim * k_dim
bytes_moved = max(1, round(bpe * (m_dim * k_dim + k_dim * n_dim + m_dim * n_dim)))
label = workload_name or f"GEMM({m_dim}x{n_dim}x{k_dim})"
return _evaluate_roofline(label, spec, precision, total_flops, bytes_moved)
def compute_elementwise_roofline(
num_elements: int,
flops_per_element: int,
memory_passes: int,
spec: GPUHardwareSpec,
precision: PrecisionMode = "BF16",
workload_name: str = "Elementwise/RMSNorm",
) -> RooflinePoint:
"""Evaluate Roofline point for memory-bound elementwise or normalization ops."""
if num_elements < 1 or flops_per_element < 1 or memory_passes < 1:
raise ValueError("num_elements, flops_per_element, and memory_passes must be >= 1")
bpe = PRECISION_BYTES[precision]
total_flops = num_elements * flops_per_element
bytes_moved = max(1, round(num_elements * memory_passes * bpe))
return _evaluate_roofline(workload_name, spec, precision, total_flops, bytes_moved)
def solve_gemm_crossover_batch(
k_dim: int,
n_dim: int,
bytes_per_elem: float,
ridge_point: float,
) -> float:
"""Solve exact batch M* where GEMM(M, N, K) arithmetic intensity equals ridge_point I*."""
denom = 2.0 * k_dim * n_dim - ridge_point * bytes_per_elem * (k_dim + n_dim)
if denom <= 0.0:
return float("inf")
return (ridge_point * bytes_per_elem * k_dim * n_dim) / denom
def analyze_llm_decode_vs_prefill_roofline(
gpu_name: str = "H100_SXM",
precision: PrecisionMode = "BF16",
hidden_dim: int = 8192,
ffn_dim: int = 28672,
num_q_heads: int = 64,
num_kv_heads: int = 8,
head_dim: int = 128,
kv_seq_len: int = 4096,
prefill_seq_len: int = 2048,
batch_sizes: tuple[int, ...] = (1, 4, 8, 32, 64, 128, 256, 320, 512),
) -> BatchCrossoverReport:
"""Compare LLM Decode GEMV/GQA-Attention across batch sizes against Compute-Bound Prefill."""
spec = get_gpu_spec(gpu_name)
bpe = PRECISION_BYTES[precision]
ridge = compute_ridge_point(spec, precision)
gqa_group = max(1, num_q_heads // num_kv_heads)
decode_linear_points: list[RooflinePoint] = []
decode_attention_points: list[RooflinePoint] = []
for batch in batch_sizes:
lin_pt = compute_gemm_roofline(
m_dim=batch,
n_dim=ffn_dim,
k_dim=hidden_dim,
spec=spec,
precision=precision,
workload_name=f"Decode_FFN_B={batch}",
)
decode_linear_points.append(lin_pt)
# GQA Attention Decode across num_kv_heads:
# Per sequence in batch: KV cache reads = 2 * num_kv_heads * kv_seq_len * head_dim elements
# Q + O activation traffic = 2 * num_q_heads * head_dim elements
# Total FLOPs (QK^T + AV) = 4 * batch * num_q_heads * kv_seq_len * head_dim
attn_flops = 4 * batch * num_q_heads * kv_seq_len * head_dim
kv_cache_elems = batch * 2 * num_kv_heads * kv_seq_len * head_dim
qo_elems = batch * 2 * num_q_heads * head_dim
attn_bytes = max(1, round(bpe * (kv_cache_elems + qo_elems)))
attn_pt = _evaluate_roofline(
workload_name=f"Decode_GQA{gqa_group}x_B={batch}_S={kv_seq_len}",
spec=spec,
precision=precision,
total_flops=attn_flops,
bytes_moved=attn_bytes,
)
decode_attention_points.append(attn_pt)
prefill_lin = compute_gemm_roofline(
m_dim=prefill_seq_len,
n_dim=ffn_dim,
k_dim=hidden_dim,
spec=spec,
precision=precision,
workload_name=f"Prefill_FFN_S={prefill_seq_len}",
)
# Causal FlashAttention prefill (no materialized SxS HBM matrix):
# FLOPs (causal factor ~0.5 on 4 * H * S^2 * d) = 2 * num_q_heads * S^2 * d_h
# HBM traffic (Q, K, V read + O write) = 4 * num_q_heads * S * d_h (MHA) or (2H_q + 2H_kv)*S*d_h
prefill_attn_flops = 2 * num_q_heads * prefill_seq_len * prefill_seq_len * head_dim
prefill_attn_elems = (2 * num_q_heads + 2 * num_kv_heads) * prefill_seq_len * head_dim
prefill_attn_bytes = max(1, round(bpe * prefill_attn_elems))
prefill_attn = _evaluate_roofline(
workload_name=f"Prefill_FlashAttn_S={prefill_seq_len}",
spec=spec,
precision=precision,
total_flops=prefill_attn_flops,
bytes_moved=prefill_attn_bytes,
)
rmsnorm = compute_elementwise_roofline(
num_elements=prefill_seq_len * hidden_dim,
flops_per_element=4,
memory_passes=2,
spec=spec,
precision=precision,
workload_name="RMSNorm_Decode_or_Tokenwise",
)
crossover_b = solve_gemm_crossover_batch(
k_dim=hidden_dim,
n_dim=ffn_dim,
bytes_per_elem=bpe,
ridge_point=ridge,
)
return BatchCrossoverReport(
gpu_name=gpu_name,
precision=precision,
bytes_per_elem=bpe,
ridge_point_flop_per_byte=round(ridge, 2),
analytical_linear_crossover_batch=round(crossover_b, 2),
decode_linear_points=decode_linear_points,
decode_attention_points=decode_attention_points,
prefill_linear_point=prefill_lin,
prefill_flash_attention_point=prefill_attn,
rmsnorm_point=rmsnorm,
)
# ---------------------------------------------------------------------------
# CUDA Graph vs Eager Launch-Overhead Event Timeline Simulator
# ---------------------------------------------------------------------------
def simulate_cuda_graph_launch_overhead(
num_eager_kernels: int = 180,
cpu_launch_us: float = 8.0,
gpu_kernel_exec_us: float = 2.0,
graph_launch_us: float = 12.0,
graph_node_gap_us: float = 0.25,
num_fused_kernels: int = 64,
) -> CudaGraphLaunchReport:
"""Simulate exact CPU-GPU dispatch timeline for Eager, CUDA Graph, and Graph + Fusion."""
if num_eager_kernels < 1 or num_fused_kernels < 1:
raise ValueError("Kernel counts must be >= 1")
if cpu_launch_us <= 0.0 or gpu_kernel_exec_us <= 0.0 or graph_launch_us <= 0.0:
raise ValueError("Latencies must be > 0")
# Eager dispatch timeline: kernel i finishes CPU enqueue at (i+1)*cpu_launch_us
# and starts on GPU at max(cpu_ready_i, gpu_free_prev).
gpu_free = 0.0
for idx in range(num_eager_kernels):
cpu_ready = (idx + 1) * cpu_launch_us
start_t = max(cpu_ready, gpu_free)
gpu_free = start_t + gpu_kernel_exec_us
eager_total_us = gpu_free
useful_gpu_work_us = num_eager_kernels * gpu_kernel_exec_us
eager_util_pct = (useful_gpu_work_us / eager_total_us) * 100.0
eager_bubble_pct = 100.0 - eager_util_pct
# CUDA Graph: single host launch `graph_launch_us`, then hardware queue dispatches nodes back-to-back
graph_total_us = (
graph_launch_us
+ num_eager_kernels * gpu_kernel_exec_us
+ max(0, num_eager_kernels - 1) * graph_node_gap_us
)
graph_util_pct = min(100.0, (useful_gpu_work_us / graph_total_us) * 100.0)
graph_speedup = eager_total_us / graph_total_us
# CUDA Graph + Kernel Fusion (same useful compute condensed into fewer nodes + lower gap/overhead)
fused_exec_us = useful_gpu_work_us * 0.90
graph_fused_total_us = graph_launch_us + fused_exec_us + max(0, num_fused_kernels - 1) * graph_node_gap_us
graph_fused_speedup = eager_total_us / graph_fused_total_us
return CudaGraphLaunchReport(
num_eager_kernels=num_eager_kernels,
num_fused_kernels=num_fused_kernels,
cpu_launch_us=cpu_launch_us,
gpu_kernel_exec_us=gpu_kernel_exec_us,
graph_launch_us=graph_launch_us,
graph_node_gap_us=graph_node_gap_us,
useful_gpu_work_us=round(useful_gpu_work_us, 2),
eager_total_us=round(eager_total_us, 2),
eager_gpu_utilization_pct=round(eager_util_pct, 2),
eager_launch_bubble_pct=round(eager_bubble_pct, 2),
cuda_graph_total_us=round(graph_total_us, 2),
cuda_graph_gpu_utilization_pct=round(graph_util_pct, 2),
cuda_graph_speedup=round(graph_speedup, 2),
graph_plus_fusion_total_us=round(graph_fused_total_us, 2),
graph_plus_fusion_speedup=round(graph_fused_speedup, 2),
)
# ---------------------------------------------------------------------------
# Real Offline PyTorch 2.15+cpu Contiguity & GEMM Scaling Microbenchmarks
# ---------------------------------------------------------------------------
def benchmark_pytorch_contiguity_vs_strided(
rows: int = 2048,
cols: int = 2048,
repeats: int = 12,
seed: int = 42,
) -> PyTorchContiguityReport:
"""Measure real PyTorch CPU row reduction latency on contiguous vs transposed non-contiguous views."""
if rows < 32 or cols < 32 or repeats < 3:
raise ValueError("rows/cols must be >= 32 and repeats >= 3")
gen = torch.Generator(device="cpu").manual_seed(seed)
x = torch.randn((rows, cols), dtype=torch.float32, generator=gen)
# Create an identical-content contiguous matrix y and its transposed non-contiguous view x_t
# so both operations reduce the exact same logical rows `(rows, cols) -> (rows,)`.
x_t = x.t()
y_contig = x_t.contiguous()
# Multi-pass warmup stabilizes OpenMP thread pool & CPU frequency scaling
for _ in range(4):
_ = y_contig.sum(dim=1)
_ = x_t.sum(dim=1)
t0 = time.perf_counter_ns()
out_c = torch.empty((rows,), dtype=torch.float32)
for _ in range(repeats):
out_c = y_contig.sum(dim=1)
t1 = time.perf_counter_ns()
out_s = torch.empty((rows,), dtype=torch.float32)
for _ in range(repeats):
out_s = x_t.sum(dim=1)
t2 = time.perf_counter_ns()
contig_ms = max(1e-4, (t1 - t0) / (repeats * 1_000_000.0))
strided_ms = max(1e-4, (t2 - t1) / (repeats * 1_000_000.0))
bytes_read = rows * cols * 4
contig_gb_s = (bytes_read / (contig_ms * 1e-3)) / 1e9
strided_gb_s = (bytes_read / (strided_ms * 1e-3)) / 1e9
max_diff = float(torch.max(torch.abs(out_c - out_s)).item())
return PyTorchContiguityReport(
execution_environment="CPU_PYTORCH_LOCAL_MEMORY_AND_GEMM_BENCHMARK",
torch_version=torch.__version__,
rows=rows,
cols=cols,
repeats=repeats,
contiguous_is_contiguous=y_contig.is_contiguous(),
strided_is_contiguous=x_t.is_contiguous(),
contiguous_strides=list(y_contig.stride()),
strided_strides=list(x_t.stride()),
contiguous_mean_ms=round(contig_ms, 4),
strided_mean_ms=round(strided_ms, 4),
strided_slowdown_factor=round(strided_ms / contig_ms, 2),
contiguous_gb_s=round(contig_gb_s, 2),
strided_gb_s=round(strided_gb_s, 2),
numerical_max_abs_diff=round(max_diff, 8),
)
def benchmark_pytorch_cpu_gemm_scaling(
batch_sizes: tuple[int, ...] = (1, 8, 64, 256),
k_dim: int = 1024,
n_dim: int = 1024,
repeats: int = 15,
seed: int = 42,
) -> PyTorchGemmScalingReport:
"""Measure real PyTorch CPU `torch.matmul` GFLOP/s scaling from GEMV (M=1) to GEMM (M=256)."""
if k_dim < 16 or n_dim < 16 or repeats < 3:
raise ValueError("k_dim/n_dim must be >= 16 and repeats >= 3")
gen = torch.Generator(device="cpu").manual_seed(seed)
weight = torch.randn((k_dim, n_dim), dtype=torch.float32, generator=gen)
rows_out: list[PyTorchGemmScaleRow] = []
for m_batch in batch_sizes:
act = torch.randn((m_batch, k_dim), dtype=torch.float32, generator=gen)
# Multi-pass warmup stabilizes BLAS packing and CPU OpenMP threads
for _ in range(3):
_ = torch.matmul(act, weight)
t0 = time.perf_counter_ns()
for _ in range(repeats):
_ = torch.matmul(act, weight)
t1 = time.perf_counter_ns()
mean_s = max(1e-9, (t1 - t0) / (repeats * 1e9))
flops = 2 * m_batch * k_dim * n_dim
bytes_fp32 = 4 * (m_batch * k_dim + k_dim * n_dim + m_batch * n_dim)
ai = flops / bytes_fp32
gflops = flops / (mean_s * 1e9)
rows_out.append(
PyTorchGemmScaleRow(
m_batch=m_batch,
k_dim=k_dim,
n_dim=n_dim,
flops=flops,
bytes_moved_fp32=bytes_fp32,
arithmetic_intensity_fp32=round(ai, 4),
mean_ms=round(mean_s * 1000.0, 4),
measured_gflops=round(gflops, 2),
)
)
speedup = rows_out[-1].measured_gflops / max(1e-9, rows_out[0].measured_gflops)
return PyTorchGemmScalingReport(
execution_environment="CPU_PYTORCH_LOCAL_MEMORY_AND_GEMM_BENCHMARK",
torch_version=torch.__version__,
k_dim=k_dim,
n_dim=n_dim,
rows=rows_out,
speedup_max_batch_vs_m1_gflops=round(speedup, 2),
)
# ---------------------------------------------------------------------------
# End-to-End WB-Ch26 Benchmark Orchestrator + `workbench_panels` Builder
# ---------------------------------------------------------------------------
def _default_kernel_path() -> Path:
return Path(__file__).resolve().parents[2] / "cuda_kernels" / "01_memory_and_gemm_kernels.cu"
def run_full_ch26_wb26_benchmark(seed: int = 42, quick: bool = False) -> dict[str, Any]:
"""Run all analytical GPU hardware models, `.cu` static audit, PyTorch CPU benchmarks,
and OpenTelemetry span tracing; return serializable JSON payload with `workbench_panels`.
"""
np.random.seed(seed)
torch.manual_seed(seed)
provider, exporter, tracer = create_in_memory_otel_tracer()
# 1. Roofline Analysis across H100_SXM, B200_SXM, RTX_4090
with tracer.start_as_current_span("gpu.roofline.sweep") as span:
h100_bf16 = analyze_llm_decode_vs_prefill_roofline("H100_SXM", "BF16")
h100_fp8 = analyze_llm_decode_vs_prefill_roofline("H100_SXM", "FP8")
b200_bf16 = analyze_llm_decode_vs_prefill_roofline("B200_SXM", "BF16")
b200_nvfp4 = analyze_llm_decode_vs_prefill_roofline("B200_SXM", "NVFP4")
rtx4090_bf16 = analyze_llm_decode_vs_prefill_roofline("RTX_4090", "BF16")
span.set_attribute("gpu.h100.bf16_ridge", h100_bf16.ridge_point_flop_per_byte)
span.set_attribute("gpu.b200.nvfp4_ridge", b200_nvfp4.ridge_point_flop_per_byte)
span.set_attribute("gpu.h100.crossover_batch", h100_bf16.analytical_linear_crossover_batch)
span.set_status(Status(StatusCode.OK))
# 2. Coalesced vs Strided Global HBM Access
with tracer.start_as_current_span("gpu.memory.coalescing_audit") as span:
coal_s1 = analyze_global_memory_coalescing(
stride_elements=1, element_bytes=4, peak_hbm_bw_gb_s=3350.0
)
coal_s4 = analyze_global_memory_coalescing(
stride_elements=4, element_bytes=4, peak_hbm_bw_gb_s=3350.0
)
coal_s32 = analyze_global_memory_coalescing(
stride_elements=32, element_bytes=4, peak_hbm_bw_gb_s=3350.0
)
span.set_attribute("coalescing.stride32.cache_line_amp", coal_s32.cache_line_amplification)
span.set_attribute("coalescing.stride32.sector_amp", coal_s32.sector_amplification)
span.set_status(Status(StatusCode.OK))
# 3. 32-Bank Shared Memory Conflicts ([32][32] vs [32][33])
with tracer.start_as_current_span("gpu.smem.bank_conflict_audit") as span:
smem_col_naive = analyze_shared_memory_banks(tile_dim=32, padding=0, access_axis="column")
smem_col_padded = analyze_shared_memory_banks(tile_dim=32, padding=1, access_axis="column")
smem_row_naive = analyze_shared_memory_banks(tile_dim=32, padding=0, access_axis="row")
span.set_attribute("smem.naive_col.conflict_ways", smem_col_naive.conflict_ways)
span.set_attribute("smem.padded_col.conflict_ways", smem_col_padded.conflict_ways)
span.set_status(Status(StatusCode.OK))
# 4. Warp Divergence & SM Occupancy Cliffs
with tracer.start_as_current_span("gpu.occupancy.cliff_audit") as span:
div_uniform = simulate_warp_divergence("uniform", branch_a_cycles=40, branch_b_cycles=40)
div_mod2 = simulate_warp_divergence("even_odd_mod2", branch_a_cycles=40, branch_b_cycles=40)
div_tail = simulate_warp_divergence("single_lane_tail", branch_a_cycles=12, branch_b_cycles=148)
occ_optimal = calculate_sm_occupancy(
"H100_SXM", threads_per_block=256, registers_per_thread=32, shared_mem_per_block_kb=16.0
)
occ_reg64 = calculate_sm_occupancy(
"H100_SXM", threads_per_block=256, registers_per_thread=64, shared_mem_per_block_kb=16.0
)
occ_reg128 = calculate_sm_occupancy(
"H100_SXM", threads_per_block=256, registers_per_thread=128, shared_mem_per_block_kb=16.0
)
occ_crash = calculate_sm_occupancy(
"H100_SXM", threads_per_block=128, registers_per_thread=128, shared_mem_per_block_kb=128.0
)
span.set_attribute("occupancy.optimal_pct", occ_optimal.occupancy_pct)
span.set_attribute("occupancy.crash_pct", occ_crash.occupancy_pct)
span.set_status(Status(StatusCode.OK))
# 5. CUDA Graph Launch Overhead Simulator
with tracer.start_as_current_span("gpu.cuda_graph.timeline_sim") as span:
cuda_graph = simulate_cuda_graph_launch_overhead()
span.set_attribute("cuda_graph.speedup", cuda_graph.cuda_graph_speedup)
span.set_attribute("cuda_graph.fusion_speedup", cuda_graph.graph_plus_fusion_speedup)
span.set_status(Status(StatusCode.OK))
# 6. Static `.cu` Kernel Audit + Real PyTorch 2.15+cpu Benchmarks
with tracer.start_as_current_span("cpu.pytorch.microbenchmarks") as span:
cu_audit = audit_cuda_kernel_file(_default_kernel_path())
contig_rows = 1024 if quick else 2048
contig_repeats = 6 if quick else 12
gemm_repeats = 6 if quick else 15
pt_contiguity = benchmark_pytorch_contiguity_vs_strided(
rows=contig_rows, cols=contig_rows, repeats=contig_repeats, seed=seed
)
pt_gemm = benchmark_pytorch_cpu_gemm_scaling(
batch_sizes=(1, 8, 64, 256), k_dim=1024, n_dim=1024, repeats=gemm_repeats, seed=seed
)
span.set_attribute("cpu.pytorch.strided_slowdown", pt_contiguity.strided_slowdown_factor)
span.set_attribute("cpu.pytorch.gemm_m256_gflops", pt_gemm.rows[-1].measured_gflops)
span.set_status(Status(StatusCode.OK))
spans = exporter.get_finished_spans()
provider.shutdown()
# Extract key Roofline points for workbench panels
dec_b1 = next(p for p in h100_bf16.decode_linear_points if p.workload_name == "Decode_FFN_B=1")
dec_b8 = next(p for p in h100_bf16.decode_linear_points if p.workload_name == "Decode_FFN_B=8")
dec_b64 = next(p for p in h100_bf16.decode_linear_points if p.workload_name == "Decode_FFN_B=64")
dec_b320 = next(p for p in h100_bf16.decode_linear_points if p.workload_name == "Decode_FFN_B=320")
prefill_lin = h100_bf16.prefill_linear_point
rmsnorm_pt = h100_bf16.rmsnorm_point
ridge_h100 = h100_bf16.ridge_point_flop_per_byte
ridge_b200 = b200_nvfp4.ridge_point_flop_per_byte
kpis = [
{
"id": "kpi_ridge_points",
"label": "Roofline Ridge Point I* (H100 BF16 vs B200 NVFP4)",
"value": f"{ridge_h100:.1f} vs {ridge_b200:.1f}",
"unit": "FLOP/Byte",
"status": "ok",
"detail": (
"H100 SXM (3.35 TB/s, 989 TF BF16) vs B200 SXM (8.0 TB/s HBM3e, 9,000 TF NVFP4); "
f"H100 FFN crossover B*={h100_bf16.analytical_linear_crossover_batch:.0f} tokens."
),
},
{
"id": "kpi_coalescing_amplification",
"label": "Global HBM Coalescing Penalty (Stride 32 vs 1)",
"value": f"{coal_s32.cache_line_amplification:.0f}x Cache-Line",
"unit": f"({coal_s32.sector_amplification:.0f}x L2 Sector)",
"status": "warn",
"detail": (
f"Strided warp reads 4,096B (32 lines) for 128B useful "
f"({coal_s32.cache_line_efficiency * 100:.2f}% eff); "
f"real PyTorch CPU strided sum(dim=1) slows "
f"{pt_contiguity.strided_slowdown_factor:.2f}x."
),
},
{
"id": "kpi_smem_bank_conflict",
"label": "SMEM 32-Bank Transpose Conflict ([32][32] -> [32][33])",
"value": f"{smem_col_naive.conflict_ways}-way -> {smem_col_padded.conflict_ways}-way",
"unit": f"({smem_col_padded.bank_efficiency * 100:.0f}% eff)",
"status": "ok",
"detail": (
"Adding +1 column pad makes gcd(33, 32)=1, eliminating 32x SRAM bank "
"serialization on column reads."
),
},
{
"id": "kpi_sm_occupancy_recovery",
"label": "H100 SM Occupancy Recovery (128KB SMEM Crash -> Tuned)",
"value": f"{occ_crash.occupancy_pct:.2f}% -> {occ_optimal.occupancy_pct:.0f}%",
"unit": f"({occ_crash.active_warps_per_sm} -> {occ_optimal.active_warps_per_sm} warps)",
"status": "ok",
"detail": (
f"128KB SMEM + 128 thr/blk starves Little's Law "
f"(4 < {occ_crash.required_warps_littles_law} warps); "
"256 thr/blk, 32 regs, 16KB SMEM reaches 100% occupancy."
),
},
{
"id": "kpi_decode_vs_prefill_tflops",
"label": "H100 BF16 Attainable TFLOPS (Decode B=1 -> Prefill)",
"value": f"{dec_b1.attainable_tflops:.2f} -> {prefill_lin.attainable_tflops:.0f}",
"unit": "TFLOPS",
"status": "ok",
"detail": (
f"Decode B=1 sits memory-bound at AI={dec_b1.arithmetic_intensity:.2f} "
f"({dec_b1.compute_utilization_pct:.2f}% util); "
f"Prefill S=2048 hits AI={prefill_lin.arithmetic_intensity:.0f} (100% peak)."
),
},
{
"id": "kpi_cuda_graph_speedup",
"label": "CUDA Graph + Fusion Step Speedup (180 Micro-Kernels)",
"value": (
f"{cuda_graph.cuda_graph_speedup:.2f}x / "
f"{cuda_graph.graph_plus_fusion_speedup:.2f}x"
),
"unit": f"({cuda_graph.eager_total_us:.0f} -> {cuda_graph.cuda_graph_total_us:.0f} us)",
"status": "ok",
"detail": (
f"Eliminates {cuda_graph.eager_launch_bubble_pct:.1f}% CPU host launch bubble "
f"(GPU util {cuda_graph.eager_gpu_utilization_pct:.1f}% -> "
f"{cuda_graph.cuda_graph_gpu_utilization_pct:.1f}%)."
),
},
]
bars = [
{
"id": "bar_roofline_decode_to_prefill",
"title": "H100 SXM (BF16, Peak=989 TFLOPS) Attainable Throughput: Decode Batch vs Prefill",
"metric_label": "Attainable TFLOPS",
"items": [
{
"label": "rmsnorm_ai_2",
"value": rmsnorm_pt.attainable_tflops,
"display": (
f"RMSNorm (AI={rmsnorm_pt.arithmetic_intensity:.1f}): "
f"{rmsnorm_pt.attainable_tflops:.2f} TFLOPS"
),
"css_class": "is-slow",
},
{
"label": "decode_b1",
"value": dec_b1.attainable_tflops,
"display": (
f"Decode B=1 (AI={dec_b1.arithmetic_intensity:.2f}): "
f"{dec_b1.attainable_tflops:.2f} TFLOPS"
),
"css_class": "is-slow",
},
{
"label": "decode_b8",
"value": dec_b8.attainable_tflops,
"display": (
f"Decode B=8 (AI={dec_b8.arithmetic_intensity:.2f}): "
f"{dec_b8.attainable_tflops:.2f} TFLOPS"
),
"css_class": "is-slow",
},
{
"label": "decode_b64",
"value": dec_b64.attainable_tflops,
"display": (
f"Decode B=64 (AI={dec_b64.arithmetic_intensity:.1f}): "
f"{dec_b64.attainable_tflops:.1f} TFLOPS"
),
"css_class": "is-mid",
},
{
"label": "decode_b320",
"value": dec_b320.attainable_tflops,
"display": (
f"Decode B=320 (AI={dec_b320.arithmetic_intensity:.1f}): "
f"{dec_b320.attainable_tflops:.1f} TFLOPS"
),
"css_class": "is-fast",
},
{
"label": "prefill_s2048",
"value": prefill_lin.attainable_tflops,
"display": (
f"Prefill S=2048 (AI={prefill_lin.arithmetic_intensity:.0f}): "
f"{prefill_lin.attainable_tflops:.1f} TFLOPS"
),
"css_class": "is-fast",
},
],
},
{
"id": "bar_memory_transaction_amplification",
"title": "Memory Transaction Amplification: Global 128B Coalescing & 32-Bank SRAM",
"metric_label": "Transaction / Serialization Factor (x)",
"items": [
{
"label": "global_coalesced_s1",
"value": coal_s1.cache_line_amplification,
"display": (
f"Global Coalesced (stride=1): "
f"{coal_s1.cache_line_amplification:.1f}x (100% eff)"
),
"css_class": "is-fast",
},
{
"label": "global_strided_s4",
"value": coal_s4.cache_line_amplification,
"display": (
f"Global Strided (stride=4): "
f"{coal_s4.cache_line_amplification:.1f}x (4 lines)"
),
"css_class": "is-mid",
},
{
"label": "global_strided_s32",
"value": coal_s32.cache_line_amplification,
"display": (
f"Global Strided (stride=32): "
f"{coal_s32.cache_line_amplification:.1f}x (32 lines)"
),
"css_class": "is-slow",
},
{
"label": "smem_padded_32x33",
"value": float(smem_col_padded.conflict_ways),
"display": (
f"SMEM Transpose [32][33] Col: "
f"{smem_col_padded.conflict_ways}-way (0 conflicts)"
),
"css_class": "is-fast",
},
{
"label": "smem_naive_32x32",
"value": float(smem_col_naive.conflict_ways),
"display": (
f"SMEM Transpose [32][32] Col: "
f"{smem_col_naive.conflict_ways}-way bank conflict"
),
"css_class": "is-slow",
},
],
},
{
"id": "bar_occupancy_and_simt_efficiency",
"title": "SM Active Occupancy & SIMT Warp Divergence Efficiency (%)",
"metric_label": "Utilization / Efficiency (%)",
"items": [
{
"label": "occ_optimal_reg32",
"value": occ_optimal.occupancy_pct,
"display": (
f"H100 SM Optimal (256 thr, 32 regs, 16KB): "
f"{occ_optimal.occupancy_pct:.1f}%"
),
"css_class": "is-fast",
},
{
"label": "occ_reg64",
"value": occ_reg64.occupancy_pct,
"display": f"H100 Reg Cliff (64 regs/thr): {occ_reg64.occupancy_pct:.1f}%",
"css_class": "is-mid",
},
{
"label": "occ_reg128",
"value": occ_reg128.occupancy_pct,
"display": f"H100 Reg Cliff (128 regs/thr): {occ_reg128.occupancy_pct:.1f}%",
"css_class": "is-slow",
},
{
"label": "occ_smem128_crash",
"value": occ_crash.occupancy_pct,
"display": f"SMEM Crash (128 thr, 128KB): {occ_crash.occupancy_pct:.2f}%",
"css_class": "is-slow",
},
{
"label": "simt_mod2_div",
"value": round(div_mod2.simt_efficiency * 100.0, 2),
"display": f"SIMT Divergence (lane%2==0): {div_mod2.simt_efficiency * 100:.1f}%",
"css_class": "is-mid",
},
{
"label": "simt_tail_div",
"value": round(div_tail.simt_efficiency * 100.0, 2),
"display": (
f"SIMT Tail Divergence (lane==31): {div_tail.simt_efficiency * 100:.2f}%"
),
"css_class": "is-slow",
},
],
},
{
"id": "bar_pytorch_cpu_gemm_and_cuda_graph",
"title": (
f"Real PyTorch {pt_gemm.torch_version} CPU MatMul Scaling (1024x1024, GFLOP/s)"
),
"metric_label": "Measured CPU GFLOP/s",
"items": [
{
"label": f"cpu_gemm_m{row.m_batch}",
"value": row.measured_gflops,
"display": (
f"M={row.m_batch} (AI={row.arithmetic_intensity_fp32:.2f}): "
f"{row.measured_gflops:.2f} GFLOP/s"
),
"css_class": "is-slow"
if row.m_batch <= 8
else ("is-mid" if row.m_batch == 64 else "is-fast"),
}
for row in pt_gemm.rows
],
},
]
b200_pref_lin = b200_nvfp4.prefill_linear_point
h100_pref_attn = h100_bf16.prefill_flash_attention_point
b200_pref_attn = b200_nvfp4.prefill_flash_attention_point
h100_dec_gqa = h100_bf16.decode_attention_points[0]
b200_dec_gqa = b200_nvfp4.decode_attention_points[0]
def _format_silicon_peak_cell(s: GPUHardwareSpec) -> str:
base = " | ".join(
f"{prec}: {tf:,.1f} TF (I*={compute_ridge_point(s, prec):.1f})" # type: ignore[arg-type]
for prec, tf in s.peak_tflops.items()
)
if s.gpu_name == "RTX_4090":
return f"{base} [Dense; FP8=330.3 TF FP32 Acc / 660.6 TF FP16 Acc; 2:4 Sparse=2x]"
if s.gpu_name == "B200_SXM":
return (
f"{base} [Dense, ~75 TF FP32; 2:4 Sparse=2x; tcgen05.mma single-thread; "
"NVFP4 16-elem FP8-E4M3 vs MXFP4 32-elem UE8M0]"
)
return f"{base} [Dense; 2:4 Sparse=2x; wgmma 4-warp]"
tables = [
{
"id": "tbl_gpu_silicon_specs",
"title": "GPU Hardware Architecture Registry: Ada RTX 4090 vs Hopper H100 vs Blackwell B200",
"columns": [
"GPU & Architecture",
"SMs / Max Warps / TMEM",
"Memory Bandwidth",
"Dense Peak Compute & Ridge I* (FLOP/B)",
],
"rows": [
[
f"{s.gpu_name} ({s.architecture})",
(
f"{s.sm_count} SMs / {s.max_threads_per_sm // 32} warps / "
f"{s.tmem_per_sm_kb:.0f} KB TMEM"
),
f"{s.hbm_bandwidth_gb_s:,.0f} GB/s ({s.memory_tech})",
_format_silicon_peak_cell(s),
]
for s in (
get_gpu_spec("RTX_4090"),
get_gpu_spec("H100_SXM"),
get_gpu_spec("B200_SXM"),
)
],
},
{
"id": "tbl_roofline_decode_prefill",
"title": (
"Roofline Model Analysis: LLM Decode (Batch 1..512) vs Prefill "
"(H100 BF16 vs B200 NVFP4)"
),
"columns": [
"Stage / Workload (FFN 8192x28672)",
"Arithmetic Intensity (BF16 vs NVFP4 bpe=0.5)",
"H100 BF16 (I*=295.2)",
"B200 NVFP4 (I*=1125.0)",
],
"rows": [
[
"RMSNorm / Elementwise",
(
f"BF16={rmsnorm_pt.arithmetic_intensity:.2f} | "
f"NVFP4={b200_nvfp4.rmsnorm_point.arithmetic_intensity:.2f}"
),
f"{rmsnorm_pt.attainable_tflops:.2f} TF ({rmsnorm_pt.regime})",
(
f"{b200_nvfp4.rmsnorm_point.attainable_tflops:.2f} TF "
f"({b200_nvfp4.rmsnorm_point.regime})"
),
],
*[
[
p_h.workload_name,
f"BF16={p_h.arithmetic_intensity:.2f} | NVFP4={p_b.arithmetic_intensity:.2f}",
(
f"{p_h.attainable_tflops:.2f} TF "
f"({p_h.compute_utilization_pct:.1f}%, {p_h.regime})"
),
(
f"{p_b.attainable_tflops:.2f} TF "
f"({p_b.compute_utilization_pct:.1f}%, {p_b.regime})"
),
]
for p_h, p_b in zip(
[
p
for p in h100_bf16.decode_linear_points
if p.workload_name
in (
"Decode_FFN_B=1",
"Decode_FFN_B=8",
"Decode_FFN_B=64",
"Decode_FFN_B=320",
"Decode_FFN_B=512",
)
],
[
p
for p in b200_nvfp4.decode_linear_points
if p.workload_name
in (
"Decode_FFN_B=1",
"Decode_FFN_B=8",
"Decode_FFN_B=64",
"Decode_FFN_B=320",
"Decode_FFN_B=512",
)
],
strict=True,
)
],
[
"Decode GQA 8x (B=1..512, S_kv=4096)",
(
f"BF16={h100_dec_gqa.arithmetic_intensity:.2f} | "
f"NVFP4={b200_dec_gqa.arithmetic_intensity:.2f}"
),
(
f"{h100_dec_gqa.attainable_tflops:.2f} TF "
f"({h100_dec_gqa.compute_utilization_pct:.1f}%, {h100_dec_gqa.regime})"
),
(
f"{b200_dec_gqa.attainable_tflops:.2f} TF "
f"({b200_dec_gqa.compute_utilization_pct:.1f}%, {b200_dec_gqa.regime})"
),
],
[
"Prefill FFN (S=2048)",
(
f"BF16={prefill_lin.arithmetic_intensity:,.1f} | "
f"NVFP4={b200_pref_lin.arithmetic_intensity:,.1f}"
),
(
f"{prefill_lin.attainable_tflops:.1f} TF "
f"({prefill_lin.compute_utilization_pct:.1f}%, {prefill_lin.regime})"
),
(
f"{b200_pref_lin.attainable_tflops:.1f} TF "
f"({b200_pref_lin.compute_utilization_pct:.1f}%, {b200_pref_lin.regime})"
),
],
[
"Prefill FlashAttention (S=2048)",
(
f"BF16={h100_pref_attn.arithmetic_intensity:.1f} | "
f"NVFP4={b200_pref_attn.arithmetic_intensity:,.1f}"
),
f"{h100_pref_attn.attainable_tflops:.1f} TF ({h100_pref_attn.regime})",
f"{b200_pref_attn.attainable_tflops:.1f} TF ({b200_pref_attn.regime})",
],
],
},
{
"id": "tbl_memory_banks_occupancy",
"title": "CUDA Memory Coalescing, 32-Bank Shared Memory, Warp Divergence & SM Occupancy Audit",
"columns": [
"Hardware Mechanism / Scenario",
"Measured Hardware Metric",
"Efficiency / Utilization",
"Root Cause & CUDA Cure",
],
"rows": [
[
"Global HBM Coalesced (stride=1)",
(
f"{coal_s1.unique_cache_lines_128b} x 128B line "
f"({coal_s1.unique_sectors_32b} sectors)"
),
(
f"{coal_s1.cache_line_efficiency * 100:.1f}% "
f"({coal_s1.effective_hbm_bw_gb_s_128b:,.0f} GB/s)"
),
"Contiguous SoA warp alignment",
],
[
"Global HBM Strided (stride=32)",
(
f"{coal_s32.unique_cache_lines_128b} x 128B lines "
f"({coal_s32.cache_line_amplification:.0f}x)"
),
(
f"{coal_s32.cache_line_efficiency * 100:.2f}% "
f"({coal_s32.effective_hbm_bw_gb_s_128b:,.1f} GB/s)"
),
"Convert AoS -> SoA or stage via SMEM tile",
],
[
"SMEM Transpose [32][32] Col",
f"{smem_col_naive.conflict_ways}-way bank conflict",
f"{smem_col_naive.bank_efficiency * 100:.2f}% (32x stall)",
"All 32 lanes hit same SRAM bank",
],
[
"SMEM Transpose [32][33] Col",
f"{smem_col_padded.conflict_ways}-way (0 conflicts)",
f"{smem_col_padded.bank_efficiency * 100:.1f}% (conflict-free)",
"+1 pad gives gcd(33, 32)=1",
],
[
"SM Occupancy Crash vs Tuned",
f"{occ_crash.active_warps_per_sm} -> {occ_optimal.active_warps_per_sm} warps/SM",
f"{occ_crash.occupancy_pct:.2f}% -> {occ_optimal.occupancy_pct:.1f}%",
"Fix 128KB SMEM / reg spill via block tuning",
],
[
"SIMT Warp Divergence (mod2 / tail)",
f"{div_mod2.total_warp_cycles} / {div_tail.total_warp_cycles} cycles",
f"{div_mod2.simt_efficiency * 100:.1f}% / {div_tail.simt_efficiency * 100:.2f}%",
"Warp-uniform branch or warp shuffle",
],
],
},
{
"id": "tbl_cuda_graph_and_cpu_validation",
"title": "CUDA Graph Launch Timeline (Simulated) & Real Offline PyTorch 2.15+cpu Measurements",
"columns": [
"Experiment / Mode",
"Latency / Throughput",
"Speedup / Ratio",
"Execution Scope Note",
],
"rows": [
[
"Eager Host Launch (180 kernels)",
(
f"{cuda_graph.eager_total_us:.1f} us "
f"({cuda_graph.eager_gpu_utilization_pct:.2f}% GPU util)"
),
f"1.00x ({cuda_graph.eager_launch_bubble_pct:.1f}% launch bubble)",
"Analytical CUDA host-GPU dispatch model",
],
[
"CUDA Graph Replay (180 nodes)",
(
f"{cuda_graph.cuda_graph_total_us:.1f} us "
f"({cuda_graph.cuda_graph_gpu_utilization_pct:.2f}% GPU util)"
),
f"{cuda_graph.cuda_graph_speedup:.2f}x vs Eager",
"Analytical CUDA Graph single launch",
],
[
"CUDA Graph + Kernel Fusion (64 nodes)",
f"{cuda_graph.graph_plus_fusion_total_us:.1f} us",
f"{cuda_graph.graph_plus_fusion_speedup:.2f}x vs Eager",
"Analytical Graph + Fusion model",
],
[
(
f"PyTorch CPU sum(dim=1) Contig vs Strided "
f"({pt_contiguity.rows}x{pt_contiguity.cols})"
),
(
f"{pt_contiguity.contiguous_mean_ms:.3f} ms vs "
f"{pt_contiguity.strided_mean_ms:.3f} ms"
),
f"{pt_contiguity.strided_slowdown_factor:.2f}x strided penalty",
"REAL CPU_PYTORCH measurement",
],
[
f"PyTorch CPU MatMul M=1 vs M=256 ({pt_gemm.k_dim}x{pt_gemm.n_dim})",
(
f"{pt_gemm.rows[0].measured_gflops:.2f} -> "
f"{pt_gemm.rows[-1].measured_gflops:.2f} GFLOP/s"
),
f"{pt_gemm.speedup_max_batch_vs_m1_gflops:.1f}x GFLOP/s scaling",
"REAL CPU_PYTORCH measurement",
],
],
},
]
return {
"config": {
"seed": seed,
"quick": quick,
"unit_id": "T1-P6-U01",
"hardware_modeling_notice": (
"GPU Roofline, 128B coalescing, 32-bank SRAM, SM occupancy, and CUDA Graph "
"timelines are deterministic analytical hardware models validated against real "
f"offline PyTorch {torch.__version__} CPU contiguity/GEMM measurements and "
"Tier-1 `.cu` static kernel checks."
),
"otel_span_count": len(spans),
"otel_span_names": [s.name for s in spans],
},
"gpu_specs": {k: v.model_dump() for k, v in GPU_HARDWARE_SPECS.items()},
"roofline": {
"h100_bf16": h100_bf16.model_dump(),
"h100_fp8": h100_fp8.model_dump(),
"b200_bf16": b200_bf16.model_dump(),
"b200_nvfp4": b200_nvfp4.model_dump(),
"rtx4090_bf16": rtx4090_bf16.model_dump(),
"fp4_microscaling_formats": FP4_MICROSCALING_FORMATS,
"nvfp4_vs_bf16_arithmetic_intensity": {
"rmsnorm": {
"bf16": round(rmsnorm_pt.arithmetic_intensity, 2),
"nvfp4_bpe_0_5": round(b200_nvfp4.rmsnorm_point.arithmetic_intensity, 2),
},
"decode_gqa_8x": {
"bf16": round(h100_dec_gqa.arithmetic_intensity, 2),
"nvfp4_bpe_0_5": round(b200_dec_gqa.arithmetic_intensity, 2),
},
"prefill_flash_attention_s2048": {
"bf16": round(h100_pref_attn.arithmetic_intensity, 1),
"nvfp4_bpe_0_5": round(b200_pref_attn.arithmetic_intensity, 1),
},
},
},
"memory_and_occupancy": {
"coalescing_stride_1": coal_s1.model_dump(),
"coalescing_stride_4": coal_s4.model_dump(),
"coalescing_stride_32": coal_s32.model_dump(),
"smem_row_naive": smem_row_naive.model_dump(),
"smem_col_naive_32x32": smem_col_naive.model_dump(),
"smem_col_padded_32x33": smem_col_padded.model_dump(),
"divergence_uniform": div_uniform.model_dump(),
"divergence_mod2": div_mod2.model_dump(),
"divergence_tail": div_tail.model_dump(),
"occupancy_optimal": occ_optimal.model_dump(),
"occupancy_reg64": occ_reg64.model_dump(),
"occupancy_reg128": occ_reg128.model_dump(),
"occupancy_crash": occ_crash.model_dump(),
},
"cuda_graph": cuda_graph.model_dump(),
"cuda_kernel_audit": cu_audit.model_dump(),
"pytorch_cpu_validation": {
"contiguity": pt_contiguity.model_dump(),
"gemm_scaling": pt_gemm.model_dump(),
},
"workbench_panels": {
"kpis": kpis,
"bars": bars,
"tables": tables,
},
}
"""CUDA memory hierarchy, 128B cache-line coalescing, 32-bank SRAM conflicts,
SIMT warp divergence, SM occupancy cliffs, and static `.cu` kernel contract auditor (`T1-P6-U01`).
"""
from __future__ import annotations
import math
import re
from pathlib import Path
from typing import Literal
from pydantic import BaseModel, ConfigDict, Field
# ---------------------------------------------------------------------------
# Strict Pydantic v2 Schemas
# ---------------------------------------------------------------------------
class SMArchitectureProfile(BaseModel):
"""Streaming Multiprocessor (SM) physical resource budget for occupancy calculations."""
model_config = ConfigDict(extra="forbid", strict=True)
gpu_name: str
max_threads_per_sm: int = Field(..., ge=32)
max_blocks_per_sm: int = Field(..., ge=1)
max_threads_per_block: int = Field(..., ge=32)
registers_per_sm: int = Field(..., ge=1024)
max_registers_per_thread: int = Field(default=255, ge=32, le=255)
reg_allocation_unit: int = Field(default=256, ge=64)
shared_mem_per_sm_kb: float = Field(..., gt=0.0)
warp_size: int = Field(default=32, ge=32, le=32)
class CoalescingReport(BaseModel):
"""Global HBM memory transaction analysis for one 32-thread warp."""
model_config = ConfigDict(extra="forbid", strict=True)
stride_elements: int = Field(..., ge=1)
element_bytes: int = Field(..., ge=1)
useful_bytes: int = Field(..., ge=1)
unique_cache_lines_128b: int = Field(..., ge=1)
unique_sectors_32b: int = Field(..., ge=1)
fetched_bytes_128b: int = Field(..., ge=128)
fetched_bytes_32b: int = Field(..., ge=32)
cache_line_amplification: float = Field(..., ge=1.0)
sector_amplification: float = Field(..., ge=1.0)
cache_line_efficiency: float = Field(..., gt=0.0, le=1.0)
sector_efficiency: float = Field(..., gt=0.0, le=1.0)
effective_hbm_bw_gb_s_128b: float = Field(..., gt=0.0)
effective_hbm_bw_gb_s_32b: float = Field(..., gt=0.0)
sample_lane_addresses: list[int]
class BankConflictReport(BaseModel):
"""32-bank Shared Memory (SRAM) access serialization report."""
model_config = ConfigDict(extra="forbid", strict=True)
tile_dim: int = Field(..., ge=1)
padding: int = Field(..., ge=0)
access_axis: Literal["row", "column", "strided_words"]
stride_words: int = Field(..., ge=1)
num_banks: int = Field(default=32, ge=1)
conflict_ways: int = Field(..., ge=1)
distinct_banks_hit: int = Field(..., ge=1)
serialization_factor: int = Field(..., ge=1)
bank_efficiency: float = Field(..., gt=0.0, le=1.0)
bank_hit_counts: list[int]
lane_to_bank: list[int]
class WarpDivergenceReport(BaseModel):
"""32-lane SIMT lockstep branch divergence efficiency report."""
model_config = ConfigDict(extra="forbid", strict=True)
pattern: str
active_lanes_branch_a: int = Field(..., ge=0, le=32)
active_lanes_branch_b: int = Field(..., ge=0, le=32)
branch_a_cycles: int = Field(..., ge=1)
branch_b_cycles: int = Field(..., ge=1)
divergent: bool
total_warp_cycles: int = Field(..., ge=1)
useful_lane_cycles: int = Field(..., ge=0)
simt_efficiency: float = Field(..., gt=0.0, le=1.0)
slowdown_vs_uniform_a: float = Field(..., ge=1.0)
class SMOccupancyReport(BaseModel):
"""Exact Streaming Multiprocessor occupancy and latency-hiding bottleneck analysis."""
model_config = ConfigDict(extra="forbid", strict=True)
gpu_name: str
threads_per_block: int = Field(..., ge=1)
warps_per_block: int = Field(..., ge=1)
registers_per_thread: int = Field(..., ge=1, le=255)
allocated_regs_per_warp: int = Field(..., ge=256)
allocated_regs_per_block: int = Field(..., ge=256)
shared_mem_per_block_kb: float = Field(..., ge=0.0)
max_warps_per_sm: int = Field(..., ge=1)
blocks_limit_by_warps: int = Field(..., ge=0)
blocks_limit_by_hw_blocks: int = Field(..., ge=0)
blocks_limit_by_registers: int = Field(..., ge=0)
blocks_limit_by_shared_mem: int = Field(..., ge=0)
active_blocks_per_sm: int = Field(..., ge=0)
active_warps_per_sm: int = Field(..., ge=0)
occupancy_pct: float = Field(..., ge=0.0, le=100.0)
primary_limiter: Literal["none_max_warps", "hw_blocks", "registers", "shared_memory", "infeasible"]
required_warps_littles_law: int = Field(..., ge=1)
latency_hiding_ratio: float = Field(..., ge=0.0)
memory_latency_stalled: bool
class CudaKernelStaticAudit(BaseModel):
"""Structural verification report for Tier-1 `.cu` reference CUDA kernels."""
model_config = ConfigDict(extra="forbid", strict=True)
kernel_path: str
global_kernels_found: list[str]
has_coalesced_and_strided: bool
has_naive_and_padded_smem_transpose: bool
has_warp_shuffle_sync: bool
has_tiled_gemm_syncthreads: bool
has_cuda_graph_capture: bool
has_cuda_graph_replay_and_sync: bool
passed_all_checks: bool
# ---------------------------------------------------------------------------
# SM Profile Registry (synchronized with GPUHardwareSpec in hardware_and_roofline)
# ---------------------------------------------------------------------------
SM_ARCHITECTURE_PROFILES: dict[str, SMArchitectureProfile] = {
"H100_SXM": SMArchitectureProfile(
gpu_name="H100_SXM",
max_threads_per_sm=2048,
max_blocks_per_sm=32,
max_threads_per_block=1024,
registers_per_sm=65536,
shared_mem_per_sm_kb=228.0,
),
"B200_SXM": SMArchitectureProfile(
gpu_name="B200_SXM",
max_threads_per_sm=2048,
max_blocks_per_sm=32,
max_threads_per_block=1024,
registers_per_sm=65536,
shared_mem_per_sm_kb=228.0,
),
"RTX_4090": SMArchitectureProfile(
gpu_name="RTX_4090",
max_threads_per_sm=1536,
max_blocks_per_sm=24,
max_threads_per_block=1024,
registers_per_sm=65536,
shared_mem_per_sm_kb=100.0,
),
}
def get_sm_profile(gpu_name: str) -> SMArchitectureProfile:
"""Fetch an immutable SM hardware profile by canonical GPU name."""
if gpu_name not in SM_ARCHITECTURE_PROFILES:
valid = ", ".join(sorted(SM_ARCHITECTURE_PROFILES))
raise ValueError(f"Unknown GPU name '{gpu_name}'. Expected one of: {valid}")
return SM_ARCHITECTURE_PROFILES[gpu_name]
# ---------------------------------------------------------------------------
# 1. Global Memory 128B Cache-Line & 32B Sector Coalescing Analyzer
# ---------------------------------------------------------------------------
def analyze_global_memory_coalescing(
stride_elements: int = 1,
element_bytes: int = 4,
base_addr_bytes: int = 0,
peak_hbm_bw_gb_s: float = 3350.0,
warp_size: int = 32,
) -> CoalescingReport:
"""Compute exact 128B L1 cache-line and 32B L2 sector transactions for a 32-lane warp."""
if stride_elements < 1:
raise ValueError("stride_elements must be >= 1")
if element_bytes not in (1, 2, 4, 8, 16):
raise ValueError("element_bytes must be one of {1, 2, 4, 8, 16}")
if base_addr_bytes < 0 or base_addr_bytes % element_bytes != 0:
raise ValueError("base_addr_bytes must be non-negative and aligned to element_bytes")
if peak_hbm_bw_gb_s <= 0.0:
raise ValueError("peak_hbm_bw_gb_s must be positive")
addrs = [base_addr_bytes + lane * stride_elements * element_bytes for lane in range(warp_size)]
unique_128b = {addr // 128 for addr in addrs}
unique_32b = {addr // 32 for addr in addrs}
useful_bytes = warp_size * element_bytes
fetched_128b = len(unique_128b) * 128
fetched_32b = len(unique_32b) * 32
min_128b_lines = max(1, math.ceil(useful_bytes / 128))
min_32b_sectors = max(1, math.ceil(useful_bytes / 32))
amp_128b = len(unique_128b) / min_128b_lines
amp_32b = len(unique_32b) / min_32b_sectors
eff_128b = min(1.0, useful_bytes / fetched_128b)
eff_32b = min(1.0, useful_bytes / fetched_32b)
return CoalescingReport(
stride_elements=stride_elements,
element_bytes=element_bytes,
useful_bytes=useful_bytes,
unique_cache_lines_128b=len(unique_128b),
unique_sectors_32b=len(unique_32b),
fetched_bytes_128b=fetched_128b,
fetched_bytes_32b=fetched_32b,
cache_line_amplification=round(amp_128b, 4),
sector_amplification=round(amp_32b, 4),
cache_line_efficiency=round(eff_128b, 6),
sector_efficiency=round(eff_32b, 6),
effective_hbm_bw_gb_s_128b=round(peak_hbm_bw_gb_s * eff_128b, 2),
effective_hbm_bw_gb_s_32b=round(peak_hbm_bw_gb_s * eff_32b, 2),
sample_lane_addresses=addrs[:8],
)
# ---------------------------------------------------------------------------
# 2. 32-Bank Shared Memory Bank-Conflict Analyzer
# ---------------------------------------------------------------------------
def analyze_shared_memory_banks(
tile_dim: int = 32,
padding: int = 0,
access_axis: Literal["row", "column", "strided_words"] = "column",
fixed_index: int = 0,
custom_stride_words: int | None = None,
num_banks: int = 32,
warp_size: int = 32,
) -> BankConflictReport:
"""Compute exact 32-bank SRAM conflict multiplicity for `[tile_dim][tile_dim + padding]` tiles."""
if tile_dim < 1:
raise ValueError("tile_dim must be >= 1")
if padding < 0:
raise ValueError("padding must be >= 0")
if fixed_index < 0:
raise ValueError("fixed_index must be >= 0")
row_stride = tile_dim + padding
if access_axis == "row":
stride_words = 1
word_indices = [fixed_index * row_stride + lane for lane in range(warp_size)]
elif access_axis == "column":
stride_words = row_stride
word_indices = [lane * row_stride + fixed_index for lane in range(warp_size)]
else:
if custom_stride_words is None or custom_stride_words < 1:
raise ValueError("custom_stride_words >= 1 is required when access_axis == 'strided_words'")
stride_words = custom_stride_words
word_indices = [fixed_index + lane * stride_words for lane in range(warp_size)]
lane_to_bank = [w % num_banks for w in word_indices]
hit_counts = [0] * num_banks
for b in lane_to_bank:
hit_counts[b] += 1
conflict_ways = max(hit_counts)
distinct_banks = sum(1 for c in hit_counts if c > 0)
efficiency = 1.0 / conflict_ways
return BankConflictReport(
tile_dim=tile_dim,
padding=padding,
access_axis=access_axis,
stride_words=stride_words,
num_banks=num_banks,
conflict_ways=conflict_ways,
distinct_banks_hit=distinct_banks,
serialization_factor=conflict_ways,
bank_efficiency=round(efficiency, 6),
bank_hit_counts=hit_counts,
lane_to_bank=lane_to_bank,
)
# ---------------------------------------------------------------------------
# 3. SIMT Warp Divergence Simulator
# ---------------------------------------------------------------------------
def simulate_warp_divergence(
pattern: Literal["uniform", "even_odd_mod2", "half_split", "single_lane_tail", "quarter_mask"],
branch_a_cycles: int = 40,
branch_b_cycles: int = 40,
warp_size: int = 32,
) -> WarpDivergenceReport:
"""Simulate SIMT lockstep divergence across 32 warp lanes."""
if branch_a_cycles < 1 or branch_b_cycles < 1:
raise ValueError("branch cycles must be >= 1")
if pattern == "uniform":
mask_a = [True] * warp_size
elif pattern == "even_odd_mod2":
mask_a = [(lane % 2 == 0) for lane in range(warp_size)]
elif pattern == "half_split":
mask_a = [(lane < warp_size // 2) for lane in range(warp_size)]
elif pattern == "single_lane_tail":
mask_a = [(lane != warp_size - 1) for lane in range(warp_size)]
elif pattern == "quarter_mask":
mask_a = [(lane % 4 == 0) for lane in range(warp_size)]
else:
raise ValueError(f"Unsupported divergence pattern: {pattern}")
n_a = sum(1 for m in mask_a if m)
n_b = warp_size - n_a
divergent = n_a > 0 and n_b > 0
total_cycles = (branch_a_cycles if n_a > 0 else 0) + (branch_b_cycles if n_b > 0 else 0)
useful_lane_cycles = n_a * branch_a_cycles + n_b * branch_b_cycles
efficiency = useful_lane_cycles / (warp_size * total_cycles)
slowdown = total_cycles / branch_a_cycles
return WarpDivergenceReport(
pattern=pattern,
active_lanes_branch_a=n_a,
active_lanes_branch_b=n_b,
branch_a_cycles=branch_a_cycles,
branch_b_cycles=branch_b_cycles,
divergent=divergent,
total_warp_cycles=total_cycles,
useful_lane_cycles=useful_lane_cycles,
simt_efficiency=round(efficiency, 6),
slowdown_vs_uniform_a=round(slowdown, 4),
)
# ---------------------------------------------------------------------------
# 4. Exact SM Occupancy & Little's Law Latency-Hiding Calculator
# ---------------------------------------------------------------------------
def calculate_sm_occupancy(
gpu_name: str = "H100_SXM",
threads_per_block: int = 256,
registers_per_thread: int = 32,
shared_mem_per_block_kb: float = 16.0,
hbm_latency_cycles: int = 500,
ilp_per_warp: float = 2.0,
warp_schedulers_per_sm: int = 4,
) -> SMOccupancyReport:
"""Compute exact active warps/SM, resource limiter, and Little's Law latency hiding."""
profile = get_sm_profile(gpu_name)
if threads_per_block < 1 or threads_per_block > profile.max_threads_per_block:
raise ValueError(f"threads_per_block={threads_per_block} out of [1, {profile.max_threads_per_block}]")
if registers_per_thread < 1 or registers_per_thread > profile.max_registers_per_thread:
raise ValueError(
f"registers_per_thread={registers_per_thread} out of [1, {profile.max_registers_per_thread}]"
)
if shared_mem_per_block_kb < 0.0:
raise ValueError("shared_mem_per_block_kb must be >= 0")
warps_per_block = math.ceil(threads_per_block / profile.warp_size)
max_warps_per_sm = profile.max_threads_per_sm // profile.warp_size
# NVIDIA hardware allocates registers per warp in `reg_allocation_unit` (256-reg) granules.
raw_regs_per_warp = registers_per_thread * profile.warp_size
gran = profile.reg_allocation_unit
allocated_regs_per_warp = math.ceil(raw_regs_per_warp / gran) * gran
allocated_regs_per_block = allocated_regs_per_warp * warps_per_block
blocks_by_warps = max_warps_per_sm // warps_per_block
blocks_by_hw = profile.max_blocks_per_sm
blocks_by_regs = profile.registers_per_sm // allocated_regs_per_block
# Align SMEM per block to 128-byte (0.125 KB) hardware granule
aligned_smem_kb = math.ceil(shared_mem_per_block_kb * 8.0) / 8.0
if aligned_smem_kb <= 0.0:
blocks_by_smem = blocks_by_hw
elif aligned_smem_kb > profile.shared_mem_per_sm_kb:
blocks_by_smem = 0
else:
blocks_by_smem = int(math.floor((profile.shared_mem_per_sm_kb + 1e-9) / aligned_smem_kb))
active_blocks = min(blocks_by_warps, blocks_by_hw, blocks_by_regs, blocks_by_smem)
active_warps = active_blocks * warps_per_block
occupancy_pct = round((active_warps / max_warps_per_sm) * 100.0, 2)
if active_blocks == 0:
limiter: Literal["none_max_warps", "hw_blocks", "registers", "shared_memory", "infeasible"] = (
"infeasible"
)
elif blocks_by_smem == active_blocks and blocks_by_smem < min(
blocks_by_warps, blocks_by_hw, blocks_by_regs
):
limiter = "shared_memory"
elif blocks_by_regs == active_blocks and blocks_by_regs < min(
blocks_by_warps, blocks_by_hw, blocks_by_smem
):
limiter = "registers"
elif blocks_by_hw == active_blocks and blocks_by_hw < min(
blocks_by_warps, blocks_by_regs, blocks_by_smem
):
limiter = "hw_blocks"
elif blocks_by_regs == active_blocks and active_warps < max_warps_per_sm:
limiter = "registers"
elif blocks_by_smem == active_blocks and active_warps < max_warps_per_sm:
limiter = "shared_memory"
else:
limiter = "none_max_warps"
# Little's Law: concurrent warps required = ceil((L_mem / issue_interval_per_warp) / ilp)
# With 4 warp schedulers issuing 1 warp instr/cycle across active warps:
# required concurrency ~ ceil(L_mem / (ilp_per_warp * (16 / warp_schedulers_per_sm)))
# At L_mem=500, ilp=2.0, issue_latency_window=4*4=16 -> ~32 warps (~50% H100 occupancy) needed.
effective_window = max(1.0, ilp_per_warp * 8.0 * (4.0 / max(1, warp_schedulers_per_sm)))
required_warps = max(1, math.ceil(hbm_latency_cycles / effective_window))
latency_hiding_ratio = round(min(1.0, active_warps / required_warps), 4)
return SMOccupancyReport(
gpu_name=gpu_name,
threads_per_block=threads_per_block,
warps_per_block=warps_per_block,
registers_per_thread=registers_per_thread,
allocated_regs_per_warp=allocated_regs_per_warp,
allocated_regs_per_block=allocated_regs_per_block,
shared_mem_per_block_kb=round(aligned_smem_kb, 3),
max_warps_per_sm=max_warps_per_sm,
blocks_limit_by_warps=blocks_by_warps,
blocks_limit_by_hw_blocks=blocks_by_hw,
blocks_limit_by_registers=blocks_by_regs,
blocks_limit_by_shared_mem=blocks_by_smem,
active_blocks_per_sm=active_blocks,
active_warps_per_sm=active_warps,
occupancy_pct=occupancy_pct,
primary_limiter=limiter,
required_warps_littles_law=required_warps,
latency_hiding_ratio=latency_hiding_ratio,
memory_latency_stalled=active_warps < required_warps,
)
# ---------------------------------------------------------------------------
# 5. Tier-1 `.cu` Kernel Contract Auditor
# ---------------------------------------------------------------------------
def audit_cuda_kernel_file(kernel_path: Path) -> CudaKernelStaticAudit:
"""Verify structural and memory-safety contracts inside a `.cu` source file."""
if not kernel_path.is_file():
raise FileNotFoundError(f"Missing CUDA kernel file: {kernel_path}")
src = kernel_path.read_text(encoding="utf-8")
kernels = re.findall(r"__global__\s+void\s+([A-Za-z_][A-Za-z0-9_]*)\s*\(", src)
has_coalesced_strided = (
"coalesced_copy_kernel" in kernels
and "strided_copy_kernel" in kernels
and "blockIdx.x * blockDim.x + threadIdx.x" in src
)
has_transpose = (
"transpose_naive_smem_kernel" in kernels
and "transpose_padded_smem_kernel" in kernels
and bool(re.search(r"__shared__\s+float\s+tile\[kTileDim\]\[kTileDim\]", src))
and bool(re.search(r"__shared__\s+float\s+tile\[kTileDim\]\[kTileDim\s*\+\s*1\]", src))
)
has_shuffle = (
"warp_shuffle_reduce_sum_kernel" in kernels and "__shfl_down_sync" in src and "0xffffffffu" in src
)
has_tiled_gemm = "tiled_gemm_smem_kernel" in kernels and "__syncthreads();" in src and "fmaf(" in src
has_cuda_graph_capture = (
"capture_decode_graph" in src
and "cudaStreamBeginCapture" in src
and "cudaStreamEndCapture" in src
and "cudaGraphInstantiate" in src
and "cudaGraphDestroy" in src
and "cudaGetLastError" in src
and "launch_decode_step_with_cuda_graph" not in src
)
has_cuda_graph_replay_and_sync = (
"replay_decode_graph" in src
and "cudaGraphLaunch" in src
and "cudaStreamSynchronize" in src
and "cudaGetLastError" in src
)
passed = all(
[
len(kernels) >= 5,
has_coalesced_strided,
has_transpose,
has_shuffle,
has_tiled_gemm,
has_cuda_graph_capture,
has_cuda_graph_replay_and_sync,
]
)
return CudaKernelStaticAudit(
kernel_path=kernel_path.as_posix(),
global_kernels_found=kernels,
has_coalesced_and_strided=has_coalesced_strided,
has_naive_and_padded_smem_transpose=has_transpose,
has_warp_shuffle_sync=has_shuffle,
has_tiled_gemm_syncthreads=has_tiled_gemm,
has_cuda_graph_capture=has_cuda_graph_capture,
has_cuda_graph_replay_and_sync=has_cuda_graph_replay_and_sync,
passed_all_checks=passed,
)
"""End-to-end CLI benchmark runner for WB-Ch26 (`T1-P6-U01`: GPU Hardware & CUDA Programming Model)."""
from __future__ import annotations
import argparse
import json
import sys
from pathlib import Path
if hasattr(sys.stdout, "reconfigure"):
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
try:
import gpu_cuda_roofline_lab # noqa: F401
except ImportError:
_SRC_DIR = Path(__file__).resolve().parents[1] / "src"
if str(_SRC_DIR) not in sys.path:
sys.path.insert(0, str(_SRC_DIR))
from gpu_cuda_roofline_lab.hardware_and_roofline import ( # noqa: E402
run_full_ch26_wb26_benchmark,
)
def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
"""Parse CLI arguments for WB-Ch26 GPU hardware & CUDA Roofline benchmark execution."""
parser = argparse.ArgumentParser(
description=(
"Run WB-Ch26: GPU Hardware Roofline (H100/B200/RTX 4090), 128B Coalescing, "
"32-Bank Shared Memory, SM Occupancy, CUDA Graph Timeline & PyTorch CPU Validation."
)
)
parser.add_argument("--seed", type=int, default=42, help="Deterministic RNG seed.")
parser.add_argument(
"--quick",
action="store_true",
help="Run lighter PyTorch CPU matrix sizing for fast CI verification (<1s).",
)
parser.add_argument(
"--output",
type=str,
default="artifacts/ch26_wb26_results.json",
help="Output JSON artifact path.",
)
return parser.parse_args(argv)
def main(argv: list[str] | None = None) -> int:
"""Execute WB-Ch26 benchmark, print telemetry summary, and write JSON artifact."""
args = parse_args(argv)
payload = run_full_ch26_wb26_benchmark(seed=args.seed, quick=args.quick)
payload["config"]["output"] = args.output
h100 = payload["roofline"]["h100_bf16"]
b200_fp4 = payload["roofline"]["b200_nvfp4"]
mem = payload["memory_and_occupancy"]
cg = payload["cuda_graph"]
pt_c = payload["pytorch_cpu_validation"]["contiguity"]
pt_g = payload["pytorch_cpu_validation"]["gemm_scaling"]
print("=== Ch 26 + WB-Ch26: GPU Hardware Architecture, CUDA Memory & Roofline ===")
print(
f"[1. Roofline] H100 BF16 I*={h100['ridge_point_flop_per_byte']:.2f} FLOP/B "
f"(crossover B*={h100['analytical_linear_crossover_batch']:.1f}) | "
f"B200 NVFP4 I*={b200_fp4['ridge_point_flop_per_byte']:.2f} FLOP/B | "
f"Decode B=1 AI={h100['decode_linear_points'][0]['arithmetic_intensity']:.2f} "
f"({h100['decode_linear_points'][0]['attainable_tflops']:.2f} TF) -> "
f"Prefill S=2048 AI={h100['prefill_linear_point']['arithmetic_intensity']:.1f} "
f"({h100['prefill_linear_point']['attainable_tflops']:.1f} TF)"
)
print(
f"[2. CUDA Memory & SM] Coalescing stride=32: "
f"{mem['coalescing_stride_32']['cache_line_amplification']:.0f}x 128B lines "
f"({mem['coalescing_stride_32']['sector_amplification']:.0f}x L2 sectors) | "
f"SMEM [32][32]->[32][33]: {mem['smem_col_naive_32x32']['conflict_ways']}-way -> "
f"{mem['smem_col_padded_32x33']['conflict_ways']}-way | "
f"SM Occupancy: {mem['occupancy_crash']['occupancy_pct']:.2f}% -> "
f"{mem['occupancy_optimal']['occupancy_pct']:.1f}%"
)
print(
f"[3. CUDA Graph & PyTorch CPU] Eager {cg['eager_total_us']:.1f}us -> "
f"Graph {cg['cuda_graph_total_us']:.1f}us ({cg['cuda_graph_speedup']:.2f}x) -> "
f"Graph+Fusion {cg['graph_plus_fusion_total_us']:.1f}us "
f"({cg['graph_plus_fusion_speedup']:.2f}x) | "
f"Real CPU PyTorch sum(dim=1): {pt_c['contiguous_mean_ms']:.3f}ms vs "
f"{pt_c['strided_mean_ms']:.3f}ms ({pt_c['strided_slowdown_factor']:.2f}x) | "
f"CPU MatMul M=1->256: {pt_g['rows'][0]['measured_gflops']:.2f}->"
f"{pt_g['rows'][-1]['measured_gflops']:.2f} GFLOP/s "
f"| OTel spans={payload['config']['otel_span_count']}"
)
out_path = Path(args.output)
out_path.parent.mkdir(parents=True, exist_ok=True)
out_path.write_text(json.dumps(payload, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
return 0
if __name__ == "__main__":
raise SystemExit(main())
"""Automated verification suite for WB-Ch26 (`gpu_cuda_roofline_lab`, Unit T1-P6-U01)."""
from __future__ import annotations
import ast
import json
import math
import subprocess
import sys
from pathlib import Path
import pytest
from hypothesis import given, settings
from hypothesis import strategies as st
from pydantic import ValidationError
from gpu_cuda_roofline_lab.cuda_memory_and_occupancy import (
SM_ARCHITECTURE_PROFILES,
BankConflictReport,
CoalescingReport,
analyze_global_memory_coalescing,
analyze_shared_memory_banks,
audit_cuda_kernel_file,
calculate_sm_occupancy,
simulate_warp_divergence,
)
from gpu_cuda_roofline_lab.hardware_and_roofline import (
FP4_MICROSCALING_FORMATS,
GPU_HARDWARE_SPECS,
GPUHardwareSpec,
RooflinePoint,
analyze_llm_decode_vs_prefill_roofline,
benchmark_pytorch_contiguity_vs_strided,
benchmark_pytorch_cpu_gemm_scaling,
compute_gemm_roofline,
compute_ridge_point,
get_gpu_spec,
run_full_ch26_wb26_benchmark,
simulate_cuda_graph_launch_overhead,
solve_gemm_crossover_batch,
)
LAB_ROOT = Path(__file__).resolve().parents[1]
BANNED_DESERIALIZERS = {"pickle", "joblib", "cloudpickle", "dill", "shelve", "marshal"}
def test_01_ast_no_unsafe_deserializers() -> None:
"""AST supply-chain gate: strictly ban unsafe Python deserializers in src/ and scripts/."""
py_files = list((LAB_ROOT / "src").rglob("*.py")) + list((LAB_ROOT / "scripts").rglob("*.py"))
assert len(py_files) >= 4
for path in py_files:
tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path))
for node in ast.walk(tree):
if isinstance(node, ast.Import):
for alias in node.names:
root = alias.name.split(".")[0]
assert root not in BANNED_DESERIALIZERS, f"Banned import {root} in {path}"
elif isinstance(node, ast.ImportFrom) and node.module:
root = node.module.split(".")[0]
assert root not in BANNED_DESERIALIZERS, f"Banned import {root} in {path}"
def test_02_pydantic_v2_strict_contracts_forbid_extra_fields() -> None:
"""Pydantic v2 models enforce strict types and reject unknown fields via extra='forbid'."""
with pytest.raises(ValidationError):
GPUHardwareSpec.model_validate(
{
**GPU_HARDWARE_SPECS["H100_SXM"].model_dump(),
"rogue_field": 123,
}
)
with pytest.raises(ValidationError):
CoalescingReport.model_validate(
{
"stride_elements": 1,
"element_bytes": 4,
"useful_bytes": 128,
"unique_cache_lines_128b": 1,
"unique_sectors_32b": 4,
"fetched_bytes_128b": 128,
"fetched_bytes_32b": 128,
"cache_line_amplification": 1.0,
"sector_amplification": 1.0,
"cache_line_efficiency": 1.0,
"sector_efficiency": 1.0,
"effective_hbm_bw_gb_s_128b": 3350.0,
"effective_hbm_bw_gb_s_32b": 3350.0,
"sample_lane_addresses": [0, 4],
"unexpected": True,
}
)
with pytest.raises(ValidationError):
RooflinePoint.model_validate(
{
"workload_name": "test",
"gpu_name": "H100_SXM",
"precision": "BF16",
"total_flops": 100,
"bytes_moved": 10,
"arithmetic_intensity": 10.0,
"ridge_point": 295.22,
"bandwidth_ceiling_tflops": 33.5,
"peak_compute_tflops": 989.0,
"attainable_tflops": 33.5,
"compute_utilization_pct": 3.39,
"regime": "memory_bound",
"extra_key": "blocked",
}
)
def test_03_gpu_spec_registry_and_sm_profile_parity() -> None:
"""Verify GPU_HARDWARE_SPECS and SM_ARCHITECTURE_PROFILES stay synchronized."""
assert set(GPU_HARDWARE_SPECS) == {"RTX_4090", "H100_SXM", "B200_SXM"}
assert set(SM_ARCHITECTURE_PROFILES) == set(GPU_HARDWARE_SPECS)
for name, spec in GPU_HARDWARE_SPECS.items():
sm = SM_ARCHITECTURE_PROFILES[name]
assert spec.max_threads_per_sm == sm.max_threads_per_sm
assert spec.max_blocks_per_sm == sm.max_blocks_per_sm
assert spec.registers_per_sm == sm.registers_per_sm
assert spec.shared_mem_per_sm_kb == sm.shared_mem_per_sm_kb
assert GPU_HARDWARE_SPECS["B200_SXM"].supports_nvfp4 is True
assert GPU_HARDWARE_SPECS["B200_SXM"].tmem_per_sm_kb == 256.0
assert GPU_HARDWARE_SPECS["B200_SXM"].peak_tflops["FP32"] == 75.0
assert "180 GB usable" in GPU_HARDWARE_SPECS["B200_SXM"].memory_tech
assert "single-thread" in GPU_HARDWARE_SPECS["B200_SXM"].issue_semantics
assert "660.6 TF" in GPU_HARDWARE_SPECS["RTX_4090"].dense_vs_sparse_note
assert FP4_MICROSCALING_FORMATS["NVFP4"]["block_size_elements"] == 16
assert FP4_MICROSCALING_FORMATS["NVFP4"]["micro_scale_dtype"] == "FP8 E4M3"
assert FP4_MICROSCALING_FORMATS["MXFP4"]["block_size_elements"] == 32
assert FP4_MICROSCALING_FORMATS["MXFP4"]["micro_scale_dtype"] == "UE8M0"
assert GPU_HARDWARE_SPECS["H100_SXM"].supports_tma is True
def test_04_global_coalescing_128b_and_32b_sector_exact_math() -> None:
"""Coalesced stride=1 fetches 1x128B line (100% eff); stride=32 fetches 32x128B lines (3.125% eff)."""
coal = analyze_global_memory_coalescing(stride_elements=1, element_bytes=4, peak_hbm_bw_gb_s=3350.0)
assert coal.unique_cache_lines_128b == 1
assert coal.unique_sectors_32b == 4
assert coal.fetched_bytes_128b == 128
assert coal.cache_line_amplification == 1.0
assert coal.cache_line_efficiency == 1.0
assert coal.effective_hbm_bw_gb_s_128b == 3350.0
strided = analyze_global_memory_coalescing(stride_elements=32, element_bytes=4, peak_hbm_bw_gb_s=3350.0)
assert strided.unique_cache_lines_128b == 32
assert strided.unique_sectors_32b == 32
assert strided.fetched_bytes_128b == 4096
assert strided.cache_line_amplification == 32.0
assert strided.sector_amplification == 8.0
assert strided.cache_line_efficiency == pytest.approx(1.0 / 32.0, rel=1e-5)
assert strided.effective_hbm_bw_gb_s_128b < 110.0
def test_05_shared_memory_32_bank_conflict_naive_vs_padded() -> None:
"""[32][32] column read hits 32-way conflict; [32][33] +1 padding eliminates all conflicts (1-way)."""
row_naive = analyze_shared_memory_banks(tile_dim=32, padding=0, access_axis="row", fixed_index=3)
assert row_naive.conflict_ways == 1
assert row_naive.distinct_banks_hit == 32
assert row_naive.bank_efficiency == 1.0
col_naive = analyze_shared_memory_banks(tile_dim=32, padding=0, access_axis="column", fixed_index=5)
assert isinstance(col_naive, BankConflictReport)
assert col_naive.conflict_ways == 32
assert col_naive.distinct_banks_hit == 1
assert col_naive.serialization_factor == 32
assert col_naive.bank_hit_counts[5] == 32
col_padded = analyze_shared_memory_banks(tile_dim=32, padding=1, access_axis="column", fixed_index=5)
assert col_padded.conflict_ways == 1
assert col_padded.distinct_banks_hit == 32
assert col_padded.bank_efficiency == 1.0
assert all(c == 1 for c in col_padded.bank_hit_counts)
@given(
padding=st.integers(min_value=0, max_value=31),
fixed_col=st.integers(min_value=0, max_value=31),
)
@settings(max_examples=40, deadline=None)
def test_06_hypothesis_padded_stride_coprime_conflict_free(padding: int, fixed_col: int) -> None:
"""Exact group-theoretic invariant: 32-bank conflict ways == gcd(32 + padding, 32)."""
rep = analyze_shared_memory_banks(
tile_dim=32,
padding=padding,
access_axis="column",
fixed_index=fixed_col,
)
expected_ways = math.gcd(32 + padding, 32)
assert rep.conflict_ways == expected_ways
assert rep.distinct_banks_hit == 32 // expected_ways
assert sum(rep.bank_hit_counts) == 32
def test_07_simt_warp_divergence_lockstep_efficiency() -> None:
"""Warp divergence serializes both paths; mod2 drops to 50%, single-lane tail drops below 15%."""
uni = simulate_warp_divergence("uniform", branch_a_cycles=40, branch_b_cycles=40)
assert not uni.divergent
assert uni.simt_efficiency == 1.0
assert uni.total_warp_cycles == 40
mod2 = simulate_warp_divergence("even_odd_mod2", branch_a_cycles=40, branch_b_cycles=40)
assert mod2.divergent
assert mod2.total_warp_cycles == 80
assert mod2.simt_efficiency == pytest.approx(0.5, abs=1e-6)
assert mod2.slowdown_vs_uniform_a == 2.0
tail = simulate_warp_divergence("single_lane_tail", branch_a_cycles=12, branch_b_cycles=148)
assert tail.divergent
assert tail.total_warp_cycles == 160
assert tail.simt_efficiency < 0.15
def test_08_sm_occupancy_register_and_smem_cliffs() -> None:
"""Verify exact 100% -> 50% -> 25% register occupancy cliffs and 6.25% SMEM crash on H100."""
opt = calculate_sm_occupancy(
"H100_SXM", threads_per_block=256, registers_per_thread=32, shared_mem_per_block_kb=16.0
)
assert opt.active_warps_per_sm == 64
assert opt.occupancy_pct == 100.0
assert opt.memory_latency_stalled is False
reg64 = calculate_sm_occupancy(
"H100_SXM", threads_per_block=256, registers_per_thread=64, shared_mem_per_block_kb=16.0
)
assert reg64.active_warps_per_sm == 32
assert reg64.occupancy_pct == 50.0
assert reg64.primary_limiter == "registers"
reg128 = calculate_sm_occupancy(
"H100_SXM", threads_per_block=256, registers_per_thread=128, shared_mem_per_block_kb=16.0
)
assert reg128.active_warps_per_sm == 16
assert reg128.occupancy_pct == 25.0
assert reg128.primary_limiter == "registers"
crash = calculate_sm_occupancy(
"H100_SXM", threads_per_block=128, registers_per_thread=128, shared_mem_per_block_kb=128.0
)
assert crash.active_blocks_per_sm == 1
assert crash.active_warps_per_sm == 4
assert crash.occupancy_pct == 6.25
assert crash.primary_limiter == "shared_memory"
assert crash.memory_latency_stalled is True
# Ada RTX 4090 has 48 warps/SM (1536 threads), not 64
ada_opt = calculate_sm_occupancy(
"RTX_4090", threads_per_block=256, registers_per_thread=32, shared_mem_per_block_kb=16.0
)
assert ada_opt.max_warps_per_sm == 48
assert ada_opt.occupancy_pct == 100.0
def test_09_roofline_ridge_points_and_precision_support() -> None:
"""Verify exact ridge points for RTX 4090, H100 SXM, and B200 SXM including NVFP4."""
h100 = get_gpu_spec("H100_SXM")
b200 = get_gpu_spec("B200_SXM")
ada = get_gpu_spec("RTX_4090")
assert compute_ridge_point(h100, "BF16") == pytest.approx(989_000.0 / 3350.0, rel=1e-4)
assert compute_ridge_point(h100, "FP8") == pytest.approx(1_979_000.0 / 3350.0, rel=1e-4)
assert compute_ridge_point(b200, "NVFP4") == pytest.approx(9_000_000.0 / 8000.0, rel=1e-4)
assert compute_ridge_point(ada, "BF16") == pytest.approx(165_200.0 / 1008.0, rel=1e-4)
with pytest.raises(ValueError, match="not supported natively"):
compute_ridge_point(h100, "NVFP4")
def test_10_llm_decode_vs_prefill_roofline_and_batch_crossover() -> None:
"""Decode B=1..8 sits memory-bound; batch crossover flips at B* ~ 309; Prefill is compute-bound."""
rep = analyze_llm_decode_vs_prefill_roofline("H100_SXM", "BF16")
b1 = next(p for p in rep.decode_linear_points if p.workload_name == "Decode_FFN_B=1")
b8 = next(p for p in rep.decode_linear_points if p.workload_name == "Decode_FFN_B=8")
b320 = next(p for p in rep.decode_linear_points if p.workload_name == "Decode_FFN_B=320")
assert b1.regime == "memory_bound"
assert b1.arithmetic_intensity < 1.05
assert b8.regime == "memory_bound"
assert b320.regime == "compute_bound"
assert 300.0 < rep.analytical_linear_crossover_batch < 320.0
assert rep.prefill_linear_point.regime == "compute_bound"
assert rep.prefill_linear_point.compute_utilization_pct == 100.0
assert rep.prefill_flash_attention_point.regime == "compute_bound"
assert rep.rmsnorm_point.regime == "memory_bound"
# Verify analytical crossover solver at exact boundary
b_star = solve_gemm_crossover_batch(8192, 28672, 2.0, rep.ridge_point_flop_per_byte)
pt_star = compute_gemm_roofline(
round(b_star), 28672, 8192, get_gpu_spec("H100_SXM"), "BF16", bytes_per_elem=2.0
)
assert abs(pt_star.arithmetic_intensity - rep.ridge_point_flop_per_byte) < 1.5
def test_11_cuda_graph_launch_overhead_and_fusion_speedup() -> None:
"""CUDA Graph removes the ~75% CPU launch bubble on micro-kernels."""
cg = simulate_cuda_graph_launch_overhead(
num_eager_kernels=180,
cpu_launch_us=8.0,
gpu_kernel_exec_us=2.0,
graph_launch_us=12.0,
graph_node_gap_us=0.25,
num_fused_kernels=64,
)
assert cg.eager_total_us == pytest.approx(1442.0, abs=1e-2)
assert cg.eager_gpu_utilization_pct < 26.0
assert cg.eager_launch_bubble_pct > 74.0
assert cg.cuda_graph_speedup > 3.0
assert cg.cuda_graph_gpu_utilization_pct > 80.0
assert cg.graph_plus_fusion_speedup > cg.cuda_graph_speedup
def test_12_pytorch_cpu_contiguous_vs_strided_real_measurement() -> None:
"""Real PyTorch CPU execution verifies contiguity layouts, exact parity & positive telemetry."""
pt = benchmark_pytorch_contiguity_vs_strided(rows=2048, cols=2048, repeats=10, seed=42)
assert pt.execution_environment == "CPU_PYTORCH_LOCAL_MEMORY_AND_GEMM_BENCHMARK"
assert pt.contiguous_is_contiguous is True
assert pt.strided_is_contiguous is False
assert pt.contiguous_strides == [2048, 1]
assert pt.strided_strides == [1, 2048]
assert pt.numerical_max_abs_diff < 1e-3
assert pt.contiguous_mean_ms > 0.0
assert pt.strided_mean_ms > 0.0
assert pt.contiguous_gb_s > 0.0
assert pt.strided_gb_s > 0.0
assert pt.strided_slowdown_factor > 0.0
def test_13_pytorch_cpu_gemm_scaling_real_measurement() -> None:
"""Real PyTorch CPU torch.matmul verifies rising arithmetic intensity & finite GFLOP/s."""
gemm = benchmark_pytorch_cpu_gemm_scaling(
batch_sizes=(1, 8, 64, 256), k_dim=1024, n_dim=1024, repeats=10, seed=42
)
assert gemm.execution_environment == "CPU_PYTORCH_LOCAL_MEMORY_AND_GEMM_BENCHMARK"
assert len(gemm.rows) == 4
ais = [r.arithmetic_intensity_fp32 for r in gemm.rows]
assert ais == sorted(ais)
assert ais[-1] > ais[0]
assert all(r.measured_gflops > 0.0 and r.mean_ms > 0.0 for r in gemm.rows)
assert gemm.speedup_max_batch_vs_m1_gflops > 0.0
def test_14_tier1_cu_kernel_static_contract_audit() -> None:
"""Tier-1 `.cu` source implements coalesced/strided, [32][33] transpose, shuffle & split CUDA Graph."""
kernel_file = LAB_ROOT / "cuda_kernels" / "01_memory_and_gemm_kernels.cu"
src = kernel_file.read_text(encoding="utf-8")
audit = audit_cuda_kernel_file(kernel_file)
assert audit.passed_all_checks is True
assert audit.has_coalesced_and_strided is True
assert audit.has_naive_and_padded_smem_transpose is True
assert audit.has_warp_shuffle_sync is True
assert audit.has_tiled_gemm_syncthreads is True
assert audit.has_cuda_graph_capture is True
assert audit.has_cuda_graph_replay_and_sync is True
assert "capture_decode_graph" in src
assert "replay_decode_graph" in src
assert "cudaStreamSynchronize" in src
assert "cudaGetLastError" in src
assert "launch_decode_step_with_cuda_graph" not in src
assert len(audit.global_kernels_found) >= 5
def test_15_otel_in_memory_spans_recorded() -> None:
"""Full WB-Ch26 run emits all 6 OpenTelemetry spans cleanly via InMemorySpanExporter."""
res = run_full_ch26_wb26_benchmark(seed=42, quick=True)
assert res["config"]["otel_span_count"] == 6
assert res["config"]["otel_span_names"] == [
"gpu.roofline.sweep",
"gpu.memory.coalescing_audit",
"gpu.smem.bank_conflict_audit",
"gpu.occupancy.cliff_audit",
"gpu.cuda_graph.timeline_sim",
"cpu.pytorch.microbenchmarks",
]
def test_16_full_benchmark_determinism_and_error_handling() -> None:
"""Deterministic analytical sections match bit-for-bit; invalid arguments raise ValueError."""
r1 = run_full_ch26_wb26_benchmark(seed=42, quick=True)
r2 = run_full_ch26_wb26_benchmark(seed=42, quick=True)
assert r1["roofline"] == r2["roofline"]
assert r1["memory_and_occupancy"] == r2["memory_and_occupancy"]
assert r1["cuda_graph"] == r2["cuda_graph"]
assert r1["cuda_kernel_audit"] == r2["cuda_kernel_audit"]
with pytest.raises(ValueError):
get_gpu_spec("UNKNOWN_GPU")
with pytest.raises(ValueError):
analyze_global_memory_coalescing(stride_elements=0)
with pytest.raises(ValueError):
calculate_sm_occupancy("H100_SXM", threads_per_block=2048)
def test_17_cli_artifact_and_workbench_panels_schema(tmp_path: Path) -> None:
"""CLI --quick writes valid JSON containing 6 KPIs, 4 bar charts, and 4 tables."""
out_file = tmp_path / "wb26_test.json"
proc = subprocess.run(
[
sys.executable,
str(LAB_ROOT / "scripts" / "run_lab_demo.py"),
"--seed",
"42",
"--quick",
"--output",
str(out_file),
],
cwd=str(LAB_ROOT),
capture_output=True,
text=True,
check=True,
)
assert "Ch 26 + WB-Ch26" in proc.stdout
data = json.loads(out_file.read_text(encoding="utf-8"))
panels = data["workbench_panels"]
assert len(panels["kpis"]) == 6
assert len(panels["bars"]) == 4
assert len(panels["tables"]) == 4
@given(
m_small=st.integers(min_value=1, max_value=64),
m_delta=st.integers(min_value=1, max_value=512),
)
@settings(max_examples=30, deadline=None)
def test_18_hypothesis_roofline_monotonic_with_batch_size(m_small: int, m_delta: int) -> None:
"""Increasing GEMM batch M strictly increases arithmetic intensity and never exceeds peak TFLOPS."""
spec = get_gpu_spec("H100_SXM")
p1 = compute_gemm_roofline(m_small, 4096, 4096, spec, "BF16")
p2 = compute_gemm_roofline(m_small + m_delta, 4096, 4096, spec, "BF16")
assert p2.arithmetic_intensity > p1.arithmetic_intensity
assert p2.attainable_tflops >= p1.attainable_tflops
assert p2.attainable_tflops <= spec.peak_tflops["BF16"]
CPU, NVIDIA H100 SXM (Hopper) và NVIDIA B200 SXM (Blackwell) trong WB-Ch26 là gì?0 chu kỳ nhờ tập thanh ghi khổng lồ trên mỗi SM; Hopper bổ sung WGMMA + TMA, còn Blackwell B200 SXM đưa thêm tcgen05.mma (ngữ nghĩa phát lệnh single-thread), bộ nhớ tích lũy chuyên dụng TMEM (256 KB/SM), NVFP4 (khối 16, FP8 E4M3) vs MXFP4 (khối 32, UE8M0), 9,000 TFLOPS dense (180 GB usable / 192 GB raw HBM3e 8,000 GB/s).
Warp gồm 32 luồng đọc mảng float32 (4 byte/phần tử) với khoảng bước stride = 32 phần tử (kiểu AoS không liền kề) thay vì stride = 1 (SoA hợp nhất). Theo phân tích WB-Ch26, hệ quả phần cứng chính xác là gì?stride = 32 (128 byte giữa hai luồng kế nhau), 32 luồng chạm 32 dòng cache 128B khác nhau (4,096 B cho 128 B hữu ích = khuếch đại 32.0x, hiệu suất 3.125%; mức sector 32B là 32/4 = 8.0x). Trên PyTorch 2.15.0+cpu, bản chuyển vị sum(dim=1) bị chậm hơn 1.90x (1.000 vs 0.526 ms).
transpose_naive_smem_kernel dùng __shared__ float tile[32][32];, vì sao pha đọc theo cột gây xung đột 32-way nhưng đổi thành tile[32][33] lại triệt tiêu hoàn toàn xung đột?32 bank SRAM tuân theo \(\gcd(s, 32)\): với tile[32][32], đọc cột bước s = 32 khiến cả 32 luồng vào cùng 1 bank (32-way, 3.12% hiệu suất); với tile[32][33], bước s = 33 nguyên tố cùng nhau với 32 (gcd(33, 32) = 1) nên đạt 1-way (100.0% SRAM).
Warp (32 luồng): rẽ nhánh phân kỳ (if (threadIdx.x % 2 == 0) và đuôi lane == 31) với rút gọn tổng bằng __shfl_down_sync (0xffffffffu), nhận định nào ĐÚNG?32 luồng dùng chung bộ đếm lệnh SIMT, rẽ nhánh phân kỳ bắt Warp chạy lần lượt cả hai nhánh (mod2 mất 80 chu kỳ = 50.0% hiệu suất; nhánh đuôi lane==31 mất 160 chu kỳ = 10.16%). Ngược lại, __shfl_down_sync luân chuyển giá trị trực tiếp giữa thanh ghi các lane trong Warp mà không chạm SRAM.
H100 SXM (64 warps/SM, 65,536 thanh ghi/SM cấp phát theo bội 256 thanh ghi/warp, 228 KB SMEM/SM), vì sao tăng thanh ghi hoặc cấp quá mức Shared Memory lại làm tụt mạnh SM Occupancy?256 luồng (8 warps), tăng thanh ghi từ 32 -> 64 -> 128 đẩy mức cấp phát lên 8,192 -> 16,384 -> 32,768 regs/block, giảm số block từ 8 -> 4 -> 2 (100% -> 50% -> 25%). Khi block 128 luồng đòi 128 KB SMEM, SM chỉ nạp được 1 block (4/64 = 6.25% occupancy), không đủ ~32 warps theo Định luật Little.
FFN 8192 x 28672 trên H100 SXM (BF16, 989 TFLOPS, 3,350 GB/s, \(I^* = 295.22\)). Khi đối chiếu giữa pha Decode (\(B = 1..8\)), ngưỡng cắt lô \(B^*\), GQA 8x Decode và Prefill (\(S = 2048\)), kết luận nào ĐÚNG?Decode B = 1, toàn bộ ma trận trọng số 469.8 MB chỉ phục vụ 1 token nên AI = 1.00 (3.35 TF, 0.34% H100 peak). Giải \(I_{\text{GEMM}}(B^*) = 295.22\) cho \(B^* = 309.57\) (B=320 đạt 989.0 TFLOPS). Còn GQA 8x Decode đọc KV-cache riêng từng chuỗi nên giữ nguyên AI = 7.98 (hoặc 31.94 ở NVFP4) bất chấp tăng lô B.
180 vi nhân CUDA liên tiếp (mỗi nhân chạy 2.0 us trên GPU, nhưng mỗi lần CPU gọi phóng nhân mất 8.0 us), CUDA Graph cải thiện hiệu năng theo cơ chế nào trong WB-Ch26?Eager, độ trễ phóng CPU 8.0 us > 2.0 us làm GPU ngồi chờ 6.0 us giữa mỗi nhân (75.03% launch bubble, tổng 1,442.0 us). Tách capture_decode_graph một lần khỏi vòng lặp replay_decode_graph (cudaGraphLaunch + cudaStreamSynchronize) phóng trọn đồ thị 1 lần (12.0 us), đẩy GPU util từ 24.97% lên 86.38% (3.46x), và kết hợp dung hợp 64 nút đạt 4.10x (351.8 us).
Nsight Compute (ncu) trên nhân GPU, thấy chỉ số smsp__warp_issue_stalled_long_scoreboard chiếm ưu thế còn dram__throughput bão hòa trên 90% SOL%, chẩn đoán và hướng xử lý SOTA 2026 là gì?Nsight Compute, long_scoreboard báo Warp đang chờ dữ liệu từ HBM/TMA (trái với short_scoreboard chờ SRAM/ALU hay mio_throttle/barrier/no_eligible), đi kèm dram__throughput > 90% SOL xác nhận nhân nằm ở sườn Memory-Bound. Giải pháp chuẩn là Kernel Fusion (Chương 27 Triton), hợp nhất 128B, lượng tử hóa FP8/NVFP4, PDL/Green Contexts và CUDA Graphs (Track 2 #34–#35).
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 — Kiểm toán Giao dịch 128B và Thí nghiệm Chuyển vị PyTorch CPU 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Tính tập hợp chỉ số dòng cache addr // 128 và sector L2 addr // 32 cho 32 luồng float32 (4B) tại stride = 1, 4, 32.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Gọi analyze_global_memory_coalescing và benchmark_pytorch_contiguity_vs_strided trong WB-Ch26 (Tests 04, 12).
Tiêu chí Đáp án & Số đối chứng
stride = 1 chạm đúng 1 dòng 128B (4 sector 32B, 100% hiệu suất, 3,350 GB/s trên H100). stride = 32 chạm 32 dòng 128B (4,096 B tải cho 128 B dùng = 32.0x khuếch đại cache-line / 8.0x L2 sector, hiệu suất 3.125%). Trên PyTorch 2.15.0+cpu (2048x2048), x_t.sum(dim=1) với stride=[1, 2048] chậm hơn 1.90x (1.000 vs 0.526 ms).
Bài tập 2 — Triệt tiêu Xung đột 32 Ngân hàng SRAM Bằng Đồng nguyên 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Áp dụng công thức bank = word_idx % 32 cho pha đọc hàng row * (32 + p) + lane và pha đọc cột lane * (32 + p) + col trên tile[32][32 + p].
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy analyze_shared_memory_banks và kiểm chứng định lý gcd(32 + padding, 32) trong Tests 05–06, 14.
Tiêu chí Đáp án & Số đối chứng
Với p = 0 ([32][32]), đọc cột có stride = 32 nên mọi lane đều rơi vào cùng col % 32 (gcd(32, 32) = 32-way conflict, 3.12% hiệu suất). Với p = 1 ([32][33]), gcd(33, 32) = 1 trải đều 32 luồng ra trọn 32 ngân hàng (1-way, 100% hiệu suất).
Bài tập 3 — Định lượng Phân kỳ SIMT và Bậc thang SM Occupancy 20%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Tính mức cấp phát thanh ghi theo bội 256 thanh ghi/warp (ceil(regs * 32 / 256) * 256 * warps_per_block) và lấy min 4 giới hạn trên SM (warps, hw_blocks, registers, shared_mem).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Kiểm tra simulate_warp_divergence và calculate_sm_occupancy trên H100_SXM và RTX_4090 (Tests 07–08).
Tiêu chí Đáp án & Số đối chứng
Trên H100 (256 thr/blk), tăng thanh ghi 32 -> 64 -> 128 hạ Occupancy 100.0% -> 50.0% -> 25.0%. Khi block 128 luồng đòi 128 KB SMEM, SM chỉ nạp 1 block (4/64 warps = 6.25%), nhỏ hơn ngưỡng 32 warps của Định luật Little (latency_hiding_ratio = 0.125). Phân kỳ mod2 đạt 50.0% SIMT, lane == 31 tụt còn 10.16%.
Bài tập 4 — Dẫn xuất Roofline LLM Decode sang Prefill và Điểm Cắt Lô 20%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Tính \(I^* = \Pi_{\text{peak}} / \text{BW}_{\text{peak}}\) cho H100 BF16 và B200 NVFP4, rồi giải \(I_{\text{GEMM}}(B^*) = I^*\) cho ma trận FFN 8192 x 28672.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy analyze_llm_decode_vs_prefill_roofline và benchmark_pytorch_cpu_gemm_scaling (Tests 09–10, 13, 18).
Tiêu chí Đáp án & Số đối chứng
H100 BF16: \(I^* = 295.22\), B* = 309.57 (~310 tokens); B=1 đạt AI = 1.00 (3.35 TF, 0.34%), B=320 và Prefill S=2048 (AI = 1,549.8) chạm 989.0 TF (100%). B200 NVFP4 đạt I* = 1,125.0 (9,000 TF). Đo thực trên PyTorch 2.15+cpu: M=1 -> 256 tăng thông lượng GFLOP/s đạt 20.15x (11.30 -> 227.72 GFLOP/s).
Bài tập 5 — Thiết kế Đường ống CUDA Graphs và Giải mã Nsight Compute 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Mô phỏng lịch trình sự kiện max(cpu_ready_i, gpu_free_{i-1}) khi cpu_launch = 8.0 us > gpu_exec = 2.0 us qua 180 vi nhân.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Gọi simulate_cuda_graph_launch_overhead và đối chiếu với capture_decode_graph / replay_decode_graph trong file .cu (Tests 11, 14).
Tiêu chí Đáp án & Số đối chứng
Eager tốn 1,442.0 us với 75.03% bong bóng chờ CPU (24.97% GPU util). Tách capture_decode_graph và replay_decode_graph (12.0 us phóng 1 lần, 0.25 us node gap, cudaStreamSynchronize) hạ xuống 416.8 us (3.46x, 86.38% GPU util), còn Graph + Fusion (64 nút) đạt 351.8 us (4.10x).
Bài tập 6 — Kiểm chứng Toàn trình WB-Ch26 và OpenTelemetry Tracing 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Đảm bảo hợp đồng Pydantic v2 (extra="forbid", strict=True), kiểm toán AST cấm pickle/joblib, và cấu trúc 6 span OpenTelemetry.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy uv.exe lock --check, ruff check, mypy src, pytest -p no:cacheprovider -v (18/18), và scripts/run_lab_demo.py --seed 42 (Tests 01–03, 15–17).
Tiêu chí Đáp án & Số đối chứng
Toàn bộ 18/18 kiểm thử pytest đạt xanh ở cả OMP_NUM_THREADS=1 lẫn đa luồng (0 skipped), ruff và mypy đạt 0 lỗi, uv.lock khóa 34 gói (ghim pytorch-cpu), 6 span OpenTelemetry được ghi đầy đủ qua InMemorySpanExporter, và artifacts/ch26_wb26_results.json xuất chuẩn 6 KPI, 4 biểu đồ cột và 4 bảng workbench_panels.