Chương 27 — Lập trình Nhân GPU OpenAI Triton Từ Gốc: SPMD Tiling, Dung hợp Bộ nhớ (Softmax/RMSNorm), L2 Swizzle MatMul & FlashAttention-2
Từ dung hợp Online Softmax (-75.0% HBM, miễn nhiễm exp(1000) NaN) & Fused RMSNorm (3.49x giảm HBM, 4.91x Roofline) đến Tiled MatMul L2 Swizzle G=4 (tỉ lệ trúng L2 43.75% -> 81.25%, -66.7% DRAM), FlashAttention-2 Forward (512x tiết kiệm HBM tại N=512, 32,768x ở N=32K, err < 4e-7 vs PyTorch) & @triton.autotune (235.2 TFLOP/s, 9.55x): 5/5 nhân @triton.jit chuẩn AST.
Đơn vị học phần (
Unit ID):T1-P6-U02(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 chiến: Lab 15 — Lập trình NhânOpenAI TritonTừ Gốc (triton_kernels&triton_kernels_lab)
Truy xuất nguồn & kế thừa: Kế thừa trực tiếp từChương 26(SM,Warps,HBMvsSRAMBanks,TMA,WGMMA/tcgen05.mma, mô hình Roofline &CUDA), Chương 14 — Mạng Nơ-ron & Nội tạiPyTorch 2.x, Chương 19 — Attention, Transformers & Kiến trúc LLM Hiện đại, Chương trình gốc DSAI (R54: Triton Programming & Implement Triton kernels from scratch), và Đề cương SOTA 2026 (Chương 27). Nền tảng nhân GPU của chương này liên thông trực tiếp sang Track 2 Phần 4 (LLM Inference Serving:PagedAttention,FlashAttention,torch.compile,CUDA Graphs— xem Đề cương Track 2).
Bốn Ca Thất bại Hiệu năng Nhân GPU Mở màn: Vì sao Mã PyTorch Eager Lãng phí Băng thông & Sập OOM#
Viết một phép tính toán học đúng trên PyTorch Eager không đồng nghĩa với việc khai thác được phần cứng GPU hiện đại (NVIDIA H100 SXM: 3,350 GB/s băng thông HBM3, 989 TFLOP/s FP16 Tensor Core, điểm gãy Roofline 295.2 FLOP/B, 228 KB SRAM/SM). Toàn bộ bốn ca thất bại dưới đây được tái lập và định lượng trực tiếp trong Lab 15 (artifacts/ch27_lab15_results.json, seed=42):
Minh bạch Bằng chứng Thực thi (PyTorch CPU vs Mô hình Phân tích Roofline/LRU khi HAS_REAL_TRITON = False):
Trên môi trường không có GPU NVIDIA (HAS_REAL_TRITON = False), Lab 15 tách bạch hai tầng kiểm chứng:
- Kiểm chứng Số học & Biên nhớ Thực trên
PyTorch CPU: Toàn bộ sai số cực đại (max_abs_errso vớitorch.softmax,torch.rsqrt,a @ b,F.scaled_dot_product_attention), kiểm tra nổNaNtrên dải[-1000, +1000], bẫy đệm đuôiother=0.0(3.00e-03) và hỏng ô canary ngoài biên đều được tính toán trực tiếp bằng tensorPyTorchtheo đúng thuật toán chia khốiSPMD. - Lưu lượng
HBM,L2 Hit Rate&Roofline TFLOP/slà Mô hình Giải tích / Giả lập: Số lượt phóng nhân, tổng byte đọc/ghiHBM, mô phỏng bộ đệmLRU L2 Cachetheo thứ tựpid, và độ trễ/TFLOP/strênH100 SXM(3,350 GB/s,989 TFLOP/s) được suy xuất từ mô hình giải tích Roofline & LRU tất định; đồng thời mã nguồn@triton.jitthuần trongtriton_kernels/được kiểm toán cấu trúc AST và sẵn sàng biên dịch native trênLinux + CUDA.
-
Ca 1 — Bùng nổ Băng thông
HBMdo Không Dung hợp (Unfused Eager HBM Round-Trips,Lab 15,Tests 05–06):Khi gọi
Softmax(128 × 777phần tửfp32) hoặcRMSNorm(128 × 1024) dưới dạng chuỗi toán tử tách rời (max,sub,exp,sum,divhoặcx*x,mean,rsqrt,mul), GPU phải phóng5nhân riêng rẽ, đọc lại toàn bộ tensor từHBMtới4–5lần và ghi các ma trận trung gian raHBM(3,110.0 KBchoSoftmax;3,590.0 KBchoRMSNorm). Ngược lại, dung hợp thành một nhânTritongiữ hàng dữ liệu trong thanh ghi/SRAMthu gọn lưu lượngHBMxuống còn777.0 KB(4.00xgiảm,-75.0%) choSoftmax(max_abs_err = 1.19e-07) và1,028.0 KB(3.49xgiảmHBM,4.91xtăng tốc Roofline) choRMSNorm(max_abs_err = 0.00e+00). -
Ca 2 — Đọc/Ghi Tràn Biên & Lỗi Đệm
other=0.0Trên Kích thước Lẻ (Unmasked OOB & Zero-Pad Bug,Lab 15,Tests 03–05):Các kích thước tensor thực tế (
N = 100,003hayn_cols = 777) hiếm khi là lũy thừa của2. Nếu bỏ quên mặt nạmask = offsets < n_elementstrongtl.load/tl.storetạiBLOCK_SIZE = 256, khối cuối ghi đè vào93ô nhớ canary lân cận (canary_corrupted = True). Tệ hơn, trênSoftmax, nếu cài mặt nạ nhưng quên đặtother=-float("inf")(mặc địnhother=0.0), các ô đệm ngoài biên đóng góp lượng \(\exp(0 - m_i) > 0\) vào mẫu số, đẩy sai sốmax_abs_errvọt lên3.00e-03(0.003003); còn tính \(\exp(x)\) ngây thơ không trừ cực đại nổ tung thànhNaNngay trên dải logits[-1000, +1000]! Chỉ Online Safe Softmax (Milakov–Gimelshein) kèmother=-float("inf")mới đạt4.66e-10sai số với0NaN. -
Ca 3 — Lập lịch Khối Theo Hàng Phá Hủy
L2 Cache(Row-Major L2 Thrashing,Lab 15,Tests 07–08):Trên phép nhân ma trận khối \(M \times N \times K\) (
512 × 512 × 256, kích thước khốiBM=64, BN=64, BK=32,64CTAs, bộ đệmL2 = 256 KB), lập lịch mặc địnhRow-Major(GROUP_SIZE_M=1) quét hết cả hàng cột của ma trận \(\mathbf{B}\) trước khi sang hàng tiếp theo của \(\mathbf{A}\). Tập làm việc của một hàng vượt quáL2nên mọi cột của \(\mathbf{B}\) bị đẩy khỏiL2trước khi hàng mới kịp dùng lại:L2 Hit Ratetụt còn43.75%(576misses) vàDRAMphải tải2,304.0 KB(4.50xdữ liệu tối thiểu bắt buộc). Đổi sang L2 Cache Swizzling (GROUP_SIZE_M=4) gom nhóm4hàng CTA tái sử dụng cục bộ theo cụm khối nângL2 Hit Ratelên81.25%(+37.50 pp) và cắt3.00xlưu lượngDRAM(2,304.0 KB -> 768.0 KB,-66.7%). -
Ca 4 — Hiện thực Hóa Ma trận \(O(N^2)\) Ra
HBM& SậpOOMNgữ cảnh Dài (Standard Attention OOM,Lab 15,Tests 09–11):Cài đặt chuẩn
PyTorchcơ bản tính tường minh \(\mathbf{S} = \mathbf{Q}\mathbf{K}^\top / \sqrt{d_k}\) và \(\mathbf{P} = \operatorname{softmax}(\mathbf{S})\) rồi ghi cả hai ma trận \(N \times N\) raHBM: ngay ởN = 512(B=2, H=4) đã chiếm8.00 MBđệm trung gian, và ở cấu hìnhLlama-3 32 Heads, N = 32,768phình lên131,072 MB(128 GB > 80 GBbộ nhớH100, sậpOOM!). Trái lại, nhân FlashAttention-2 Forward phân khối \(B_r \times B_c\) giữ trọn \(\mathbf{S}_{\text{tile}}, \mathbf{P}_{\text{tile}}\) bên trongSRAMvà chuẩn hóa trực tuyến(m_i, l_i)chỉ xuất vectơLogSumExp\(O(N)\) (16.0 KBtạiN=512=512xgiảm đỉnhHBM; và4.00 MBtạiN=32K=32,768xgiảm đỉnh,0OOM), khớpPyTorch SDPAtới3.58e-07(causal) và2.38e-07(chuỗi lẻN=149).
Mục tiêu Học tập (Learning Objectives)#
Sau khi hoàn tất Chương 27 và vượt qua trọn vẹn 17/17 bài kiểm thử của Lab 15, học viên đạt chuẩn kỹ sư tối ưu nhân GPU:
- Làm chủ Mô hình
SPMDCấp Khối củaOpenAI Triton 3.x: Phân biệt lập trình từng luồngSIMTcủaCUDAvới mô hình lập trình theo khối véc-tơSPMD(tl.program_id,tl.arange, số học con trỏ 2Dstride_m, mặt nạ biênmask/other,tl.dot,tl.make_block_ptrvà bộ tạo mãMLIR/LLVM). - Thiết kế Nhân Dung hợp Vượt Nút thắt Băng thông (
Kernel Fusion): Phân tích trên mô hình Roofline lý doSoftmaxvàRMSNormbị nghẽnHBM; dẫn xuất và cài đặt thuật toán 1-Pass Online Safe Softmax (Milakov–Gimelshein) cùng Fused RMSNorm cắt3.49x–4.00xlưu lượngHBM. - Tối ưu Tái sử dụng Bộ nhớ Đệm
L2&SRAMTrênGEMM: Lập trìnhTiled MatMulvớitl.dottích lũyfp32và thiết kế phép ánh xạL2 Cache Swizzling(GROUP_SIZE_M) cùng tối ưu cấu hình tự động@triton.autotunecó kiểm soát giới hạn228 KBSMEM. - Cài đặt Nhân
FlashAttention-2 ForwardTừ Gốc: Chứng minh đẳng thức hồi quy chuẩn hóa lại \(\mathbf{O}_{\text{new}} = \operatorname{diag}(e^{m_{\text{old}} - m_{\text{new}}})\mathbf{O}_{\text{old}} + \mathbf{P}_{\text{tile}}\mathbf{V}_{\text{tile}}\), áp dụng mặt nạ nhân quả theo khối bỏ qua tam giác trên, và xác minh độ chính xác< 1e-5so vớiSDPA. - Nắm vững Công nghệ
Triton 3.2–3.5, Hệ sinh thái DSL 2025–2026 &FlashAttention-3/4: Thành thạo API hướng đối tượngtl.make_tensor_descriptor(TMA/Ragged TMA),WarpSpec,Proton(triton.profiler), đóng gói@torch.library.triton_optránh đứt gãytorch.compile/AOTInductor, nắm hệ sinh tháiGluon/Helion/CuTe-DSL/TileLang, bẫy triển khai sản xuất và bước nhảyFlashAttention-4(1,613 TFLOPStrênBlackwell B200).
Truy xuất Nguồn (Syllabus & Raw Curriculum Traceability)#
Thành phần Chương trình Nguồn (R54) |
Nội dung Chuyên sâu trong Chương 27 | Sơ đồ / Mô phỏng Tương tác | Thực thi trong Lab 15 (triton_kernels + triton_kernels_lab) |
|---|---|---|---|
OpenAI Triton SPMD & Vector Add (R54.1) |
Mô hình SPMD, tl.program_id, tl.arange, số học con trỏ, mặt nạ biên mask/other, Roofline băng thông |
Mermaid 1 |
vec_add_kernel & spmd_vector_add (Tests 03, 13, 17) |
Kernel Fusion: Online Softmax & RMSNorm (R54.2) |
Dung hợp bỏ round-trip HBM, 3-pass vs 2-pass vs 1-pass Online Milakov–Gimelshein, bẫy other=0.0, Fused RMSNorm |
Widget 1 (triton-fusion-hbm-traffic-lab) |
fused_online_softmax_kernel, fused_rmsnorm_kernel, run_softmax_ablation, run_rmsnorm_ablation (Tests 04–06) |
Tiled MatMul, L2 Swizzle & Autotune (R54.3) |
tl.dot, tl.make_block_ptr, ánh xạ GROUP_SIZE_M chống thrashing L2, @triton.autotune & cắt tỉa SMEM, TMA, num_stages |
Mermaid 2 + Widget 2 (tiled-matmul-l2-swizzle-explorer) |
tiled_matmul_swizzled_kernel, spmd_tiled_matmul, run_matmul_autotune_sweep (Tests 07–08, 12) |
FlashAttention-2 Forward & SOTA 2026 (R54.4) |
Chia khối \(B_r \times B_c\) trong SRAM, mặt nạ nhân quả, O(N^2) -> O(N) HBM, TorchInductor, Liger-Kernel, FlashAttention-3 |
Mermaid 3 + Widget 3 (flashattention-sram-tiling-simulator) |
flash_attn_fwd_kernel, spmd_flash_attention_fwd, run_flash_attention_benchmark (Tests 09–11, 14) |
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 27 | Tên biến trong Lab 15 |
|---|---|---|---|
| \(\text{pid}, \text{pid}_m, \text{pid}_n\) | \(\mathbb{Z}_{\ge 0}\) | Chỉ số khối chương trình (program_id) tuyến tính và tọa độ 2D trên lưới đầu ra |
pid, pid_m, pid_n |
| \(B_M, B_N, B_K\) | \(\mathbb{Z}_{>0}\) (phần tử) | Kích thước khối lát gạch cho ba chiều \(M, N, K\) của Tiled MatMul |
block_m, block_n, block_k |
\(G\) (GROUP_SIZE_M) |
\(\mathbb{Z}_{\ge 1}\) | Số hàng khối gom nhóm theo chiều \(M\) trong phép hoán vị L2 Cache Swizzling |
group_size_m |
| \(B_r, B_c\) | \(\mathbb{Z}_{>0}\) | Số hàng truy vấn Q và số cột khóa/giá trị K, V trong một khối SRAM của FlashAttention-2 |
block_r, block_c |
| \(m_i, \ell_i\) | \(\mathbb{R}, \mathbb{R}_{\ge 0}\) | Giá trị cực đại dòng đang chạy và tổng lũy thừa chuẩn hóa trong Online Softmax |
m_i, l_i |
| \(L_i\) | \(\mathbb{R}\) | Vectơ LogSumExp \(m_i + \ln(\ell_i)\) lưu duy nhất ra HBM (\(O(N)\)) cho pha lan truyền ngược |
logsumexp |
| \(I_{\text{arith}}\) | \(\text{FLOP}/\text{Byte}\) | Cường độ số học \(\text{FLOPs} / \text{Bytes}_{\text{HBM}}\) đối chiếu với điểm gãy Roofline (\(295.2\)) | arithmetic_intensity |
| \(S_{\text{SMEM}}\) | \(\text{Bytes}\) | Dung lượng SRAM tiêu thụ cho đường ống num_stages trên mỗi CTA (\(\le 228\text{ KB}\) trên H100) |
sram_required_bytes |
Trụ cột 1 — Nền tảng Toán học & Thuật toán: Từ SPMD Đến Dung hợp Nhân, L2 Swizzle & FlashAttention-2#
1.1 Mô hình Lập trình SPMD của OpenAI Triton 3.x & Mặt nạ Biên (Vector Add)#
Khác với CUDA (SIMT — lập trình viên điều khiển từng luồng vô hướng threadIdx.x, tự cấp phát mảng __shared__, tự đồng bộ __syncthreads() và tự xử lý xung đột ngân hàng bank conflict), OpenAI Triton nâng mức trừu tượng lên khối véc-tơ/ma trận (Block-Level SPMD):
- Mỗi lời gọi nhân khởi chạy một lưới các phiên bản chương trình độc lập (
Program InstanceshayCTA), nhận định danh quapid = tl.program_id(axis=0). - Bên trong một
CTA, mọi biến dữ liệu là véc-tơ hoặc khối 2D đồng bộ được xác định qua chỉ sốoffsets = pid * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE), còn trình biên dịchTriton(Triton-IR -> Triton-GPU-IR -> LLVM/PTX) tự động phân chia khối đó xuống từngWarp, sắp xếp bố cụcShared Memorytránh bank conflict và phát sinh lệnh chép bất đồng bộ! - Bẫy 1 — Phân tích Roofline của Phép toán Phần tử (
Vector Add): Với hai véc-tơ \(\mathbf{x}, \mathbf{y} \in \mathbb{R}^N\) (fp32, \(4\) bytes), mỗi phần tử cần2lần đọc và1lần ghi (12bytesHBM) cho đúng1phép cộng:\[I_{\text{arith}}(\text{VecAdd}_{\text{fp32}}) = \frac{N\;\text{FLOP}}{3 \cdot 4N\;\text{Bytes}} = \frac{1}{12} \approx 0.0833\;\text{FLOP/B} \ll 295.2\;\text{FLOP/B}\;(\text{H100 Ridge Point}).\]Nghĩa là mọi nhân phần tử đơn lẻ luôn bị nghẽn băng thôngHBMtuyệt đối (Memory-Bound). Vì vậy, tối ưu tối thượng không phải giảm số phép toán số học mà là giảm số lần chạmHBM! - Bẫy 2 — Mặt nạ Biên Tuyệt đối (
mask&other): KhiN = 100,003vàBLOCK_SIZE = 256, lưới cần \(\lceil 100003 / 256 \rceil = 391\) khối (100,096vị trí), dư93phần tử đuôi. Nếutl.load/tl.storethiếumask = offsets < n_elements, khối cuối sẽ ghi tràn làm hỏng đúng93phần tử canary vùng nhớ kề (Lab 15,Test 03).
1.2 Dung hợp Nhân Bộ nhớ (Kernel Fusion): Online Safe Softmax & Fused RMSNorm#
-
Ba Thế hệ Thuật toán
SoftmaxTheo Hàng \(\mathbf{x} \in \mathbb{R}^{M \times N}\):- Thế hệ 0 (Ngây thơ không trừ cực đại — Sập
NaN): Tính trực tiếp \(\frac{e^{x_j}}{\sum_k e^{x_k}}\). Ngay khi \(x_j > 88.72\) ởfp32(hoặc \(11.08\) ởfp16), \(e^{x_j} = +\infty \implies \infty / \infty = \texttt{NaN}\) (Lab 15,Test 04trên dải[-1000, +1000]). - Thế hệ 1 (PyTorch Eager Không Dung hợp — 5 lượt
HBM): Phóng5nhân rời rạc: (1) \(m = \max_k x_k\), (2) \(\tilde{\mathbf{x}} = \mathbf{x} - m\), (3) \(\mathbf{e} = \exp(\tilde{\mathbf{x}})\), (4) \(\ell = \sum_k e_k\), (5) \(\mathbf{y} = \mathbf{e}/\ell\). Trên bảng128 × 777(fp32), tổng lưu lượngHBMvọt lên3,110.0 KB(5lượt đọc +3lượt ghi toàn ma trận). -
Thế hệ 2 (
Online Safe Softmax— Milakov & Gimelshein, 2018): Thay vì cần biết \(m_{\text{global}}\) trước mới cộng tổng mũ, ta quét từng khối cột \(B_C\) (col_start = 0, BLOCK_SIZE, ...) và cập nhật trạng thái rút gọn \((m_i, \ell_i)\) trực tuyến trong một lượt duy nhất:\[m_{\text{new}} = \max(m_{\text{old}}, m_{\text{tile}}), \qquad \ell_{\text{new}} = \ell_{\text{old}} \cdot e^{m_{\text{old}} - m_{\text{new}}} + \sum_{j \in \text{tile}} e^{x_j - m_{\text{new}}}.\]Nhờ thừa số hiệu chỉnh \(e^{m_{\text{old}} - m_{\text{new}}} \in (0, 1]\), các số mũ cũ được co giãn chuẩn xác về hệ quy chiếu cực đại mới mà không bao giờ tràn số và không bao giờ phải ghi mảng \(\exp(\mathbf{x} - m)\) trung gian ra
HBM!- Khi \(N\) vừa trong thanh ghi/
SRAM(BLOCK_SIZE >= N), toàn bộ hàng chỉ đọc từHBM1 lần và ghi kết quả 1 lần (777.0 KB, cắt4.00xlưu lượngHBM/-75.0%,max_abs_err = 1.19e-07). - Khi hàng siêu dài (\(N \gg \text{BLOCK\_SIZE}\)), thuật toán online chia khối giảm lưu lượng từ
3,110.0 KBxuống1,165.5 KB(2.67xgiảm) và đạt4.66e-10sai số trên dải cực trị[-1000, +1000].- Cảnh báo Sống còn — Lỗi Đệm
other=0.0: Trên hàng có777cột vớiBLOCK_SIZE = 256, khối thứ tư dư247ô đệm (mask = offsets < 777). Nếu quênother=-float("inf")mà đểother=0.0, \(\exp(0.0 - m_i) > 0\) cộng thêm vào \(\ell_i\), phá hỏng phân phối xác suất (max_abs_err = 3.00e-03,Lab 15,Test 05).
- Cảnh báo Sống còn — Lỗi Đệm
- Khi \(N\) vừa trong thanh ghi/
- Thế hệ 0 (Ngây thơ không trừ cực đại — Sập
-
Fused RMSNorm(Chuẩn hóa Lõi củaLlama/Qwen/DeepSeek):\[\mathbf{y} = \frac{\mathbf{x}}{\sqrt{\frac{1}{N}\sum_{j=1}^N x_j^2 + \varepsilon}} \odot \mathbf{w}.\]PyTorch Eager phát sinh
5lượt đọc/ghiHBM(3,590.0 KBtrên128 × 1024). Nhânfused_rmsnorm_kernelcủaTritongom bình phương, cộng dồnfp32, tínhtl.rsqrt, và nhân trọng số \(\mathbf{w}\) trong 1 nhân duy nhất (1,028.0 KBHBM, cắt3.49xlưu lượng (-71.4%),max_abs_err = 0.00e+00, và tăng tốc4.91xtheo Roofline nhờ triệt tiêu4lần trễ phóng nhân!).
1.3 Tiled MatMul, Ánh xạ L2 Cache Swizzling (GROUP_SIZE_M) & @triton.autotune#
Phép nhân ma trận \(\mathbf{C} = \mathbf{A}\mathbf{B}\) (\(\mathbf{A} \in \mathbb{R}^{M \times K}\), \(\mathbf{B} \in \mathbb{R}^{K \times N}\)) chia lưới đầu ra thành \(\lceil M / B_M \rceil \times \lceil N / B_N \rceil\) khối CTA. Mỗi CTA \((\text{pid}_m, \text{pid}_n)\) thực hiện vòng lặp qua \(K/B_K\) lát cắt: nạp khối \(\mathbf{A}[\text{pid}_m, k]\) (B_M × B_K) và \(\mathbf{B}[k, \text{pid}_n]\) (B_K × B_N) vào SRAM, nhân qua Tensor Core tl.dot(a, b, acc) tích lũy fp32.
-
Vì sao Lập lịch
Row-MajorPhá HủyL2 Cache? VớiRow-Major(\(\text{pid}_m = \lfloor \text{pid} / G_N \rfloor, \;\text{pid}_n = \text{pid} \bmod G_N\)), hàng đầu tiên cácCTA\((0, 0), (0, 1), \dots, (0, G_N - 1)\) đọc toàn bộ lát cắt \(\mathbf{A}[0, :]\) (Hitliên tiếp) nhưng đồng thời kéo toàn bộ \(N \times K\) phần tử của \(\mathbf{B}\) qua bộ đệmL2. Nếu \(\text{Footprint}(\mathbf{B}) > \text{Capacity}(\text{L2})\), đến lúcCTA\((1, 0)\) khởi chạy thì các khối đầu của \(\mathbf{B}[:, 0]\) đã bị đẩy khỏiL2hoàn toàn! -
Toán học Hoán vị
L2 Cache Swizzling(GROUP_SIZE_M): Thay vì duyệt hết một hàng dài \(G_N\) khối,Tritongom từng dải \(G\) hàng khối (GROUP_SIZE_M) và duyệt ưu tiên theo cột bên trong dải \(G\) hàng đó (num_pid_in_group = G * num_pid_n):\[\text{group\_id} = \left\lfloor \frac{\text{pid}}{G \cdot G_N} \right\rfloor, \qquad \text{first\_m} = \text{group\_id} \cdot G, \qquad g_m = \min(G_M - \text{first\_m}, G),\]\[\text{pid}_m = \text{first\_m} + \big((\text{pid} \bmod (G \cdot G_N)) \bmod g_m\big), \qquad \text{pid}_n = \left\lfloor \frac{\text{pid} \bmod (G \cdot G_N)}{g_m} \right\rfloor.\]Cơ chế này biến băng tải truy cập thành các cửa sổ vuông \(G \times K\): trong
4CTAliên tiếp \((0, 0), (1, 0), (2, 0), (3, 0)\), cùng một khối cột \(\mathbf{B}[:, 0]\) giữ nóng trongL2phục vụ cả4khối \(\mathbf{A}\); ngay sau đó \((0, 1) \dots (3, 1)\) lại dùng trọn vẹn4hàng khối \(\mathbf{A}[0..3, :]\) vẫn đang nóng trongL2! TrongLab 15(512 × 512 × 256,BM=64, BN=64, BK=32,L2=256 KB),L2 Swizzle (G=4)vọtL2 Hit Ratetừ43.75% -> 81.25%(+37.50 pp), cắt số lần trượtL2từ576 -> 192và giảm3.00xlưu lượngDRAM(2,304.0 KB -> 768.0 KB). -
@triton.autotune& Cắt tỉa Dung lượngSRAM(SMEM): Một khối càng lớn \((B_M, B_N)\) càng tăng cường độ số học (\(\frac{2 B_M B_N B_K}{2(B_M B_K + B_K B_N)}\)), nhưng đường ống phần mềmnum_stages(\(S\)) lại nhân bội dung lượng bộ đệmSRAM:\[S_{\text{SMEM}} = S \cdot (B_M B_K + B_K B_N) \cdot b_{\text{elem}} \le S_{\text{SMEM, max}}\;(228\;\text{KB trên H100}).\]Trong
Lab 15(Test 12),@triton.autotunetự động loại bỏ cấu hình(256, 256, 64, S=4)vì đòi hỏi256.0 KB > 228.0 KBSMEMvà chọn điểm tối ưu Pareto(BM=128, BN=128, BK=32, G=4, S=4)(64.0 KB SMEM), đạt235.2 TFLOP/s(9.55xnhanh hơn cấu hình cơ sở32×32,24.6 TFLOP/s).
1.4 FlashAttention-2 Forward Từ Gốc: Chia Khối SRAM \(B_r \times B_c\) & Đẳng thức Chuẩn hóa Lại#
Nhân chú ý chuẩn \(\mathbf{O} = \operatorname{softmax}\!\left(\frac{\mathbf{Q}\mathbf{K}^\top}{\sqrt{d_k}} + \mathbf{M}_{\text{causal}}\right)\mathbf{V}\) (\(\mathbf{Q}, \mathbf{K}, \mathbf{V} \in \mathbb{R}^{B \times H \times N \times d}\)) có độ phức tạp tính toán \(O(N^2 d)\) nhưng bị đóng băng bởi dung lượng bộ nhớ trung gian \(O(N^2)\) khi phải ghi hai ma trận \(\mathbf{S}, \mathbf{P} \in \mathbb{R}^{B \times H \times N \times N}\) ra HBM. Ở Llama-3 32 Heads, N = 32,768 (fp16), chỉ riêng \(\mathbf{S}\) và \(\mathbf{P}\) đã đòi hỏi 128.0 GB (131,072 MB), vượt trần 80 GB của H100 và gây sập OOM tức thì!
FlashAttention-2 (Dao, ICLR 2024) đảo ngược thứ tự vòng lặp (đặt khối truy vấn \(\mathbf{Q}_i \in \mathbb{R}^{B_r \times d}\) ở vòng lặp ngoài để giữ cố định trong SRAM/thanh ghi của từng CTA, và cuộn các khối khóa/giá trị \(\mathbf{K}_j, \mathbf{V}_j \in \mathbb{R}^{B_c \times d}\) ở vòng lặp trong):
-
Tích Điểm & Mặt nạ Nhân quả Theo Khối: Tại mỗi bước \(j\):
\[\mathbf{S}_{ij} = \frac{\mathbf{Q}_i \mathbf{K}_j^\top}{\sqrt{d}} \in \mathbb{R}^{B_r \times B_c}, \qquad \mathbf{S}_{ij}[r, c] \leftarrow -\infty \;\;\text{nếu } (\text{causal} \land r < c) \lor c \ge N.\]Tối ưu cắt nửa tính toán (
Causal Block Skipping): Mọi khối cột có \(c_{\text{start}} \ge r_{\text{end}}\) nằm hoàn toàn phía trên đường chéo chính nên được bỏ qua hoàn toàn, cắt gần50%số phép toán và giảm tổng lưu lượng đọc+ghiHBM(total HBM Read+Write traffic: đọc \(\mathbf{Q}, \mathbf{K}, \mathbf{V}\) và ghi \(\mathbf{S}, \mathbf{P}, \mathbf{O}\) ở Attention chuẩn so với bỏ hoàn toàn \(\mathbf{S}, \mathbf{P}\), bỏ khối \(\mathbf{K}, \mathbf{V}\) tam giác trên và chỉ ghi \(\mathbf{O}, L\) ởFlashAttention-2) từ18.00 MBxuống còn5.52 MB(3.26xgiảm tổng trafficHBMtạiN=512,Lab 15). -
Đẳng thức Chuẩn hóa Lại Trực tuyến (
Exact Online Rescaling): Khác với phiên bản v1 chia cho \(\ell_i\) ở từng bước trong, FlashAttention-2 giữ bộ tích lũy chưa chia mẫu số \(\tilde{\mathbf{O}}_i\) xuyên suốt vòng lặp để giảm bớt phép chia véc-tơ đắt đỏ và rút ngắn chuỗi phụ thuộc lệnh:\[m_i^{\text{new}} = \max\!\big(m_i^{\text{old}}, \;\operatorname{rowmax}(\mathbf{S}_{ij})\big), \qquad \alpha = e^{m_i^{\text{old}} - m_i^{\text{new}}}, \qquad \tilde{\mathbf{P}}_{ij} = e^{\mathbf{S}_{ij} - m_i^{\text{new}}},\]\[\ell_i^{\text{new}} = \alpha \odot \ell_i^{\text{old}} + \operatorname{rowsum}(\tilde{\mathbf{P}}_{ij}), \qquad \tilde{\mathbf{O}}_i^{\text{new}} = \operatorname{diag}(\alpha)\,\tilde{\mathbf{O}}_i^{\text{old}} + \tilde{\mathbf{P}}_{ij}\,\mathbf{V}_j.\]Lưu ý biên toán học (
-inf - (-inf)Guard): Nếu một khối đầu toàn bộ phần tử đều bị che nhân quả (\(m_i^{\text{old}} = m_i^{\text{new}} = -\infty\)), biểu thức \(e^{-\infty - (-\infty)}\) dễ sinhNaN; cần gán tường minh \(\alpha = \text{tl.where}((m_i == -\infty) \mid (m_{\text{new}} == -\infty),\, 0.0,\, e^{m_i - m_{\text{new}}})\) và \(\tilde{\mathbf{P}}_{ij} = \text{tl.where}(\text{valid\_mask},\, e^{\mathbf{S}_{ij} - m_{\text{new}}},\, 0.0)\) (cả trongfused_online_softmax_kernellẫnflash_attn_fwd_kernel). -
Epilogue Duy nhất Ra
HBM(\(O(N)\)): Sau khi quét hết các khối \(\mathbf{K}_j, \mathbf{V}_j\),CTAchia duy nhất một lần:\[\mathbf{O}_i = \operatorname{diag}(\ell_i)^{-1}\tilde{\mathbf{O}}_i, \qquad L_i = m_i + \ln(\ell_i) \in \mathbb{R}^{B_r}.\]Nhờ chỉ xuất vectơ
LogSumExp\(L\) kích thước \(O(N)\) để dùng lại cho pha lan truyền ngược (activation recomputation thay vì lưu ma trận \(\mathbf{P}\)), đỉnh bộ nhớHBMtrung gian giảm từ8.00 MB -> 16.0 KB(512x) tạiN=512và131,072 MB -> 4.00 MB(32,768x) tạiN=32K, với sai số tuyệt đối cực đại chỉ3.58e-07so vớiPyTorch SDPA!
Trụ cột 2 — Kiến trúc SOTA Triton 3.2–3.5, Hệ sinh thái DSL 2025–2026, TorchInductor & FlashAttention-3/4#
2.1 Nguyên thủy SOTA OpenAI Triton 3.2–3.5, Hệ sinh thái DSL & FlashAttention-3/4 (Hopper/Blackwell)#
-
tl.make_block_ptr& APITMAHướng Đối tượng (tl.make_tensor_descriptor+Ragged TMA): Thay vì tự viết phép cộng con trỏ 2D (ptr + offs_m[:, None]*stride_m + offs_n[None, :]*stride_n) hay gọi API thử nghiệm đã lỗi thời (tl.experimental_descriptor_loadcũ),Triton 3.2–3.5chuẩn hóa bộ mô tả phần cứng Tensor Memory Accelerator (TMA) qua giao diện hướng đối tượngtl.make_tensor_descriptor(...)(hoặcTensorDescriptor.from_tensorphía host) kết hợpdesc.load(...)/desc.store(...):python6 dòng# Triton 3.2–3.5 Object-Oriented TMA Descriptor (Hopper H100 / Blackwell B200) desc_a = tl.make_tensor_descriptor( a_ptr, shape=[M, K], strides=[K, 1], block_shape=[BLOCK_M, BLOCK_K] ) a_tile = desc_a.load([pid_m * BLOCK_M, k_offset]) desc_c.store([pid_m * BLOCK_M, pid_n * BLOCK_N], acc.to(c_ptr.dtype.element_ty))Trên
H100/B200,TMAchép bất đồng bộ cả khối2D/3DtừHBM -> SMEM, tự kiểm biên điền0mà không tốn thanh ghi tính địa chỉ, đồng thời hỗ trợRagged TMAcho phép nạp chuỗi chiều dài biến thiên (cu_seqlens) không cần đệm vuông. -
Đường ống Phần mềm (
num_stages),WarpSpec& Bộ đo Nội nhânProton(triton.profiler):num_stages=3..4biến vòng lặpfor k in range(...)thành đường ống đa tầng che lấp~400–600chu kỳ trễHBM.WarpSpec(Triton 3.3–3.5): Chú thích vòng lặptl.range(..., warp_specialize=True)/WarpSpecializationcho phép trình biên dịchTritontự tách warps Producer (gọiTMAbơmSMEM) khỏi warps Consumer (WGMMA/tcgen05.mma), đưa kỹ thuật cấp thấp củaFlashAttention-3về thẳng Python.Proton(triton.profiler): Trình đo hiệu năng nội nhân tích hợp sẵn củaTriton(proton.start(),proton.scope(),proton.finalize()), cho phép đo chu kỳ từng khối/warp vàTFLOP/sngay trong vòng lặp phát triển mà không phải chạy dấu vết nặng nề củaNsight Computeở mọi bước.
-
Nhân Bền vững (
Persistent Kernels) & Hệ sinh thái DSL Nhân GPU2025–2026: Thay vì phóng hàng nghìnCTAgây nhiễuwave quantizationvà nguộiL2,Persistent Kernelphóng đúngCTA = num_sms(132trênH100) và cho mỗiCTAlặp qua nhiều khối. Bên cạnhTriton 3.5, hệ sinh thái DSL biên dịch nhân2025–2026phân tầng rõ rệt theo trục năng suất vs kiểm soát phần cứng:Gluon: DSL tầng thấp chính thức trongTriton 3.4+/3.5, mở quyền kiểm soát tường minh bố cục thanh ghi/SMEM,TMAvà đồng bộ warp ngang hàngCUTLASSngay trong hệTriton.Helion: DSL bậc cao củaPyTorch/Metadùng cú pháp chỉ mục Pythonic tự nhiên và tự động tìm kiếm không gian khối, biên dịch xuống nhânTritontối ưu.CuTe-DSL(CUTLASS 4.x) &TileLang:CuTe-DSLđưa bộ bố cụcCuTevà lệnhBlackwell tcgen05.mma/TMEMlên Python (nền tảng xây dựngFlashAttention-4), cònTileLangcho phép lập lịch bộ nhớ/đường ống cấp khối đa nền tảng (CUDA/AMDGPU).
-
Từ
FlashAttention-3(Hopper H100) đếnFlashAttention-4(Blackwell B200):FlashAttention-3(Shah et al., 2024–2025,H100): Phá trần~35%của FA-2 bằng Producer–Consumer Warp Specialization + Ping-Pong gối đầuWGMMAvớiSFU exp2fvà Incoherent Processing (biến đổi trực giao Hadamard choFP8), đạt~75%đỉnhH100(~740 TFLOP/sFP16,1.2 PFLOP/sFP8).FlashAttention-4(CuTe-DSLtrênBlackwell B200, 2025–2026): Trên kiến trúcBlackwell B200, tốc độTensor Core(tcgen05.mma) tăng gấp đôi (~2.25 PFLOP/sBF16/FP16), nhưng thông lượng cụm hàm siêu việtSFU(exp2f) không tăng tương xứng (asymmetric hardware scaling), biến phép tínhexpthành nút thắt cổ chai mới!FlashAttention-4(viết bằngCuTe-DSL) giải quyết nút thắt này bằng (a) mô phỏngexpbằng phần mềm (software exp emulation) chuyển bớt tải từSFUsang các đơn vịFMA/ALUrảnh rỗi, (b) tái chuẩn hóa có chọn lọc (selective rescaling) bỏ qua phép nhân \(\alpha \cdot \tilde{\mathbf{O}}\) khi độ lệch cực đại \(\Delta m\) nhỏ dưới ngưỡng an toàn, và (c) đường ống bất đồng bộTMA/TMEMđa CTA, đạt tới1,613 TFLOPS(71%hiệu suất đỉnhB200)!
2.2 torch.compile (TorchInductor) vs Nhân Triton Viết Tay & Đóng gói @torch.library.triton_op#
Khi nào dùng torch.compile, khi nào phải tự viết hoặc dùng Liger-Kernel / Unsloth?
torch.compile(model, mode="max-autotune")(TorchInductor): Tự động dò đồ thị tính toán (FX Graph), thực hiện dung hợp dọc & ngang (Pointwise + Reduction Fusion) và sinh mã nguồnOpenAI Tritonhoàn chỉnh ngay lúc biên dịch (AOTInductorcho suy luận không trễcold-start). Với90%các lớp chuẩn (MLPSwiGLU,RMSNorm,Cross-Entropycơ bản),TorchInductorđã đạt85%–95%tốc độ nhân viết tay mà không cần bảo trì mã GPU.- Giới hạn của Trình biên dịch Tự động — Nơi
Liger-Kernel&UnslothÁp đảo:- Không tự phát hiện biến đổi thuật toán (
Algorithmic Reformulation):TorchInductorKHÔNG thể tự suy raOnline Softmax + FlashAttentionhayFused Cross-Entropy Chunking(tính trực tiếp log-softmax trên từ điển128Kvocab mà không bao giờ vật chất hóa tensorlogitsFP32khổng lồ —Liger-Kernelcắt~60%–80%VRAM huấn luyện LLM nhờ dung hợp trực tiếp lớp chiếu tuyến tính cuối +Cross-Entropy!). - Đứt gãy Đồ thị (
Graph Breaks) & Hình dạng Động (Dynamic Shapes): Khi có nhánh điều kiện Python hoặc độ dài chuỗiseq_lenthay đổi liên tục qua từng yêu cầu phục vụ,torch.compilebị vỡ đồ thị hoặc phải biên dịch lại tốn hàng giây — trong khi nhânTritonviết tay (UnslothchoRoPE + RMSNorm + LoRA,FlashInfer/vLLMchoPagedAttentionkhông liên tục KV-cache ở Track 2 Phần 4) xử lý mọi bước nhảy bộ nhớ không đồng nhất (ragged/paged batches) trong một nhân duy nhất!
- Không tự phát hiện biến đổi thuật toán (
Để nhúng một nhân Triton viết tay vào mô hình torch.compile / AOTInductor mà không gây đứt gãy đồ thị (0 graph breaks) và tương thích hoàn chỉnh với FakeTensor/Autograd, chuẩn công nghiệp PyTorch 2.5+ sử dụng @torch.library.triton_op + wrap_triton + torch.library.opcheck (mẫu minh họa tích hợp CUDA+Triton):
import torch
from triton_kernels.vector_and_fused_norm import fused_rmsnorm_kernel
@torch.library.triton_op("fsds::fused_rmsnorm", mutates_args={})
def fused_rmsnorm_op(x: torch.Tensor, weight: torch.Tensor, eps: float = 1e-6) -> torch.Tensor:
"""Wrap custom Triton kernel as a compile-safe PyTorch custom op (zero graph breaks)."""
out = torch.empty_like(x)
grid = lambda meta: (x.shape[0],) # 1 CTA per row
torch.library.wrap_triton(fused_rmsnorm_kernel)[grid](
x, weight, out, x.stride(0), x.shape[1], eps
)
return out
@fused_rmsnorm_op.register_fake
def _(x: torch.Tensor, weight: torch.Tensor, eps: float = 1e-6) -> torch.Tensor:
return torch.empty_like(x)
# Khi triển khai trên Linux+CUDA: kiểm định schema, FakeTensor & AOTAutograd trước khi đưa vào torch.compile:
# torch.library.opcheck(fused_rmsnorm_op, (x_cuda, w_cuda), {"eps": 1e-6})
# compiled_fn = torch.compile(fused_rmsnorm_op, fullgraph=True, mode="max-autotune")
Bốn Bẫy Triển khai Nhân Triton Trong Sản xuất (Principal Production Traps):
- Bão Khóa
NFSTrênKubernetes(TRITON_CACHE_DIR=/tmp/triton_cache): Mặc định Triton lưu tệp biên dịch.cubin/.sovào~/.triton/cache— thường gắnNFS/EFSdùng chung giữa nhiều pod. Khi hàng trăm pod khởi động đồng thời sẽ gây tranh chấp khóa tệp làm treo cold-start; luôn gánTRITON_CACHE_DIR=/tmp/triton_cache(ổNVMe/tmpfscục bộ từng node). - Tràn Thanh ghi Xuống Bộ nhớ Cục bộ (
Register Spillingtolmem&maxnreg): Cấu hìnhBLOCK_M/BLOCK_Nquá lớn hoặc unroll vòng lặp sâu làm vượt trần255thanh ghi/luồng (65,536regs/SM), khiến trình biên dịch âm thầm đẩy biến xuốnglocal memory (lmem)trênHBMvà làm sập tốc độ5–10x. Luôn kiểm trabytes spill stores/loadsquaptxas/Proton/Nsight Compute, giảm cỡ khối hoặc giới hạnmaxnreg. - Mất Độ Chính xác
FP32Ngầm DoTF32(allow_tf32=False/input_precision="ieee"): Trên Ampere/Hopper/Blackwell,tl.dot(a, b)với đầu vàofp32mặc định ép vềTF32(10-bit phần định trị!), gây trôi sai số trên tính toán khoa học hoặc đối chứngunit testkhắt khe. Phải chỉ định tường minhinput_precision="ieee"(allow_tf32=False) khi cần chuẩnIEEE-754 fp32. - Mất Cân bằng Tải
MoE& Chuỗi Ragged (Chunked Atomic Work-Stealing): Các lớpMixture-of-Experts(Mixtral,DeepSeek-V3) định tuyến số token lệch mạnh giữa các chuyên gia (experts), làm lưới tĩnh sinh straggler (SM xong sớm ngồi chờ). Kỹ thuật sản xuất dùng nhân bền vững (Persistent CTA) + cướp việc nguyên tử theo khối (Chunked tl.atomic_add Work-Stealing) để phân phối động các khối hợp lệ mà không lãng phí FLOP đệm0.
Trụ cột 3 — Hệ sinh thái 2026 & Mã nguồn Thực thi Độc lập#
Đoạn mã dưới đây chạy hoàn toàn độc lập trong .venv (Python 3.12, torch, numpy), kiểm chứng trực tiếp ba cơ chế cốt lõi của Chương 27: (1) Online Safe Softmax bất biến trên dải cực trị [-1000, +1000] & phát hiện lỗi đệm other=0.0, (2) ánh xạ song ánh L2 Cache Swizzling (GROUP_SIZE_M=4) kèm đếm trúng bộ đệm LRU, và (3) FlashAttention-2 Forward Causal Tiled khớp tuyệt đối với torch.nn.functional.scaled_dot_product_attention:
"""Pillar 3 Executable Specimen: Triton-Style Online Softmax, L2 Swizzle & FlashAttention-2."""
from __future__ import annotations
import json
import math
from collections import OrderedDict
import torch
import torch.nn.functional as F
def run_ch27_specimen() -> dict[str, float | int | bool]:
"""Verify Online Softmax stability, L2 Swizzle hit lift, and FlashAttention-2 parity."""
torch.manual_seed(42)
# 1. Online Safe Softmax (Milakov-Gimelshein) on extreme [-1000, +1000] & odd cols=300
x_ext = torch.linspace(-1000.0, 1000.0, steps=300).unsqueeze(0).expand(4, 300).clone()
unsafe_has_nan = bool(torch.isnan(torch.exp(x_ext) / torch.exp(x_ext).sum(-1, keepdim=True)).any())
block = 128
out_sm = torch.empty_like(x_ext)
for r in range(x_ext.shape[0]):
m_i = torch.tensor(-float("inf"))
l_i = torch.tensor(0.0)
for c0 in range(0, 300, block):
tile = x_ext[r, c0 : c0 + block]
m_new = torch.maximum(m_i, tile.max())
alpha = torch.exp(m_i - m_new) if not torch.isinf(m_i) else torch.tensor(0.0)
l_i = l_i * alpha + torch.exp(tile - m_new).sum()
m_i = m_new
out_sm[r] = torch.exp(x_ext[r] - m_i) / l_i
online_softmax_err = float((out_sm - torch.softmax(x_ext, dim=-1)).abs().max().item())
# 2. L2 Cache Swizzle (GROUP_SIZE_M=4) vs Row-Major on 8x8 tile grid (L2=64 tiles)
def sim_l2_hit(group_m: int, swizzle: bool) -> float:
num_m, num_n, num_k, cap = 8, 8, 8, 64
lru: OrderedDict[tuple[str, int, int], None] = OrderedDict()
hits, misses = 0, 0
for pid in range(num_m * num_n):
if not swizzle:
pm, pn = pid // num_n, pid % num_n
else:
in_grp = group_m * num_n
gid = pid // in_grp
fm = gid * group_m
gm = min(num_m - fm, group_m)
pm = fm + ((pid % in_grp) % gm)
pn = (pid % in_grp) // gm
for k in range(num_k):
for tag in (("A", pm, k), ("B", k, pn)):
if tag in lru:
hits += 1
lru.move_to_end(tag)
else:
misses += 1
if len(lru) >= cap:
lru.popitem(last=False)
lru[tag] = None
return hits / (hits + misses)
row_major_l2 = sim_l2_hit(1, False)
swizzled_l2 = sim_l2_hit(4, True)
# 3. Simplified FlashAttention-2 Forward (Causal, odd N=149, Br=32, Bc=32) vs SDPA
b, h, n, d = 1, 2, 149, 32
q = torch.randn(b, h, n, d)
k = torch.randn(b, h, n, d)
v = torch.randn(b, h, n, d)
scale = 1.0 / math.sqrt(d)
o_fa = torch.zeros_like(q)
for bi in range(b):
for hi in range(h):
for r0 in range(0, n, 32):
r1 = min(r0 + 32, n)
q_blk = q[bi, hi, r0:r1]
m_i = torch.full((r1 - r0, 1), -float("inf"))
l_i = torch.zeros((r1 - r0, 1))
acc = torch.zeros((r1 - r0, d))
for c0 in range(0, r1, 32):
c1 = min(c0 + 32, n)
s_ij = (q_blk @ k[bi, hi, c0:c1].T) * scale
q_idx = torch.arange(r0, r1).unsqueeze(1)
k_idx = torch.arange(c0, c1).unsqueeze(0)
s_ij = s_ij.masked_fill(k_idx > q_idx, -float("inf"))
m_ij = torch.maximum(m_i, s_ij.max(-1, keepdim=True).values)
alpha = torch.where(torch.isinf(m_i), torch.zeros_like(m_i), torch.exp(m_i - m_ij))
p_ij = torch.where(torch.isinf(s_ij) & (s_ij < 0), torch.zeros_like(s_ij), torch.exp(s_ij - m_ij))
acc = acc * alpha + p_ij @ v[bi, hi, c0:c1]
l_i = l_i * alpha + p_ij.sum(-1, keepdim=True)
m_i = m_ij
o_fa[bi, hi, r0:r1] = acc / l_i
sdpa_ref = F.scaled_dot_product_attention(q, k, v, is_causal=True)
fa_max_err = float((o_fa - sdpa_ref).abs().max().item())
return {
"unsafe_exp_nan_on_1000": unsafe_has_nan,
"online_softmax_max_abs_err": round(online_softmax_err, 12),
"row_major_l2_hit_rate": round(row_major_l2, 4),
"swizzled_g4_l2_hit_rate": round(swizzled_l2, 4),
"flash_attn_causal_odd_n_max_err": round(fa_max_err, 9),
}
if __name__ == "__main__":
print(json.dumps(run_ch27_specimen(), indent=2))
Trụ cột 4 — Phòng thí nghiệm Thực chiến (Lab 15: triton_kernels + triton_kernels_lab) & Rubric Kiểm thử#
4.1 Kiến trúc Hai Tầng (Two-Tier) của Lab 15#
Toàn bộ mã nguồn thực nghiệm được đóng gói chuẩn hóa tại labs/lab-15-triton-kernels-from-scratch/README.md (100% ngoại tuyến trên Python 3.12 + PyTorch 2.15+cpu, tất định seed=42, khóa 34 gói bằng uv.lock, cấm tuyệt đối pickle/joblib):
- Tầng 1 (
triton_kernels/— Mã nguồn NhânOpenAI Triton 3.xThuần):triton_kernels/__init__.py: tự động nạptritonthật trên hệ thốngLinux + CUDAhoặc nạp lớp decorator kiểu tĩnh@triton.jit/@triton.autotunekhông lỗimypy --stricttrên CPU.triton_kernels/vector_and_fused_norm.py:vec_add_kernel,fused_online_softmax_kernel,fused_rmsnorm_kernel.triton_kernels/tiled_matmul_and_flash_attn.py:tiled_matmul_swizzled_kernel(tl.make_block_ptr,GROUP_SIZE_M,tl.dot) vàflash_attn_fwd_kernel(\(B_r \times B_c\)SRAM+ nhân quả).
- Tầng 2 (
src/triton_kernels_lab/— Bộ Mô phỏngSPMDThực thi TrênPyTorch+ Kiểm toánHBM/L2/Roofline +OpenTelemetry):spmd_tile_engine.py:HardwareSpec,HBMTraceStats,L2SwizzleResult,spmd_vector_add(với canary buffer phát hiện tràn biên),spmd_fused_online_softmax,spmd_fused_rmsnorm,spmd_tiled_matmul(tích hợp bộ đệmLRU L2thực thi theopid), vàaudit_tier1_triton_kernels_ast.flash_attn_and_autotune.py:spmd_flash_attention_fwd,standard_materialized_attention, quét suy giảm đỉnh bộ nhớLlama-3 32Htới32,768token, bộ tìm kiếm@triton.autotunecó cắt tỉa228 KB SMEM, và ghi vếtOpenTelemetry(InMemorySpanExporter).
4.2 Bảng Kết quả Thực nghiệm Chuẩn hóa (seed=42, artifacts/ch27_lab15_results.json)#
| Phân hệ / Ca Thất bại | So sánh Cơ sở (Baseline) |
Giải pháp Triton SOTA |
Chỉ số Đo Thực tế (seed=42) |
|---|---|---|---|
Ca 1 & 2: VecAdd & Mặt nạ Biên |
Unmasked (N=100,003) |
Masked (mask = offsets < n) |
93 ô canary bị hỏng \(\to\) 0 hỏng, max_abs_err = 0.0 (AI = 0.083 FLOP/B) |
Ca 1 & 2: Fused Online Softmax |
Eager 5-ops (3,110.0 KB) & Zero-Pad (3.00e-03) |
Triton Online / SRAM-Resident |
4.00x giảm HBM (777.0 KB, -75.0%), 1.19e-07 err; 0 NaN trên [-1000,+1000] |
Ca 1: Fused RMSNorm (128×1024) |
Eager 5-ops (3,590.0 KB, 26.1 us) |
Triton Fused (1 kernel, 5.31 us) |
3.49x giảm HBM (1,028.0 KB), 4.91x tăng tốc Roofline, err = 0.0 |
Ca 3: L2 Swizzle MatMul (512×512×256) |
Row-Major G=1 (43.75% hit) |
L2 Swizzled G=4 (256 KB L2) |
L2 Hit = 81.25% (+37.50 pp), 3.00x cắt DRAM (2,304 -> 768 KB), err = 3.43e-05 |
Ca 4: FlashAttention-2 Forward |
Std O(N^2) (8.00 MB @512; 128 GB @32K) |
FlashAttn-2 (Br=64, Bc=64) |
512x giảm HBM @512 (16.0 KB), 32,768x @32K (4.00 MB), err = 3.58e-07 |
@triton.autotune & OTel/AST |
Naive 32×32 G=1 S=1 (24.6 TFLOP/s) |
128×128×32 G=4 S=4 (64 KB SMEM) |
235.2 TFLOP/s (9.55x), loại 1 mẫu >228 KB, 5/5 AST & 11 OTel spans |
4.3 Hợp đồng 17 Bài kiểm thử Tự động (tests/test_triton_kernels_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/, scripts/, triton_kernels/, cấm pickle, joblib, cloudpickle, dill, shelve, marshal |
2 |
test_02_pydantic_v2_strict_schemas_extra_forbid |
Khóa extra="forbid" và ràng buộc biên trên HardwareSpec, HBMTraceStats, L2SwizzleResult, AutotuneConfig, FlashAttnTraceResult |
3 |
test_03_vector_add_masking_and_tail_canary_guard |
Chứng minh không mask làm hỏng 21 ô canary đuôi tại N=1,003; bật mask cho err = 0.0 và bảo toàn canary |
4 |
test_04_online_softmax_numerical_equivalence_and_extreme_logits |
spmd_fused_online_softmax khớp torch.softmax (< 1e-6) trên dải cực trị [-1000, +1000] không NaN |
5 |
test_05_softmax_tail_padding_neg_inf_vs_zero_bug_and_hbm_cut |
Bắt lỗi other=0.0 (err > 1e-3); chứng minh cắt >= 3.5x (4.00x) HBM ở SRAM và >= 2.5x (2.67x) ở multi-tile |
6 |
test_06_fused_rmsnorm_equivalence_and_hbm_traffic_reduction |
Fused RMSNorm khớp PyTorch (< 1e-5), cắt >= 3.0x (3.49x) HBM và tăng tốc >= 2.5x (4.91x) Roofline |
7 |
test_07_tiled_matmul_exact_equivalence_and_l2_swizzle_hit_lift |
Tiled MatMul khớp a @ b (< 1e-3); GROUP_SIZE_M=4 tăng hit > +25 pp (+37.5 pp) và cắt >= 2.5x (3.00x) DRAM |
8 |
test_08_l2_swizzle_coord_bijection_all_pids |
Kiểm chứng compute_swizzled_cta_coords là song ánh chính xác trên cả lưới chia hết lẫn lưới lẻ (7, 5) |
9 |
test_09_flash_attention_non_causal_equivalence_vs_sdpa |
FlashAttention-2 (causal=False) khớp F.scaled_dot_product_attention với max_abs_err < 1e-5 và lse hữu hạn |
10 |
test_10_flash_attention_causal_equivalence_and_non_divisible_seq |
FlashAttention-2 (causal=True) khớp SDPA trên cả chuỗi lẻ N=149, Br=32, Bc=32 với max_abs_err < 1e-5 |
11 |
test_11_flash_attention_hbm_peak_reduction_and_oom_prevention |
Đạt >= 500x (512x) giảm đỉnh HBM tại N=512 và >= 30,000x (32,768x) tại N=32K tránh OOM 80 GB |
12 |
test_12_autotune_sram_pruning_and_pareto_winner |
Cắt tỉa cấu hình vượt 228 KB SMEM, chọn ứng viên Pareto vượt cơ sở >= 1.5x (9.55x) |
13 |
test_13_tier1_triton_kernels_ast_and_shim_structural_audit |
Xác nhận AST đủ 5/5 nhân @triton.jit, 4/4 @triton.autotune, nguyên thủy tl.* và shim [grid] chạy sạch |
14 |
test_14_hypothesis_property_non_divisible_block_and_seq_lens |
Kiểm thử Hypothesis sinh ngẫu nhiên chiều dài lẻ 17..199, block_size và causal giữ sai số < 1e-5 |
15 |
test_15_opentelemetry_real_span_instrumentation |
InMemorySpanExporter thu đủ 6 loại span OpenTelemetry across toàn bộ nhân & autotuner |
16 |
test_16_benchmark_determinism_and_cli_workbench_panels_schema |
Kết quả seed=42 tất định tuyệt đối; CLI xuất 6 KPI, 4 biểu đồ cột và 4 bảng workbench_panels |
17 |
test_17_hardware_roofline_ridge_point_and_memory_bound_classification |
Điểm gãy Roofline H100 (~295.2 FLOP/B) phân loại đúng Softmax là memory-bound và tăng AI sau dung hợp |
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 Bảy Công trình & Trụ cột Kỹ nghệ Nền tảng (2018–2026)#
- Milakov, M. & Gimelshein, N. (2018). Online Normalizer Calculation for Softmax (
arXiv:1805.02867) — nền tảng toán học thu gọn Softmax 3-lượt thành 1-lượt trực tuyến bằng thừa số hiệu chỉnh \(\exp(m_{\text{old}} - m_{\text{new}})\). - Tillet, P., Kung, H. T. & Cox, D. (MAPL 2019) & OpenAI Triton
3.2–3.5(2024–2026). Triton: An Intermediate Language and Compiler for Tiled Neural Network Computations — từ mô hìnhSPMDcấp khối tới hệ sinh thái3.2–3.5(tl.make_tensor_descriptor/Ragged TMA,WarpSpec,Protontriton.profiler) và DSL tầng thấpGluon. - Dao, T. et al. (NeurIPS 2022) & Dao, T. (ICLR 2024). FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness & FlashAttention-2: Faster Attention with Better Parallelism and Work Partitioning — thuật toán chia khối \(B_r \times B_c\) giữ ma trận \(\mathbf{S}, \mathbf{P}\) thuần trong
SRAMvà tối ưu chia khối vòng ngoài theoQ. - Shah, J. et al. (2024–2025) &
FlashAttention-4(2025–2026). FlashAttention-3: Fast and Accurate Attention with Asynchrony and Low-precision (Hopper H100:TMAProducer/ConsumerWarp Specialization, Ping-PongWGMMA–Softmax,FP8Hadamard) vàFlashAttention-4(CuTe-DSLtrênBlackwell B200: xử lý bất đối xứng phần cứng giữatcgen05.mmavà cụmSFU expqua softwareexpemulation + selective rescaling, đạt1,613 TFLOPS(71%)). - Ansel, J. et al. (ASPLOS 2024). PyTorch 2: Faster Machine Learning Through Dynamic Python Bytecode Transformation and Graph Compilation (
TorchInductor/AOTInductor) — sinh nhânTritontự động từ đồ thịFXvà tích hợp nhân tùy biến không đứt gãy qua@torch.library.triton_op+wrap_triton+opcheck. - LinkedIn / HuggingFace (
Liger-Kernel, 2024–2025) &UnslothEngineering. Thư viện nhânTritonviết tay cho LLM (Fused Linear CrossEntropy,RMSNorm,RoPE,SwiGLU), minh họa sức mạnh dung hợp vượt ngưỡng bộ nhớ củatorch.compile. - Hệ sinh thái Kernel DSL
2025–2026(Gluon,Helion,CuTe-DSL,TileLang). Bộ công cụ phân tầng giữa kiểm soát phần cứng tối đa (Gluon,CuTe-DSL/CUTLASS 4.x) và năng suất tự động hóa cấp cao biên dịch xuốngTriton/PTX(Helion,TileLang).
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(SPMDvsSIMT& RooflineVector Add):CUDAđiều khiển luồng vô hướng từng thread kèm tự đồng bộ__shared__, cònTritonchạySPMDcấp khối véc-tơ (tl.program_id,tl.arange).VecAdd fp32có \(I_{\text{arith}} = 0.0833\;\text{FLOP/B} \ll 295.2\;\text{FLOP/B}\) nên bị nghẽn băng thôngHBMtuyệt đối.Q2(Mặt nạ Biên & Bẫyother=0.0): Thiếumask = offsets < nghi đè93ô nhớ lân cận (N=100,003); đặtother=0.0trên đuôiSoftmaxlàm \(\exp(0 - m_i)\) làm sai phân phối (err = 3.00e-03) — bắt buộc dùngother=-float("inf").Q3(Online SoftmaxMilakov–Gimelshein): Cập nhật trực tuyến \(m_{\text{new}} = \max(m_{\text{old}}, m_{\text{tile}})\) và \(\ell_{\text{new}} = \ell_{\text{old}} e^{m_{\text{old}} - m_{\text{new}}} + \sum e^{x - m_{\text{new}}}\) giữ ổn định tuyệt đối trên[-1000, +1000](4.66e-10err,0NaN) và loại bỏ ghi mảng \(\exp\) raHBM.Q4(Dung hợpSoftmax&RMSNorm): Dung hợp thu gọn5lần phóng nhân xuống1, cắt lưu lượngHBM4.00xchoSoftmax(3,110.0 -> 777.0 KB) và3.49xchoRMSNorm(3,590.0 -> 1,028.0 KB,4.91xtăng tốc Roofline).Q5(L2 Cache SwizzlingGROUP_SIZE_M):Row-Majorduyệt hết cột của \(\mathbf{B}\) làm trànL2(43.75%hit,4.50xDRAM);GROUP_SIZE_M=4tái sử dụng khối theo cụm4hàng đẩyL2 Hit Ratelên81.25%(+37.50 pp) và cắt3.00xDRAM.Q6(@triton.autotune& Giới hạnSMEM): Đường ốngnum_stagesnhân dung lượngSRAMtheo \(S \cdot (B_M B_K + B_K B_N) \cdot b\); cấu hình(256, 256, 64, S=4)cần256.0 KB > 228.0 KBH100 SMEMbị cắt tỉa, còn(128, 128, 32, G=4, S=4)đạt235.2 TFLOP/s(9.55x).Q7(FlashAttention-2 Forward& Đẳng thức Chuẩn hóa Lại): Chia khối \(B_r \times B_c\) giữ \(\mathbf{S}, \mathbf{P}\) trongSRAMvà dùng \(\tilde{\mathbf{O}}_{\text{new}} = \operatorname{diag}(\alpha)\tilde{\mathbf{O}}_{\text{old}} + \tilde{\mathbf{P}}_{ij}\mathbf{V}_j\) chỉ ghiOvà vectơLogSumExp\(O(N)\), giảm512xđỉnhHBMtạiN=512và32,768xtạiN=32K(4.00 MBvs128 GBOOM).Q8(SOTATriton 3.2–3.5,@torch.library.triton_op,Liger-Kernel&FlashAttention-3/4):tl.make_tensor_descriptor(TMA/Ragged TMA),WarpSpecvàProtonđưa lập lịch Hopper/Blackwell vào Python;@torch.library.triton_op+wrap_tritontránh đứt gãytorch.compile/AOTInductor;FlashAttention-3(H100,~75%) vàFlashAttention-4(CuTe-DSLtrênB200,software exp+selective rescaling,1,613 TFLOPS/71%) giải quyết nút thắt bất đối xứngTensor Core–SFU.
5.3 Sáu Bài tập Chuyên sâu & Thang chấm Rubric (ex1..ex6)#
- Bài tập 1 (
15%) — Phân tích Roofline & Mặt nạ BiênVector Add: Tính cường độ số học củaVecAddfp32vàfp16, đối chiếu với điểm gãy295.2 FLOP/BcủaH100. Chứng minh bằngspmd_vector_add(Test 03) hậu quả tràn canary khi bỏmask. - Bài tập 2 (
15%) — Dẫn xuấtOnline Safe Softmax& Bẫy Đệmother=0.0: Chứng minh công thức hiệu chỉnh \(\exp(m_{\text{old}} - m_{\text{new}})\) bất biến thang điểm trên[-1000, +1000]; phân tích định lượng sai số3.00e-03khi đệmother=0.0và mức tiết kiệmHBM4.00x(Softmax) /3.49x(RMSNorm) (Tests 04–06). - Bài tập 3 (
20%) — Toán họcL2 Cache Swizzling(GROUP_SIZE_M): Viết tay quỹ đạo16CTAđầu tiên của lưới8 × 8khiGROUP_SIZE_M=4; giải thích trên bộ đệmLRU 256 KBvì saoL2 Hit Ratetăng từ43.75% -> 81.25%(3.00xgiảmDRAM) và chứng minh tính song ánh với lưới lẻ (Tests 07–08). - Bài tập 4 (
20%) — Chứng minhFlashAttention-2& Tính Ngân sáchHBM: Dẫn xuất đẳng thức cộng dồn \(\tilde{\mathbf{O}}_i\) và vectơLogSumExp\(L_i\); tính dung lượng đỉnhHBMtạiN=512(8.00 MB -> 16.0 KB) vàN=32,768(128 GB OOM -> 4.00 MB) cho cấu hìnhLlama-3 32H, cùng cơ chế bỏ khối tam giác trên (Tests 09–11). - Bài tập 5 (
15%) — Tối ưu@triton.autotune,Triton 3.2–3.5,FA-3/FA-4& Bẫy Sản xuất: Viết công thức dung lượngSRAMphụ thuộcnum_stages, giải thích lý do(256, 256, 64, S=4)vượt trần228 KBH100, và đối chiếuTorchInductor,@torch.library.triton_op,Liger-Kernel,tl.make_tensor_descriptor,WarpSpec,FlashAttention-3/4(B200SFUbottleneck) cùng 4 bẫy sản xuất (TRITON_CACHE_DIR,lmemspill,allow_tf32=False, MoE atomic work-stealing) (Test 12). - Bài tập 6 (
15%) — Kiểm chứng Toàn trìnhLab 15(triton_kernels+triton_kernels_lab): Kiểm toán AST5/5nhân@triton.jit, chạyuv lock --check,ruff check,mypy src triton_kernels,scripts/run_lab_demo.py, và vượt qua trọn vẹn17/17 pytestkèmHypothesis&OpenTelemetry(Tests 01–02, 13–17).
| Tiêu chí Rubric | Đạt (Pass, 60–74%) |
Khá (Merit, 75–84%) |
Xuất sắc (Distinction, 85–100%) |
|---|---|---|---|
Nền tảng SPMD, Dung hợp & Mặt nạ (ex1, ex2) |
Viết đúng công thức Online Softmax, RMSNorm và chạy Tests 03–06 |
Giải thích định lượng Roofline 0.083 FLOP/B và sai số đệm other=0.0 (3.00e-03) |
Chứng minh chặt chẽ ổn định số học [-1000,+1000] và phân biệt SRAM-Resident (4.00x) vs Multi-Tile (2.67x) |
L2 Swizzle, FlashAttention-2 & SOTA (ex3, ex4, ex5) |
Mô tả được ánh xạ GROUP_SIZE_M, đẳng thức FlashAttention-2 và công thức SMEM |
Tính đúng L2 Hit (43.75% -> 81.25%), đỉnh HBM 512x/32,768x và cắt tỉa >228 KB |
Cài đặt chuẩn xử lý biên -inf - (-inf) trên chuỗi lẻ N=149 và đối chiếu sâu Triton 3.2–3.5/FA-3/FA-4 (B200)/4 bẫy sản xuất |
Thực nghiệm & Chất lượng Mã (ex6, Lab 15) |
Vượt qua 17/17 pytest, xuất đúng JSON artifact |
Đạt 0 lỗi ruff/mypy, khóa uv.lock và cổng AST cấm pickle |
Xác minh đầy đủ 5/5 nhân Tầng 1, 11 spans OpenTelemetry và workbench_panels (6 KPI, 4 bar, 4 bảng) |
HBM Traffic Footprint (KB): Eager Unfused vs Triton Fused Softmax & RMSNorm
Tiled GEMM L2 Cache Hit Rate (%): Naive Row-Major vs GROUP_SIZE_M Swizzle
Attention Intermediate Peak Memory (MB) at Llama-3 32 Heads, Seq=8192
Autotune Sweep Predicted Roofline Throughput (TFLOP/s on H100 SXM)
Failure Cases 1 & 2: Boundary Masking, Tail Padding & Kernel Fusion HBM Audit
| Kernel / Regime | Launches / HBM Bytes | Max Abs Err vs PyTorch | Diagnosis |
|---|---|---|---|
| VecAdd Masked (N=100003) | 1 / 1171.9 KB | 0.0e+00 | Guarded 93 tail elems; Canary OK |
| VecAdd Unmasked Bug (N=100003) | 1 / 1171.9 KB | 0.0e+00 | OOB Canary CORRUPTED (93 elems) |
| Softmax Eager Unfused (128x777) | 5 / 3110.0 KB | 1.19e-07 | Bandwidth-bound HBM round-trips |
| Softmax Zero-Pad Bug (other=0.0) | 1 / 1165.5 KB | 3.00e-03 | Corrupts denominator on non-divisible cols |
| Softmax Triton Online Tiled / SRAM | 1 / 1165.5 KB -> 777.0 KB | 1.19e-07 | 4.00x HBM cut; 0 NaN on [-1000,+1000] |
| RMSNorm Eager vs Triton Fused (128x1024) | 3590.0 KB -> 1028.0 KB | 0.00e+00 | 3.49x HBM cut (4.91x) |
Failure Case 3: Tiled GEMM Scheduling (Row-Major vs GROUP_SIZE_M L2 Swizzle)
| Schedule Mode | L2 Tile Hits / Misses | L2 Hit Rate & DRAM Amp | Max Abs Err vs PyTorch |
|---|---|---|---|
| Row-Major (G=1, 512x512x256) | 448 / 576 | 43.75% (4.50x compulsory) | 3.43e-05 |
| L2 Swizzled (G=4, 512x512x256) | 832 / 192 | 81.25% (1.50x compulsory) | 3.43e-05 |
| Swizzle Gain Summary | -384 DRAM misses | +37.50 pp (3.00x DRAM cut) | Exact Tile Equivalence PASS |
Failure Case 4: FlashAttention-2 Numerical Parity & O(N^2) -> O(N) HBM Scaling
| Regime / Context Length | Std HBM Peak O(N^2) | FlashAttn Peak O(N) | Reduction & Fidelity |
|---|---|---|---|
| Live Non-Causal (N=512, D=64) | 8.00 MB | 16.0 KB | 512x (err 1.79e-07) |
| Live Causal (N=512, D=64) | 8.00 MB | 16.0 KB | 512x (err 3.58e-07) |
| Odd Tail Causal (N=149, Br=32) | 173.4 KB | 1.2 KB | 149x (err 2.38e-07) |
| Llama-3 32H Projection (N=2048) | 512.0 MB | 0.25 MB | 2048x peak reduction |
| Llama-3 32H Projection (N=8192) | 8192.0 MB | 1.00 MB | 8192x peak reduction |
| Llama-3 32H Projection (N=32768) | 131072.0 MB [OOM >80GB] | 4.00 MB | 32768x peak reduction |
Triton @autotune Sweep: SRAM Capacity Pruning & Roofline Pareto Selection
| Tile Config (BM, BN, BK, G, S) | SMEM Footprint | L2 Hit / AI (FLOP/B) | Predicted TFLOP/s |
|---|---|---|---|
| (32, 32, 32, G=1, S=1) | 4.0 KB OK | 46.9% / 26.9 | 24.6 TFLOP/s |
| (32, 64, 32, G=4, S=2) | 12.0 KB OK | 81.2% / 73.1 | 83.4 TFLOP/s |
| (64, 64, 32, G=1, S=2) | 16.0 KB OK | 43.8% / 46.5 | 66.0 TFLOP/s |
| (64, 64, 32, G=4, S=3) | 24.0 KB OK | 81.2% / 102.4 | 149.4 TFLOP/s |
| (64, 128, 32, G=4, S=3) | 36.0 KB OK | 75.0% / 102.4 | 207.8 TFLOP/s |
| (128, 64, 32, G=4, S=3) | 36.0 KB OK | 37.5% / 46.5 | 94.5 TFLOP/s |
| (128, 128, 32, G=4, S=4) | 64.0 KB OK | 37.5% / 73.1 | 235.2 TFLOP/s [BEST] |
| (128, 128, 64, G=4, S=3) | 96.0 KB OK | 37.5% / 73.1 | 232.0 TFLOP/s |
| (256, 256, 64, G=4, S=4) | 256.0 KB PRUNED | 25.0% / 102.4 | 0.0 TFLOP/s |
02-track-1-data-science-and-ai/part-06-gpu-cuda-and-triton/labs/lab-15-triton-kernels-from-scratch
[build-system]
requires = ["setuptools>=68.0"]
build-backend = "setuptools.build_meta"
[project]
name = "triton-kernels-lab"
version = "0.1.0"
description = "Lab 15: Triton Kernel Engineering from Scratch (Vector Add, Fused Online Softmax & RMSNorm, L2-Swizzled Tiled MatMul, FlashAttention-2 Forward & Autotuning) for T1-P6-U02."
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"
strict = true
warn_return_any = true
warn_unused_ignores = true
ignore_missing_imports = true
"""Tier-1 OpenAI Triton 3.x Kernel Definitions with Clean Offline CPU Compatibility Shim.
On Linux CUDA environments where `triton` is installed, this module exposes the genuine
`triton` and `triton.language` runtime objects. On Windows/CPU-only environments, it provides
lightweight typed decorator and namespace shims so every `@triton.jit` and `@triton.autotune`
kernel remains importable, statically type-checkable (`mypy --strict`), and AST-auditable.
"""
from __future__ import annotations
import importlib
import importlib.util
from collections.abc import Callable
from dataclasses import dataclass, field
from typing import Any, Protocol, TypeVar, cast
F = TypeVar("F", bound=Callable[..., Any])
@dataclass(frozen=True, slots=True)
class TritonConfigShim:
"""Offline representation of `triton.Config`."""
kwargs: dict[str, Any]
num_warps: int = 4
num_stages: int = 3
num_ctas: int = 1
@dataclass(frozen=True, slots=True)
class TritonKernelMetadata:
"""Metadata attached to decorated Triton kernels for static verification."""
fn_name: str
is_jitted: bool = True
autotune_configs: tuple[TritonConfigShim, ...] = field(default_factory=tuple)
autotune_key: tuple[str, ...] = field(default_factory=tuple)
class JitKernelHandle[KT: Callable[..., Any]]:
"""Typed wrapper matching Triton JIT kernel indexing `kernel[grid](*args, **kwargs)`."""
def __init__(self, fn: KT) -> None:
self.fn: KT = fn
self.__name__: str = getattr(fn, "__name__", "triton_kernel")
self.__doc__: str | None = getattr(fn, "__doc__", None)
self.__wrapped__: KT = fn
self.triton_meta: TritonKernelMetadata = TritonKernelMetadata(fn_name=self.__name__)
def __getitem__(self, grid: Any) -> Callable[..., Any]:
def _launch(*args: Any, **kwargs: Any) -> dict[str, Any]:
return {
"kernel": self.__name__,
"grid": grid,
"status": "offline_shim_dry_run",
"args_count": len(args),
"kwargs_keys": sorted(kwargs.keys()),
}
return _launch
def __call__(self, *args: Any, **kwargs: Any) -> Any:
return self.fn(*args, **kwargs)
class TritonAPIProtocol(Protocol):
"""Typed protocol matching the subset of OpenAI Triton decorators and helpers used in Lab 15."""
def jit(self, fn: F) -> JitKernelHandle[F]: ...
def autotune(
self,
configs: list[Any],
key: list[str],
**kwargs: Any,
) -> Callable[[JitKernelHandle[F]], JitKernelHandle[F]]: ...
def Config(
self,
kwargs: dict[str, Any],
num_warps: int = 4,
num_stages: int = 3,
) -> Any: ...
def cdiv(self, x: int, div: int) -> int: ...
class _TritonRuntimeShim:
"""Lightweight offline shim matching Triton 3.x decorator and utility signatures."""
def jit(self, fn: F) -> JitKernelHandle[F]:
return JitKernelHandle(fn)
def autotune(
self,
configs: list[Any],
key: list[str],
**kwargs: Any,
) -> Callable[[JitKernelHandle[F]], JitKernelHandle[F]]:
del kwargs
def _decorator(handle: JitKernelHandle[F]) -> JitKernelHandle[F]:
handle.triton_meta = TritonKernelMetadata(
fn_name=handle.__name__,
is_jitted=True,
autotune_configs=tuple(configs),
autotune_key=tuple(key),
)
return handle
return _decorator
def Config(
self,
kwargs: dict[str, Any],
num_warps: int = 4,
num_stages: int = 3,
) -> TritonConfigShim:
return TritonConfigShim(kwargs=dict(kwargs), num_warps=num_warps, num_stages=num_stages)
def cdiv(self, x: int, div: int) -> int:
return (x + div - 1) // div
class _TritonLanguageShim:
"""Offline namespace stub for `triton.language` (`tl`) primitives."""
constexpr: type[int] = int
float16: str = "float16"
bfloat16: str = "bfloat16"
float32: str = "float32"
def __getattr__(self, name: str) -> Any:
def _op(*args: Any, **kwargs: Any) -> Any:
raise RuntimeError(
f"`triton.language.{name}` cannot execute directly on CPU without Triton+CUDA; "
"use `triton_kernels_lab` SPMD simulator on CPU or run on Linux+CUDA."
)
return _op
def _load_triton_and_lang() -> tuple[bool, TritonAPIProtocol, Any]:
if importlib.util.find_spec("triton") is not None:
real_triton = importlib.import_module("triton")
real_tl = importlib.import_module("triton.language")
return True, cast(TritonAPIProtocol, real_triton), real_tl
return False, _TritonRuntimeShim(), _TritonLanguageShim()
HAS_REAL_TRITON, triton, tl = _load_triton_and_lang()
__all__ = [
"HAS_REAL_TRITON",
"JitKernelHandle",
"TritonConfigShim",
"TritonKernelMetadata",
"tl",
"triton",
]
"""Tier-1 Triton 3.x Kernels: Vector Addition, Fused Online Softmax & Fused RMSNorm.
These kernels follow idiomatic OpenAI Triton 3.x SPMD patterns (`@triton.jit`,
`@triton.autotune`, boundary masking with `mask=...`, `other=-float("inf")` on Softmax
padding, and Milakov-Gimelshein online rescaling) and execute natively on Linux+CUDA GPUs.
"""
from __future__ import annotations
from typing import TYPE_CHECKING, Any
import torch
from triton_kernels import HAS_REAL_TRITON, tl, triton
if TYPE_CHECKING:
type ConstExpr = int
else:
ConstExpr = tl.constexpr
@triton.jit
def vec_add_kernel(
x_ptr: Any,
y_ptr: Any,
out_ptr: Any,
n_elements: int,
BLOCK_SIZE: ConstExpr,
) -> None:
"""1D SPMD coalesced vector addition with strict tail boundary masking."""
pid = tl.program_id(axis=0)
block_start = pid * BLOCK_SIZE
offsets = block_start + tl.arange(0, BLOCK_SIZE)
mask = offsets < n_elements
x = tl.load(x_ptr + offsets, mask=mask, other=0.0)
y = tl.load(y_ptr + offsets, mask=mask, other=0.0)
output = x + y
tl.store(out_ptr + offsets, output, mask=mask)
@triton.autotune(
configs=[
triton.Config({"BLOCK_SIZE": 256}, num_warps=4, num_stages=2),
triton.Config({"BLOCK_SIZE": 512}, num_warps=4, num_stages=3),
triton.Config({"BLOCK_SIZE": 1024}, num_warps=8, num_stages=3),
],
key=["n_cols"],
)
@triton.jit
def fused_online_softmax_kernel(
input_ptr: Any,
output_ptr: Any,
input_row_stride: int,
output_row_stride: int,
n_cols: int,
BLOCK_SIZE: ConstExpr,
) -> None:
"""Fused row-wise Online Safe Softmax (Milakov-Gimelshein) eliminating HBM intermediates."""
row_idx = tl.program_id(axis=0)
row_start_ptr = input_ptr + row_idx * input_row_stride
out_row_start_ptr = output_ptr + row_idx * output_row_stride
if n_cols <= BLOCK_SIZE:
# Single-pass SRAM specialization: 1 HBM load + 1 HBM store when entire row fits in tile.
col_offsets = tl.arange(0, BLOCK_SIZE)
mask = col_offsets < n_cols
x_row = tl.load(
row_start_ptr + col_offsets, mask=mask, other=-float("inf")
).to(tl.float32)
m_row = tl.max(x_row, axis=0)
p_row = tl.where(mask, tl.exp(x_row - m_row), 0.0)
l_row = tl.sum(p_row, axis=0)
y_row = tl.where(mask, p_row / l_row, 0.0)
tl.store(
out_row_start_ptr + col_offsets,
y_row.to(output_ptr.dtype.element_ty),
mask=mask,
)
else:
m_i = -float("inf")
l_i = 0.0
for col_start in range(0, n_cols, BLOCK_SIZE):
col_offsets = col_start + tl.arange(0, BLOCK_SIZE)
mask = col_offsets < n_cols
x_tile = tl.load(
row_start_ptr + col_offsets, mask=mask, other=-float("inf")
).to(tl.float32)
m_tile = tl.max(x_tile, axis=0)
m_new = tl.maximum(m_i, m_tile)
alpha = tl.where(
(m_i == -float("inf")) | (m_new == -float("inf")),
0.0,
tl.exp(m_i - m_new),
)
p_tile = tl.where(mask, tl.exp(x_tile - m_new), 0.0)
l_i = l_i * alpha + tl.sum(p_tile, axis=0)
m_i = m_new
for col_start in range(0, n_cols, BLOCK_SIZE):
col_offsets = col_start + tl.arange(0, BLOCK_SIZE)
mask = col_offsets < n_cols
x_tile = tl.load(
row_start_ptr + col_offsets, mask=mask, other=-float("inf")
).to(tl.float32)
y_tile = tl.where(mask, tl.exp(x_tile - m_i) / l_i, 0.0)
tl.store(
out_row_start_ptr + col_offsets,
y_tile.to(output_ptr.dtype.element_ty),
mask=mask,
)
@triton.autotune(
configs=[
triton.Config({"BLOCK_SIZE": 256}, num_warps=4, num_stages=2),
triton.Config({"BLOCK_SIZE": 512}, num_warps=4, num_stages=2),
triton.Config({"BLOCK_SIZE": 1024}, num_warps=8, num_stages=3),
],
key=["n_cols"],
)
@triton.jit
def fused_rmsnorm_kernel(
x_ptr: Any,
w_ptr: Any,
y_ptr: Any,
stride_row: int,
n_cols: int,
eps: float,
BLOCK_SIZE: ConstExpr,
) -> None:
"""Single-kernel Fused RMSNorm in fp32 accumulation over SRAM/registers."""
row_idx = tl.program_id(axis=0)
x_row_ptr = x_ptr + row_idx * stride_row
y_row_ptr = y_ptr + row_idx * stride_row
sum_sq = 0.0
for col_start in range(0, n_cols, BLOCK_SIZE):
col_offsets = col_start + tl.arange(0, BLOCK_SIZE)
mask = col_offsets < n_cols
x_tile = tl.load(x_row_ptr + col_offsets, mask=mask, other=0.0).to(tl.float32)
sum_sq = sum_sq + tl.sum(x_tile * x_tile, axis=0)
rstd = tl.rsqrt(sum_sq / n_cols + eps)
for col_start in range(0, n_cols, BLOCK_SIZE):
col_offsets = col_start + tl.arange(0, BLOCK_SIZE)
mask = col_offsets < n_cols
x_tile = tl.load(x_row_ptr + col_offsets, mask=mask, other=0.0).to(tl.float32)
w_tile = tl.load(w_ptr + col_offsets, mask=mask, other=1.0).to(tl.float32)
y_tile = x_tile * rstd * w_tile
tl.store(y_row_ptr + col_offsets, y_tile.to(y_ptr.dtype.element_ty), mask=mask)
def launch_vec_add(x: torch.Tensor, y: torch.Tensor, block_size: int = 256) -> torch.Tensor:
"""Launch Triton `vec_add_kernel` on CUDA, or compute exact reference on CPU."""
if x.shape != y.shape:
raise ValueError(f"Shape mismatch: {x.shape} vs {y.shape}")
out = torch.empty_like(x)
n_elements = x.numel()
if HAS_REAL_TRITON and x.is_cuda and y.is_cuda:
grid = (triton.cdiv(n_elements, block_size),)
vec_add_kernel[grid](x, y, out, n_elements, BLOCK_SIZE=block_size)
return out
return x + y
__all__ = [
"fused_online_softmax_kernel",
"fused_rmsnorm_kernel",
"launch_vec_add",
"vec_add_kernel",
]
"""Tier-1 Triton 3.x Kernels: L2-Swizzled Tiled MatMul & FlashAttention-2 Forward.
Implements Triton 3.x block pointer abstractions (`tl.make_block_ptr`, `tl.advance`)
compatible with Hopper TMA descriptors, `GROUP_SIZE_M` L2 cache swizzling, `tl.dot`
Tensor Core accumulation, and exact FlashAttention-2 online softmax rescaling.
"""
from __future__ import annotations
from typing import TYPE_CHECKING, Any
from triton_kernels import tl, triton
if TYPE_CHECKING:
type ConstExpr = int
else:
ConstExpr = tl.constexpr
@triton.autotune(
configs=[
triton.Config(
{"BLOCK_SIZE_M": 128, "BLOCK_SIZE_N": 128, "BLOCK_SIZE_K": 32, "GROUP_SIZE_M": 8},
num_stages=3,
num_warps=8,
),
triton.Config(
{"BLOCK_SIZE_M": 64, "BLOCK_SIZE_N": 128, "BLOCK_SIZE_K": 32, "GROUP_SIZE_M": 8},
num_stages=4,
num_warps=4,
),
triton.Config(
{"BLOCK_SIZE_M": 64, "BLOCK_SIZE_N": 64, "BLOCK_SIZE_K": 32, "GROUP_SIZE_M": 4},
num_stages=3,
num_warps=4,
),
],
key=["M", "N", "K"],
)
@triton.jit
def tiled_matmul_swizzled_kernel(
a_ptr: Any,
b_ptr: Any,
c_ptr: Any,
M: int,
N: int,
K: int,
stride_am: int,
stride_ak: int,
stride_bk: int,
stride_bn: int,
stride_cm: int,
stride_cn: int,
BLOCK_SIZE_M: ConstExpr,
BLOCK_SIZE_N: ConstExpr,
BLOCK_SIZE_K: ConstExpr,
GROUP_SIZE_M: ConstExpr,
) -> None:
"""Blocked GEMM with `GROUP_SIZE_M` L2 cache CTA swizzling and `tl.make_block_ptr`."""
pid = tl.program_id(axis=0)
num_pid_m = tl.cdiv(M, BLOCK_SIZE_M)
num_pid_n = tl.cdiv(N, BLOCK_SIZE_N)
num_pid_in_group = GROUP_SIZE_M * num_pid_n
group_id = pid // num_pid_in_group
first_pid_m = group_id * GROUP_SIZE_M
group_size_m = tl.minimum(num_pid_m - first_pid_m, GROUP_SIZE_M)
pid_m = first_pid_m + ((pid % num_pid_in_group) % group_size_m)
pid_n = (pid % num_pid_in_group) // group_size_m
a_block_ptr = tl.make_block_ptr(
base=a_ptr,
shape=(M, K),
strides=(stride_am, stride_ak),
offsets=(pid_m * BLOCK_SIZE_M, 0),
block_shape=(BLOCK_SIZE_M, BLOCK_SIZE_K),
order=(1, 0),
)
b_block_ptr = tl.make_block_ptr(
base=b_ptr,
shape=(K, N),
strides=(stride_bk, stride_bn),
offsets=(0, pid_n * BLOCK_SIZE_N),
block_shape=(BLOCK_SIZE_K, BLOCK_SIZE_N),
order=(1, 0),
)
accumulator = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype=tl.float32)
for _k in range(0, tl.cdiv(K, BLOCK_SIZE_K)):
a_tile = tl.load(a_block_ptr, boundary_check=(0, 1), padding_option="zero")
b_tile = tl.load(b_block_ptr, boundary_check=(0, 1), padding_option="zero")
accumulator = tl.dot(a_tile, b_tile, accumulator)
a_block_ptr = tl.advance(a_block_ptr, (0, BLOCK_SIZE_K))
b_block_ptr = tl.advance(b_block_ptr, (BLOCK_SIZE_K, 0))
c_block_ptr = tl.make_block_ptr(
base=c_ptr,
shape=(M, N),
strides=(stride_cm, stride_cn),
offsets=(pid_m * BLOCK_SIZE_M, pid_n * BLOCK_SIZE_N),
block_shape=(BLOCK_SIZE_M, BLOCK_SIZE_N),
order=(1, 0),
)
tl.store(c_block_ptr, accumulator.to(c_ptr.dtype.element_ty), boundary_check=(0, 1))
@triton.autotune(
configs=[
triton.Config({"BLOCK_M": 64, "BLOCK_N": 64}, num_stages=2, num_warps=4),
triton.Config({"BLOCK_M": 128, "BLOCK_N": 64}, num_stages=3, num_warps=8),
],
key=["N_CTX", "HEAD_DIM"],
)
@triton.jit
def flash_attn_fwd_kernel(
q_ptr: Any,
k_ptr: Any,
v_ptr: Any,
o_ptr: Any,
l_ptr: Any,
stride_qz: int,
stride_qm: int,
stride_qk: int,
stride_kz: int,
stride_kn: int,
stride_kk: int,
stride_vz: int,
stride_vn: int,
stride_vk: int,
stride_oz: int,
stride_om: int,
stride_ok: int,
qk_scale: float,
N_CTX: int,
HEAD_DIM: ConstExpr,
BLOCK_M: ConstExpr,
BLOCK_N: ConstExpr,
IS_CAUSAL: ConstExpr,
) -> None:
"""Simplified FlashAttention-2 Forward kernel with B_r x B_c SRAM tiling & online softmax."""
pid_m = tl.program_id(axis=0)
pid_bh = tl.program_id(axis=1)
q_offset = pid_bh * stride_qz
k_offset = pid_bh * stride_kz
v_offset = pid_bh * stride_vz
o_offset = pid_bh * stride_oz
q_block_ptr = tl.make_block_ptr(
base=q_ptr + q_offset,
shape=(N_CTX, HEAD_DIM),
strides=(stride_qm, stride_qk),
offsets=(pid_m * BLOCK_M, 0),
block_shape=(BLOCK_M, HEAD_DIM),
order=(1, 0),
)
k_block_ptr = tl.make_block_ptr(
base=k_ptr + k_offset,
shape=(HEAD_DIM, N_CTX),
strides=(stride_kk, stride_kn),
offsets=(0, 0),
block_shape=(HEAD_DIM, BLOCK_N),
order=(0, 1),
)
v_block_ptr = tl.make_block_ptr(
base=v_ptr + v_offset,
shape=(N_CTX, HEAD_DIM),
strides=(stride_vn, stride_vk),
offsets=(0, 0),
block_shape=(BLOCK_N, HEAD_DIM),
order=(1, 0),
)
o_block_ptr = tl.make_block_ptr(
base=o_ptr + o_offset,
shape=(N_CTX, HEAD_DIM),
strides=(stride_om, stride_ok),
offsets=(pid_m * BLOCK_M, 0),
block_shape=(BLOCK_M, HEAD_DIM),
order=(1, 0),
)
offs_m = pid_m * BLOCK_M + tl.arange(0, BLOCK_M)
m_i = tl.full([BLOCK_M], value=-float("inf"), dtype=tl.float32)
l_i = tl.zeros([BLOCK_M], dtype=tl.float32)
acc = tl.zeros([BLOCK_M, HEAD_DIM], dtype=tl.float32)
q_tile = tl.load(q_block_ptr, boundary_check=(0, 1), padding_option="zero")
hi = tl.minimum((pid_m + 1) * BLOCK_M, N_CTX) if IS_CAUSAL else N_CTX
for start_n in range(0, hi, BLOCK_N):
offs_n = start_n + tl.arange(0, BLOCK_N)
k_tile = tl.load(k_block_ptr, boundary_check=(0, 1), padding_option="zero")
v_tile = tl.load(v_block_ptr, boundary_check=(0, 1), padding_option="zero")
qk = tl.dot(q_tile, k_tile) * qk_scale
valid_col = offs_n[None, :] < N_CTX
if IS_CAUSAL:
valid_mask = valid_col & (offs_m[:, None] >= offs_n[None, :])
else:
valid_mask = valid_col
qk = tl.where(valid_mask, qk, -float("inf"))
m_ij = tl.maximum(m_i, tl.max(qk, axis=1))
alpha = tl.where(
(m_i == -float("inf")) | (m_ij == -float("inf")),
0.0,
tl.exp(m_i - m_ij),
)
p_tile = tl.where(valid_mask, tl.exp(qk - m_ij[:, None]), 0.0)
acc = acc * alpha[:, None] + tl.dot(p_tile.to(v_tile.dtype), v_tile)
l_i = l_i * alpha + tl.sum(p_tile, axis=1)
m_i = m_ij
k_block_ptr = tl.advance(k_block_ptr, (0, BLOCK_N))
v_block_ptr = tl.advance(v_block_ptr, (BLOCK_N, 0))
acc = acc / l_i[:, None]
tl.store(o_block_ptr, acc.to(o_ptr.dtype.element_ty), boundary_check=(0, 1))
l_offsets = pid_bh * N_CTX + offs_m
tl.store(l_ptr + l_offsets, m_i + tl.log(l_i), mask=offs_m < N_CTX)
__all__ = [
"flash_attn_fwd_kernel",
"tiled_matmul_swizzled_kernel",
]
"""Lab 15 (`triton_kernels_lab`): SPMD Triton Tile Simulator, HBM/L2 Cache Accounting & FlashAttention-2."""
from __future__ import annotations
from triton_kernels_lab.flash_attn_and_autotune import (
AutotuneCandidateResult,
AutotuneReport,
FlashAttnScalingPoint,
FlashAttnTraceResult,
create_in_memory_otel_tracer,
run_flash_attention_benchmark,
run_full_triton_lab_benchmark,
run_matmul_autotune_sweep,
spmd_flash_attention_fwd,
standard_materialized_attention,
)
from triton_kernels_lab.spmd_tile_engine import (
AutotuneConfig,
HardwareSpec,
HBMTraceStats,
L2SwizzleResult,
audit_tier1_triton_kernels_ast,
compute_swizzled_cta_coords,
run_l2_swizzle_ablation,
run_rmsnorm_ablation,
run_softmax_ablation,
run_vector_add_ablation,
spmd_fused_online_softmax,
spmd_fused_rmsnorm,
spmd_tiled_matmul,
spmd_vector_add,
)
__all__ = [
"AutotuneCandidateResult",
"AutotuneConfig",
"AutotuneReport",
"FlashAttnScalingPoint",
"FlashAttnTraceResult",
"HBMTraceStats",
"HardwareSpec",
"L2SwizzleResult",
"audit_tier1_triton_kernels_ast",
"compute_swizzled_cta_coords",
"create_in_memory_otel_tracer",
"run_flash_attention_benchmark",
"run_full_triton_lab_benchmark",
"run_l2_swizzle_ablation",
"run_matmul_autotune_sweep",
"run_rmsnorm_ablation",
"run_softmax_ablation",
"run_vector_add_ablation",
"spmd_flash_attention_fwd",
"spmd_fused_online_softmax",
"spmd_fused_rmsnorm",
"spmd_tiled_matmul",
"spmd_vector_add",
"standard_materialized_attention",
]
"""Tier-2 Executable SPMD Simulator: Vector Add Masking, Fused Online Softmax, RMSNorm & L2 Swizzle."""
from __future__ import annotations
import ast
from collections import OrderedDict
from pathlib import Path
from typing import Any, Literal
import torch
from opentelemetry.trace import Tracer
from pydantic import BaseModel, ConfigDict, Field
def cdiv(a: int, b: int) -> int:
"""Integer ceiling division matching `triton.cdiv`."""
return (a + b - 1) // b
class HardwareSpec(BaseModel):
"""GPU memory hierarchy & Roofline hardware contract (defaults to NVIDIA H100 SXM)."""
model_config = ConfigDict(extra="forbid", frozen=True)
name: str = "NVIDIA H100 SXM (80GB HBM3)"
hbm_bw_gbps: float = Field(default=3350.0, gt=0.0)
fp16_tflops: float = Field(default=989.0, gt=0.0)
sram_per_sm_kb: float = Field(default=228.0, gt=0.0)
l2_cache_mb: float = Field(default=50.0, gt=0.0)
num_sms: int = Field(default=132, ge=1)
launch_overhead_us: float = Field(default=5.0, ge=0.0)
@property
def ridge_point_flops_per_byte(self) -> float:
"""Roofline ridge point (FLOP/Byte) separating memory-bound from compute-bound."""
return (self.fp16_tflops * 1e12) / (self.hbm_bw_gbps * 1e9)
@property
def sram_limit_bytes(self) -> int:
"""Maximum shared memory capacity per SM in bytes."""
return int(self.sram_per_sm_kb * 1024)
class HBMTraceStats(BaseModel):
"""Measured HBM traffic, kernel launch, Roofline time, and numerical fidelity stats."""
model_config = ConfigDict(extra="forbid")
kernel_name: str
kernel_launches: int = Field(..., ge=1)
hbm_bytes_read: int = Field(..., ge=0)
hbm_bytes_written: int = Field(..., ge=0)
total_hbm_bytes: int = Field(..., ge=0)
flops: int = Field(..., ge=0)
arithmetic_intensity: float = Field(..., ge=0.0)
peak_intermediate_hbm_bytes: int = Field(..., ge=0)
estimated_gpu_time_us: float = Field(..., ge=0.0)
effective_bandwidth_gbps: float = Field(..., ge=0.0)
max_abs_err: float = Field(..., ge=0.0)
mean_abs_err: float = Field(..., ge=0.0)
has_nan_or_inf: bool = False
oob_guarded_elements: int = Field(default=0, ge=0)
oob_corrupted_elements: int = Field(default=0, ge=0)
class L2SwizzleResult(BaseModel):
"""Executed L2 LRU tile cache simulation and numerical equivalence for Tiled MatMul."""
model_config = ConfigDict(extra="forbid")
m: int = Field(..., ge=1)
n: int = Field(..., ge=1)
k: int = Field(..., ge=1)
block_m: int = Field(..., ge=1)
block_n: int = Field(..., ge=1)
block_k: int = Field(..., ge=1)
group_size_m: int = Field(..., ge=1)
schedule_mode: Literal["row_major", "l2_swizzled"]
total_ctas: int = Field(..., ge=1)
l2_capacity_bytes: int = Field(..., ge=1)
l2_tile_hits: int = Field(..., ge=0)
l2_tile_misses: int = Field(..., ge=0)
l2_hit_rate: float = Field(..., ge=0.0, le=1.0)
dram_bytes_fetched: int = Field(..., ge=0)
ideal_compulsory_bytes: int = Field(..., ge=0)
dram_amplification: float = Field(..., ge=1.0)
max_abs_err: float = Field(..., ge=0.0)
tile_order_preview: list[tuple[int, int, int]]
class AutotuneConfig(BaseModel):
"""Candidate Triton tile & software pipelining configuration."""
model_config = ConfigDict(extra="forbid", frozen=True)
block_m: int = Field(..., ge=16)
block_n: int = Field(..., ge=16)
block_k: int = Field(..., ge=16)
group_size_m: int = Field(..., ge=1)
num_stages: int = Field(..., ge=1, le=8)
num_warps: int = Field(..., ge=1, le=32)
def sram_required_bytes(self, elem_bytes: int = 2) -> int:
"""Double/multi-buffered A & B shared memory footprint per CTA."""
return self.num_stages * (self.block_m * self.block_k + self.block_k * self.block_n) * elem_bytes
def _estimate_roofline_time_us(
flops: int,
total_hbm_bytes: int,
kernel_launches: int,
hw: HardwareSpec,
) -> tuple[float, float]:
mem_time_s = total_hbm_bytes / (hw.hbm_bw_gbps * 1e9)
cmp_time_s = flops / (hw.fp16_tflops * 1e12)
compute_plus_mem_us = max(mem_time_s, cmp_time_s) * 1e6
total_us = compute_plus_mem_us + kernel_launches * hw.launch_overhead_us
eff_bw = (total_hbm_bytes / (total_us * 1e-6)) / 1e9 if total_us > 0 else 0.0
return total_us, eff_bw
def spmd_vector_add(
x: torch.Tensor,
y: torch.Tensor,
block_size: int = 256,
enable_mask: bool = True,
hw: HardwareSpec | None = None,
tracer: Tracer | None = None,
) -> tuple[torch.Tensor, HBMTraceStats, bool]:
"""Execute SPMD Vector Add per `pid` with canary buffer OOB boundary inspection."""
spec = hw or HardwareSpec()
if x.shape != y.shape or x.ndim != 1:
raise ValueError("spmd_vector_add expects matching 1D tensors.")
n = x.numel()
elem_bytes = x.element_size()
num_pids = cdiv(n, block_size)
padded_n = num_pids * block_size
tail_pad = padded_n - n
# Canary-padded buffers detect OOB tail corruption if masking is disabled
canary_val = 9999.0
x_buf = torch.full((padded_n,), canary_val, dtype=x.dtype)
y_buf = torch.full((padded_n,), canary_val, dtype=y.dtype)
out_buf = torch.full((padded_n,), canary_val, dtype=x.dtype)
x_buf[:n] = x
y_buf[:n] = y
oob_guarded = 0
oob_corrupted = 0
for pid in range(num_pids):
offsets = pid * block_size + torch.arange(block_size, dtype=torch.int64)
mask = offsets < n
if enable_mask:
valid_idx = offsets[mask]
out_buf[valid_idx] = x_buf[valid_idx] + y_buf[valid_idx]
oob_guarded += int((~mask).sum().item())
else:
out_buf[offsets] = x_buf[offsets] + y_buf[offsets]
oob_corrupted += int((~mask).sum().item())
out = out_buf[:n].clone()
ref = x + y
max_err = float((out - ref).abs().max().item()) if n > 0 else 0.0
mean_err = float((out - ref).abs().mean().item()) if n > 0 else 0.0
canary_corrupted = bool(tail_pad > 0 and not torch.all(out_buf[n:] == canary_val).item())
hbm_read = 2 * n * elem_bytes
hbm_written = n * elem_bytes
total_hbm = hbm_read + hbm_written
flops = n
est_us, eff_bw = _estimate_roofline_time_us(flops, total_hbm, 1, spec)
stats = HBMTraceStats(
kernel_name="vec_add_masked" if enable_mask else "vec_add_unmasked_oob_bug",
kernel_launches=1,
hbm_bytes_read=hbm_read,
hbm_bytes_written=hbm_written,
total_hbm_bytes=total_hbm,
flops=flops,
arithmetic_intensity=flops / max(1, total_hbm),
peak_intermediate_hbm_bytes=0,
estimated_gpu_time_us=est_us,
effective_bandwidth_gbps=eff_bw,
max_abs_err=max_err,
mean_abs_err=mean_err,
oob_guarded_elements=oob_guarded,
oob_corrupted_elements=oob_corrupted,
)
if tracer is not None:
with tracer.start_as_current_span("triton.vec_add") as span:
span.set_attribute("n_elements", n)
span.set_attribute("enable_mask", enable_mask)
span.set_attribute("oob_guarded", oob_guarded)
span.set_attribute("canary_corrupted", canary_corrupted)
return out, stats, canary_corrupted
def run_vector_add_ablation(
n_elements: int = 100_003,
block_size: int = 256,
seed: int = 42,
hw: HardwareSpec | None = None,
tracer: Tracer | None = None,
) -> dict[str, Any]:
"""Compare masked vs unmasked vector add on non-power-of-two tail length."""
gen = torch.Generator().manual_seed(seed)
x = torch.randn(n_elements, generator=gen, dtype=torch.float32)
y = torch.randn(n_elements, generator=gen, dtype=torch.float32)
_, masked_stats, masked_corrupt = spmd_vector_add(
x, y, block_size=block_size, enable_mask=True, hw=hw, tracer=tracer
)
_, unmasked_stats, unmasked_corrupt = spmd_vector_add(
x, y, block_size=block_size, enable_mask=False, hw=hw, tracer=tracer
)
return {
"n_elements": n_elements,
"block_size": block_size,
"tail_elements": masked_stats.oob_guarded_elements,
"masked": masked_stats.model_dump(),
"masked_canary_corrupted": masked_corrupt,
"unmasked": unmasked_stats.model_dump(),
"unmasked_canary_corrupted": unmasked_corrupt,
}
def spmd_fused_online_softmax(
x: torch.Tensor,
block_size: int = 256,
pad_with_neg_inf: bool = True,
sram_row_resident_limit: int = 2048,
hw: HardwareSpec | None = None,
tracer: Tracer | None = None,
) -> tuple[torch.Tensor, HBMTraceStats]:
"""Execute per-row SPMD tiled Online Safe Softmax (Milakov-Gimelshein) on 2D tensors."""
if x.ndim != 2:
raise ValueError("spmd_fused_online_softmax expects 2D (rows, cols) tensor.")
spec = hw or HardwareSpec()
rows, cols = x.shape
elem_bytes = x.element_size()
x_f32 = x.to(torch.float32)
out = torch.empty_like(x_f32)
oob_guarded = 0
for row_idx in range(rows):
row = x_f32[row_idx]
m_i = torch.tensor(-float("inf"), dtype=torch.float32)
l_i = torch.tensor(0.0, dtype=torch.float32)
for col_start in range(0, cols, block_size):
col_end = min(col_start + block_size, cols)
valid_len = col_end - col_start
pad_len = block_size - valid_len
tile = row[col_start:col_end]
if pad_len > 0:
oob_guarded += pad_len
pad_val = -float("inf") if pad_with_neg_inf else 0.0
pad_tensor = torch.full((pad_len,), pad_val, dtype=torch.float32)
tile_padded = torch.cat([tile, pad_tensor], dim=0)
else:
tile_padded = tile
m_tile = tile_padded.max()
m_new = torch.maximum(m_i, m_tile)
alpha = torch.exp(m_i - m_new) if not torch.isinf(m_i) else torch.tensor(0.0)
exp_tile = torch.exp(tile_padded - m_new)
l_i = l_i * alpha + exp_tile.sum()
m_i = m_new
for col_start in range(0, cols, block_size):
col_end = min(col_start + block_size, cols)
out[row_idx, col_start:col_end] = torch.exp(row[col_start:col_end] - m_i) / l_i
out_cast = out.to(x.dtype)
ref = torch.softmax(x_f32, dim=-1).to(x.dtype)
max_err = float((out_cast - ref).abs().max().item())
mean_err = float((out_cast - ref).abs().mean().item())
has_nan = bool(torch.isnan(out_cast).any().item() or torch.isinf(out_cast).any().item())
# If row fits in SM SRAM/registers, Triton reads x once and writes once.
# Otherwise multi-tile online pass reads x twice without writing exp() to HBM.
is_sram_resident = block_size >= cols and cols <= sram_row_resident_limit
hbm_reads = rows * cols * elem_bytes if is_sram_resident else 2 * rows * cols * elem_bytes
hbm_written = rows * cols * elem_bytes
total_hbm = hbm_reads + hbm_written
flops = 5 * rows * cols # max/sub/exp/sum/div approx 5 ops/element
est_us, eff_bw = _estimate_roofline_time_us(flops, total_hbm, 1, spec)
stats = HBMTraceStats(
kernel_name=(
"fused_sram_softmax"
if (block_size >= cols and pad_with_neg_inf)
else ("fused_online_tiled_softmax" if pad_with_neg_inf else "buggy_zero_pad_softmax")
),
kernel_launches=1,
hbm_bytes_read=hbm_reads,
hbm_bytes_written=hbm_written,
total_hbm_bytes=total_hbm,
flops=flops,
arithmetic_intensity=flops / max(1, total_hbm),
peak_intermediate_hbm_bytes=0,
estimated_gpu_time_us=est_us,
effective_bandwidth_gbps=eff_bw,
max_abs_err=max_err,
mean_abs_err=mean_err,
has_nan_or_inf=has_nan,
oob_guarded_elements=oob_guarded,
oob_corrupted_elements=0 if pad_with_neg_inf else oob_guarded,
)
if tracer is not None:
with tracer.start_as_current_span("triton.fused_softmax") as span:
span.set_attribute("rows", rows)
span.set_attribute("cols", cols)
span.set_attribute("block_size", block_size)
span.set_attribute("pad_with_neg_inf", pad_with_neg_inf)
span.set_attribute("max_abs_err", max_err)
return out_cast, stats
def run_softmax_ablation(
rows: int = 128,
cols: int = 777,
block_size: int = 256,
seed: int = 42,
hw: HardwareSpec | None = None,
tracer: Tracer | None = None,
) -> dict[str, Any]:
"""Compare Naive Unsafe, Unfused Eager PyTorch, Buggy Zero-Pad, and Fused Online Softmax."""
spec = hw or HardwareSpec()
gen = torch.Generator().manual_seed(seed)
x = torch.randn((rows, cols), generator=gen, dtype=torch.float32) * 3.0
ref = torch.softmax(x, dim=-1)
elem_bytes = x.element_size()
# 1. Naive unsafe exp(x) / sum(exp(x)) on normal + extreme [-1000, +1000] logits
extreme = torch.linspace(-1000.0, 1000.0, steps=cols).unsqueeze(0).expand(8, cols).clone()
unsafe_out = torch.exp(extreme) / torch.exp(extreme).sum(dim=-1, keepdim=True)
unsafe_has_nan = bool(torch.isnan(unsafe_out).any().item() or torch.isinf(unsafe_out).any().item())
fused_extreme, fused_extreme_stats = spmd_fused_online_softmax(
extreme, block_size=block_size, pad_with_neg_inf=True, hw=spec
)
extreme_ref = torch.softmax(extreme, dim=-1)
fused_extreme_err = float((fused_extreme - extreme_ref).abs().max().item())
# 2. Unfused Eager PyTorch Softmax (5 separate kernel launches & HBM intermediates)
m_val = x.max(dim=-1, keepdim=True).values
shifted = x - m_val
exps = torch.exp(shifted)
denom = exps.sum(dim=-1, keepdim=True)
eager_out = exps / denom
eager_err = float((eager_out - ref).abs().max().item())
eager_mean_err = float((eager_out - ref).abs().mean().item())
# 5 read passes over (M,N) + 3 write passes over (M,N) + 4 row-scalar passes
eager_reads = 5 * rows * cols * elem_bytes + 2 * rows * elem_bytes
eager_writes = 3 * rows * cols * elem_bytes + 2 * rows * elem_bytes
eager_total = eager_reads + eager_writes
eager_flops = 5 * rows * cols
eager_us, eager_bw = _estimate_roofline_time_us(eager_flops, eager_total, 5, spec)
eager_stats = HBMTraceStats(
kernel_name="eager_unfused_5_ops",
kernel_launches=5,
hbm_bytes_read=eager_reads,
hbm_bytes_written=eager_writes,
total_hbm_bytes=eager_total,
flops=eager_flops,
arithmetic_intensity=eager_flops / max(1, eager_total),
peak_intermediate_hbm_bytes=2 * rows * cols * elem_bytes,
estimated_gpu_time_us=eager_us,
effective_bandwidth_gbps=eager_bw,
max_abs_err=eager_err,
mean_abs_err=eager_mean_err,
)
# 3. Failure Case 2: Unmasked / zero-padded tail bug (`other=0.0` instead of `-inf`)
_, zero_pad_stats = spmd_fused_online_softmax(
x, block_size=block_size, pad_with_neg_inf=False, hw=spec
)
# 4. Fused Online Safe Softmax (multi-tile Milakov-Gimelshein AND SRAM-resident 1-pass)
_, online_tiled_stats = spmd_fused_online_softmax(
x, block_size=block_size, pad_with_neg_inf=True, hw=spec, tracer=tracer
)
_, sram_resident_stats = spmd_fused_online_softmax(
x, block_size=1024, pad_with_neg_inf=True, hw=spec, tracer=tracer
)
reduction_sram = eager_stats.total_hbm_bytes / max(1, sram_resident_stats.total_hbm_bytes)
reduction_online = eager_stats.total_hbm_bytes / max(1, online_tiled_stats.total_hbm_bytes)
return {
"rows": rows,
"cols": cols,
"block_size": block_size,
"eager_unfused": eager_stats.model_dump(),
"buggy_zero_pad": zero_pad_stats.model_dump(),
"fused_online_tiled": online_tiled_stats.model_dump(),
"fused_sram_resident": sram_resident_stats.model_dump(),
"hbm_reduction_sram_x": round(reduction_sram, 4),
"hbm_reduction_online_x": round(reduction_online, 4),
"hbm_savings_pct_sram": round((1.0 - 1.0 / reduction_sram) * 100.0, 2),
"extreme_logits_naive_nan": unsafe_has_nan,
"extreme_logits_fused_max_abs_err": fused_extreme_err,
"extreme_logits_fused_nan": fused_extreme_stats.has_nan_or_inf,
}
def spmd_fused_rmsnorm(
x: torch.Tensor,
weight: torch.Tensor,
eps: float = 1e-6,
block_size: int = 256,
hw: HardwareSpec | None = None,
tracer: Tracer | None = None,
) -> tuple[torch.Tensor, HBMTraceStats]:
"""Execute single-kernel SPMD Fused RMSNorm in fp32 accumulation."""
if x.ndim != 2 or weight.ndim != 1 or x.shape[1] != weight.shape[0]:
raise ValueError("spmd_fused_rmsnorm expects x:(M, N) and weight:(N,).")
spec = hw or HardwareSpec()
rows, cols = x.shape
elem_bytes = x.element_size()
x_f32 = x.to(torch.float32)
w_f32 = weight.to(torch.float32)
out = torch.empty_like(x_f32)
for row_idx in range(rows):
row = x_f32[row_idx]
sum_sq = torch.tensor(0.0, dtype=torch.float32)
for col_start in range(0, cols, block_size):
tile = row[col_start : col_start + block_size]
sum_sq = sum_sq + (tile * tile).sum()
rstd = torch.rsqrt(sum_sq / float(cols) + eps)
for col_start in range(0, cols, block_size):
sl = slice(col_start, col_start + block_size)
out[row_idx, sl] = row[sl] * rstd * w_f32[sl]
out_cast = out.to(x.dtype)
ref = (x_f32 * torch.rsqrt(x_f32.pow(2).mean(dim=-1, keepdim=True) + eps) * w_f32).to(x.dtype)
max_err = float((out_cast - ref).abs().max().item())
mean_err = float((out_cast - ref).abs().mean().item())
hbm_read = rows * cols * elem_bytes + cols * elem_bytes
hbm_written = rows * cols * elem_bytes
total_hbm = hbm_read + hbm_written
flops = 4 * rows * cols
est_us, eff_bw = _estimate_roofline_time_us(flops, total_hbm, 1, spec)
stats = HBMTraceStats(
kernel_name="fused_triton_rmsnorm",
kernel_launches=1,
hbm_bytes_read=hbm_read,
hbm_bytes_written=hbm_written,
total_hbm_bytes=total_hbm,
flops=flops,
arithmetic_intensity=flops / max(1, total_hbm),
peak_intermediate_hbm_bytes=0,
estimated_gpu_time_us=est_us,
effective_bandwidth_gbps=eff_bw,
max_abs_err=max_err,
mean_abs_err=mean_err,
)
if tracer is not None:
with tracer.start_as_current_span("triton.fused_rmsnorm") as span:
span.set_attribute("rows", rows)
span.set_attribute("cols", cols)
span.set_attribute("max_abs_err", max_err)
return out_cast, stats
def run_rmsnorm_ablation(
rows: int = 128,
cols: int = 1024,
eps: float = 1e-6,
seed: int = 42,
hw: HardwareSpec | None = None,
tracer: Tracer | None = None,
) -> dict[str, Any]:
"""Benchmark Eager 5-launch RMSNorm vs Single-Kernel Fused Triton RMSNorm."""
spec = hw or HardwareSpec()
gen = torch.Generator().manual_seed(seed)
x = torch.randn((rows, cols), generator=gen, dtype=torch.float32)
weight = torch.randn((cols,), generator=gen, dtype=torch.float32)
elem_bytes = x.element_size()
# Unfused Eager RMSNorm (5 kernel launches: x*x, mean, rsqrt(mean+eps), x*rstd, normed*w)
sq = x * x
mean_sq = sq.mean(dim=-1, keepdim=True)
rstd = torch.rsqrt(mean_sq + eps)
normed = x * rstd
eager_out = normed * weight
del eager_out
eager_read = 4 * rows * cols * elem_bytes + cols * elem_bytes + 2 * rows * elem_bytes
eager_write = 3 * rows * cols * elem_bytes + 2 * rows * elem_bytes
eager_total = eager_read + eager_write
eager_flops = 4 * rows * cols
eager_us, eager_bw = _estimate_roofline_time_us(eager_flops, eager_total, 5, spec)
eager_stats = HBMTraceStats(
kernel_name="eager_unfused_rmsnorm",
kernel_launches=5,
hbm_bytes_read=eager_read,
hbm_bytes_written=eager_write,
total_hbm_bytes=eager_total,
flops=eager_flops,
arithmetic_intensity=eager_flops / max(1, eager_total),
peak_intermediate_hbm_bytes=2 * rows * cols * elem_bytes,
estimated_gpu_time_us=eager_us,
effective_bandwidth_gbps=eager_bw,
max_abs_err=0.0,
mean_abs_err=0.0,
)
_, fused_stats = spmd_fused_rmsnorm(
x, weight, eps=eps, block_size=1024, hw=spec, tracer=tracer
)
red_x = eager_stats.total_hbm_bytes / max(1, fused_stats.total_hbm_bytes)
roofline_speedup = eager_stats.estimated_gpu_time_us / max(
1e-9, fused_stats.estimated_gpu_time_us
)
return {
"rows": rows,
"cols": cols,
"eager_unfused": eager_stats.model_dump(),
"fused_rmsnorm": fused_stats.model_dump(),
"hbm_reduction_x": round(red_x, 4),
"hbm_savings_pct": round((1.0 - 1.0 / red_x) * 100.0, 2),
"speedup_roofline_x": round(roofline_speedup, 3),
}
def compute_swizzled_cta_coords(
pid: int,
num_pid_m: int,
num_pid_n: int,
group_size_m: int,
schedule_mode: Literal["row_major", "l2_swizzled"],
) -> tuple[int, int]:
"""Exact OpenAI Triton CTA scheduling coordinate transform `(pid_m, pid_n)`."""
if schedule_mode == "row_major":
return pid // num_pid_n, pid % num_pid_n
num_pid_in_group = group_size_m * num_pid_n
group_id = pid // num_pid_in_group
first_pid_m = group_id * group_size_m
actual_group_m = min(num_pid_m - first_pid_m, group_size_m)
pid_m = first_pid_m + ((pid % num_pid_in_group) % actual_group_m)
pid_n = (pid % num_pid_in_group) // actual_group_m
return pid_m, pid_n
def spmd_tiled_matmul(
a: torch.Tensor,
b: torch.Tensor,
block_m: int = 64,
block_n: int = 64,
block_k: int = 32,
group_size_m: int = 4,
schedule_mode: Literal["row_major", "l2_swizzled"] = "l2_swizzled",
l2_capacity_bytes: int = 262_144,
io_elem_bytes: int | None = None,
tracer: Tracer | None = None,
) -> tuple[torch.Tensor, L2SwizzleResult]:
"""Execute real blocked MatMul across SPMD CTAs while simulating an LRU L2 tile cache."""
if a.ndim != 2 or b.ndim != 2 or a.shape[1] != b.shape[0]:
raise ValueError("spmd_tiled_matmul expects compatible 2D matrices (M,K) @ (K,N).")
m, k = a.shape
_, n = b.shape
elem_bytes = io_elem_bytes if io_elem_bytes is not None else a.element_size()
num_pid_m = cdiv(m, block_m)
num_pid_n = cdiv(n, block_n)
num_pid_k = cdiv(k, block_k)
total_ctas = num_pid_m * num_pid_n
# Real LRU cache tracking exact A[pid_m, k_idx] & B[k_idx, pid_n] tile bytes
l2_cache: OrderedDict[tuple[str, int, int], int] = OrderedDict()
l2_used_bytes = 0
hits = 0
misses = 0
dram_bytes_fetched = 0
unique_tiles_seen: set[tuple[str, int, int]] = set()
ideal_compulsory_bytes = 0
def _access_l2(tag: tuple[str, int, int], nbytes: int) -> None:
nonlocal l2_used_bytes, hits, misses, dram_bytes_fetched, ideal_compulsory_bytes
if tag not in unique_tiles_seen:
unique_tiles_seen.add(tag)
ideal_compulsory_bytes += nbytes
if tag in l2_cache:
hits += 1
l2_cache.move_to_end(tag)
return
misses += 1
dram_bytes_fetched += nbytes
while l2_used_bytes + nbytes > l2_capacity_bytes and l2_cache:
_, evicted_bytes = l2_cache.popitem(last=False)
l2_used_bytes -= evicted_bytes
if nbytes <= l2_capacity_bytes:
l2_cache[tag] = nbytes
l2_used_bytes += nbytes
a_f32 = a.to(torch.float32)
b_f32 = b.to(torch.float32)
out = torch.zeros((m, n), dtype=torch.float32)
preview: list[tuple[int, int, int]] = []
for pid in range(total_ctas):
pid_m, pid_n = compute_swizzled_cta_coords(
pid, num_pid_m, num_pid_n, group_size_m=group_size_m, schedule_mode=schedule_mode
)
if len(preview) < 16:
preview.append((pid, pid_m, pid_n))
m0 = pid_m * block_m
m1 = min(m0 + block_m, m)
n0 = pid_n * block_n
n1 = min(n0 + block_n, n)
acc = torch.zeros((m1 - m0, n1 - n0), dtype=torch.float32)
for k_idx in range(num_pid_k):
k0 = k_idx * block_k
k1 = min(k0 + block_k, k)
a_tile_bytes = block_m * block_k * elem_bytes
b_tile_bytes = block_k * block_n * elem_bytes
_access_l2(("A", pid_m, k_idx), a_tile_bytes)
_access_l2(("B", k_idx, pid_n), b_tile_bytes)
acc = acc + (a_f32[m0:m1, k0:k1] @ b_f32[k0:k1, n0:n1])
out[m0:m1, n0:n1] = acc
out_cast = out.to(a.dtype)
ref = (a_f32 @ b_f32).to(a.dtype)
max_err = float((out_cast - ref).abs().max().item())
total_accesses = hits + misses
hit_rate = hits / max(1, total_accesses)
dram_amp = dram_bytes_fetched / max(1, ideal_compulsory_bytes)
res = L2SwizzleResult(
m=m,
n=n,
k=k,
block_m=block_m,
block_n=block_n,
block_k=block_k,
group_size_m=group_size_m,
schedule_mode=schedule_mode,
total_ctas=total_ctas,
l2_capacity_bytes=l2_capacity_bytes,
l2_tile_hits=hits,
l2_tile_misses=misses,
l2_hit_rate=hit_rate,
dram_bytes_fetched=dram_bytes_fetched,
ideal_compulsory_bytes=ideal_compulsory_bytes,
dram_amplification=dram_amp,
max_abs_err=max_err,
tile_order_preview=preview,
)
if tracer is not None:
with tracer.start_as_current_span("triton.tiled_matmul_swizzle") as span:
span.set_attribute("schedule_mode", schedule_mode)
span.set_attribute("group_size_m", group_size_m)
span.set_attribute("l2_hit_rate", hit_rate)
span.set_attribute("dram_bytes_fetched", dram_bytes_fetched)
return out_cast, res
def run_l2_swizzle_ablation(
m: int = 512,
n: int = 512,
k: int = 256,
block_m: int = 64,
block_n: int = 64,
block_k: int = 32,
group_size_m: int = 4,
l2_capacity_bytes: int = 262_144,
seed: int = 42,
tracer: Tracer | None = None,
) -> dict[str, Any]:
"""Compare Row-Major vs L2-Swizzled Tiled MatMul on identical tensors and LRU cache."""
gen = torch.Generator().manual_seed(seed)
# Quantize to fp16 inputs then upcast to fp32 accumulator (matching Triton tl.dot fp16->fp32)
a_fp16 = torch.randn((m, k), generator=gen, dtype=torch.float32).to(torch.float16).to(torch.float32)
b_fp16 = torch.randn((k, n), generator=gen, dtype=torch.float32).to(torch.float16).to(torch.float32)
_, row_major = spmd_tiled_matmul(
a_fp16,
b_fp16,
block_m=block_m,
block_n=block_n,
block_k=block_k,
group_size_m=1,
schedule_mode="row_major",
l2_capacity_bytes=l2_capacity_bytes,
io_elem_bytes=2,
tracer=tracer,
)
_, swizzled = spmd_tiled_matmul(
a_fp16,
b_fp16,
block_m=block_m,
block_n=block_n,
block_k=block_k,
group_size_m=group_size_m,
schedule_mode="l2_swizzled",
l2_capacity_bytes=l2_capacity_bytes,
io_elem_bytes=2,
tracer=tracer,
)
dram_cut_x = row_major.dram_bytes_fetched / max(1, swizzled.dram_bytes_fetched)
dram_cut_pct = (1.0 - 1.0 / dram_cut_x) * 100.0
hit_lift_pp = (swizzled.l2_hit_rate - row_major.l2_hit_rate) * 100.0
return {
"row_major": row_major.model_dump(),
"l2_swizzled": swizzled.model_dump(),
"l2_hit_rate_lift_pp": round(hit_lift_pp, 2),
"dram_traffic_reduction_x": round(dram_cut_x, 3),
"dram_traffic_savings_pct": round(dram_cut_pct, 2),
}
def audit_tier1_triton_kernels_ast(triton_kernels_dir: Path) -> dict[str, Any]:
"""Verify Tier-1 `triton_kernels/` files contain genuine Triton decorators & primitives."""
expected_kernels = {
"vec_add_kernel",
"fused_online_softmax_kernel",
"fused_rmsnorm_kernel",
"tiled_matmul_swizzled_kernel",
"flash_attn_fwd_kernel",
}
found_jitted: set[str] = set()
found_autotuned: set[str] = set()
found_tl_ops: set[str] = set()
for py_path in sorted(triton_kernels_dir.glob("*.py")):
tree = ast.parse(py_path.read_text(encoding="utf-8"), filename=str(py_path))
for node in ast.walk(tree):
if isinstance(node, ast.FunctionDef):
decs = [ast.unparse(d) for d in node.decorator_list]
if any("triton.jit" in d for d in decs):
found_jitted.add(node.name)
if any("triton.autotune" in d for d in decs):
found_autotuned.add(node.name)
elif isinstance(node, ast.Attribute) and isinstance(node.value, ast.Name):
if node.value.id == "tl":
found_tl_ops.add(node.attr)
missing_kernels = sorted(expected_kernels - found_jitted)
return {
"jitted_kernels": sorted(found_jitted),
"autotuned_kernels": sorted(found_autotuned),
"tl_primitives": sorted(found_tl_ops),
"all_expected_present": len(missing_kernels) == 0,
"missing_kernels": missing_kernels,
}
"""Tier-2 FlashAttention-2 Forward Tiled Simulator, Tile Autotuner & OTel Benchmark Suite."""
from __future__ import annotations
import math
from pathlib import Path
from typing import Any, Literal
import torch
import torch.nn.functional as F
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
from opentelemetry.trace import Tracer
from pydantic import BaseModel, ConfigDict, Field
from triton_kernels_lab.spmd_tile_engine import (
AutotuneConfig,
HardwareSpec,
audit_tier1_triton_kernels_ast,
cdiv,
run_l2_swizzle_ablation,
run_rmsnorm_ablation,
run_softmax_ablation,
run_vector_add_ablation,
spmd_tiled_matmul,
)
class FlashAttnTraceResult(BaseModel):
"""Numerical fidelity, HBM memory reduction, and SRAM tiling metrics for FlashAttention-2."""
model_config = ConfigDict(extra="forbid")
batch: int = Field(..., ge=1)
heads: int = Field(..., ge=1)
seq_len: int = Field(..., ge=1)
head_dim: int = Field(..., ge=1)
block_r: int = Field(..., ge=1)
block_c: int = Field(..., ge=1)
causal: bool
max_abs_err: float = Field(..., ge=0.0)
mean_abs_err: float = Field(..., ge=0.0)
has_nan_or_inf: bool = False
std_hbm_peak_bytes: int = Field(..., ge=0)
flash_hbm_peak_bytes: int = Field(..., ge=0)
hbm_memory_reduction_x: float = Field(..., ge=1.0)
std_hbm_traffic_bytes: int = Field(..., ge=0)
flash_hbm_traffic_bytes: int = Field(..., ge=0)
hbm_traffic_reduction_x: float = Field(..., ge=1.0)
sram_tile_bytes: int = Field(..., ge=0)
fits_h100_sram: bool
arithmetic_intensity: float = Field(..., ge=0.0)
class FlashAttnScalingPoint(BaseModel):
"""Context-length O(N^2) HBM vs O(N) FlashAttention memory & OOM envelope."""
model_config = ConfigDict(extra="forbid")
seq_len: int
std_score_matrix_mb: float
flash_logsumexp_mb: float
memory_reduction_x: float
exceeds_80gb_h100: bool
class AutotuneCandidateResult(BaseModel):
"""Single tile config evaluation during `@triton.autotune` search."""
model_config = ConfigDict(extra="forbid")
config: AutotuneConfig
valid_sram: bool
sram_required_bytes: int
l2_hit_rate: float
dram_bytes: int
arithmetic_intensity: float
predicted_tflops: float
estimated_latency_ms: float
class AutotuneReport(BaseModel):
"""Summary of `@triton.autotune` sweep with SRAM pruning and Pareto winner."""
model_config = ConfigDict(extra="forbid")
matrix_shape: tuple[int, int, int]
sram_limit_bytes: int
total_candidates: int
valid_candidates_count: int
pruned_candidates_count: int
best_config: AutotuneConfig
best_predicted_tflops: float
baseline_naive_tflops: float
speedup_over_naive: float
candidates: list[AutotuneCandidateResult]
def create_in_memory_otel_tracer(
service_name: str = "triton_kernels_lab",
) -> tuple[TracerProvider, InMemorySpanExporter, Tracer]:
"""Create a real OpenTelemetry TracerProvider with InMemorySpanExporter."""
exporter = InMemorySpanExporter()
provider = TracerProvider()
provider.add_span_processor(SimpleSpanProcessor(exporter))
tracer = provider.get_tracer(service_name)
return provider, exporter, tracer
def standard_materialized_attention(
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
causal: bool = False,
) -> tuple[torch.Tensor, int, int]:
"""Standard O(N^2) materialized attention tracking HBM peak intermediates and traffic."""
b, h, n, d = q.shape
elem_bytes = 2 # fp16 deployment model
scale = 1.0 / math.sqrt(d)
q_f32 = q.to(torch.float32)
k_f32 = k.to(torch.float32)
v_f32 = v.to(torch.float32)
s = torch.matmul(q_f32, k_f32.transpose(-2, -1)) * scale
if causal:
mask = torch.triu(torch.ones((n, n), dtype=torch.bool, device=q.device), diagonal=1)
s = s.masked_fill(mask.unsqueeze(0).unsqueeze(0), -float("inf"))
p = torch.softmax(s, dim=-1)
out = torch.matmul(p, v_f32).to(q.dtype)
# Standard materializes S (B,H,N,N) and P (B,H,N,N) in HBM
std_peak_bytes = 2 * b * h * n * n * elem_bytes
# Reads Q,K -> writes S; reads S -> writes P; reads P,V -> writes O
std_traffic_bytes = (4 * b * h * n * d + 4 * b * h * n * n) * elem_bytes
return out, std_peak_bytes, std_traffic_bytes
def spmd_flash_attention_fwd(
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
block_r: int = 64,
block_c: int = 64,
causal: bool = False,
hw: HardwareSpec | None = None,
tracer: Tracer | None = None,
) -> tuple[torch.Tensor, torch.Tensor, FlashAttnTraceResult]:
"""Execute faithful B_r x B_c SRAM-tiled FlashAttention-2 Forward with Online Softmax."""
if q.ndim != 4 or k.shape != q.shape or v.shape != q.shape:
raise ValueError("spmd_flash_attention_fwd expects matching (B, H, N, D) tensors.")
spec = hw or HardwareSpec()
b, h, n, d = q.shape
scale = 1.0 / math.sqrt(d)
elem_bytes = 2 # fp16 SRAM/HBM IO accounting
q_f32 = q.to(torch.float32)
k_f32 = k.to(torch.float32)
v_f32 = v.to(torch.float32)
out = torch.zeros_like(q_f32)
logsumexp = torch.zeros((b, h, n), dtype=torch.float32)
num_q_blocks = cdiv(n, block_r)
kv_elems_loaded = 0
for bi in range(b):
for hi in range(h):
for q_blk in range(num_q_blocks):
r0 = q_blk * block_r
r1 = min(r0 + block_r, n)
br_actual = r1 - r0
q_tile = q_f32[bi, hi, r0:r1, :] # resident in SRAM
m_i = torch.full((br_actual, 1), -float("inf"), dtype=torch.float32)
l_i = torch.zeros((br_actual, 1), dtype=torch.float32)
o_i = torch.zeros((br_actual, d), dtype=torch.float32)
max_k = r1 if causal else n
for c0 in range(0, max_k, block_c):
c1 = min(c0 + block_c, n)
kv_elems_loaded += 2 * (c1 - c0) * d
k_tile = k_f32[bi, hi, c0:c1, :]
v_tile = v_f32[bi, hi, c0:c1, :]
s_ij = (q_tile @ k_tile.T) * scale
if causal:
q_idx = torch.arange(r0, r1, dtype=torch.int64).unsqueeze(1)
k_idx = torch.arange(c0, c1, dtype=torch.int64).unsqueeze(0)
s_ij = s_ij.masked_fill(k_idx > q_idx, -float("inf"))
row_max = s_ij.max(dim=-1, keepdim=True).values
m_ij = torch.maximum(m_i, row_max)
# Guard against -inf - (-inf) -> NaN when an entire block is masked
valid_m_prev = ~torch.isinf(m_i)
alpha = torch.where(
valid_m_prev & (~torch.isinf(m_ij)),
torch.exp(m_i - m_ij),
torch.zeros_like(m_ij),
)
p_ij = torch.where(
torch.isinf(s_ij) & (s_ij < 0),
torch.zeros_like(s_ij),
torch.exp(s_ij - m_ij),
)
o_i = o_i * alpha + (p_ij @ v_tile)
l_i = l_i * alpha + p_ij.sum(dim=-1, keepdim=True)
m_i = m_ij
out[bi, hi, r0:r1, :] = o_i / l_i
logsumexp[bi, hi, r0:r1] = (m_i + torch.log(l_i)).squeeze(-1)
out_cast = out.to(q.dtype)
sdpa_ref = F.scaled_dot_product_attention(q_f32, k_f32, v_f32, is_causal=causal).to(q.dtype)
max_err = float((out_cast - sdpa_ref).abs().max().item())
mean_err = float((out_cast - sdpa_ref).abs().mean().item())
has_nan = bool(torch.isnan(out_cast).any().item() or torch.isinf(out_cast).any().item())
_, std_peak_bytes, std_traffic_bytes = standard_materialized_attention(q, k, v, causal=causal)
# FlashAttention only writes logsumexp L (B,H,N) fp32 to HBM; S_ij & P_ij stay strictly in SRAM
flash_peak_bytes = b * h * n * 4
# Outer loop reads Q once & writes O,L once; inner KV traffic skips causal upper triangle
flash_traffic_bytes = (
2 * b * h * n * d * elem_bytes + kv_elems_loaded * elem_bytes + flash_peak_bytes
)
# Double-buffered Q, K, V + S_tile in SRAM
sram_tile_bytes = (block_r * d + 2 * block_c * d) * elem_bytes + block_r * block_c * 4
flops = (2 if causal else 4) * b * h * n * n * d
ai = flops / max(1, flash_traffic_bytes)
trace = FlashAttnTraceResult(
batch=b,
heads=h,
seq_len=n,
head_dim=d,
block_r=block_r,
block_c=block_c,
causal=causal,
max_abs_err=max_err,
mean_abs_err=mean_err,
has_nan_or_inf=has_nan,
std_hbm_peak_bytes=std_peak_bytes,
flash_hbm_peak_bytes=flash_peak_bytes,
hbm_memory_reduction_x=std_peak_bytes / max(1, flash_peak_bytes),
std_hbm_traffic_bytes=std_traffic_bytes,
flash_hbm_traffic_bytes=flash_traffic_bytes,
hbm_traffic_reduction_x=std_traffic_bytes / max(1, flash_traffic_bytes),
sram_tile_bytes=sram_tile_bytes,
fits_h100_sram=sram_tile_bytes <= spec.sram_limit_bytes,
arithmetic_intensity=ai,
)
if tracer is not None:
with tracer.start_as_current_span("triton.flash_attn_fwd") as span:
span.set_attribute("seq_len", n)
span.set_attribute("causal", causal)
span.set_attribute("max_abs_err", max_err)
span.set_attribute("hbm_memory_reduction_x", trace.hbm_memory_reduction_x)
return out_cast, logsumexp, trace
def run_flash_attention_benchmark(
batch: int = 2,
heads: int = 4,
seq_len: int = 512,
head_dim: int = 64,
block_r: int = 64,
block_c: int = 64,
seed: int = 42,
hw: HardwareSpec | None = None,
tracer: Tracer | None = None,
) -> dict[str, Any]:
"""Verify FlashAttention-2 non-causal & causal equivalence and sweep context O(N^2) vs O(N)."""
spec = hw or HardwareSpec()
gen = torch.Generator().manual_seed(seed)
q = torch.randn((batch, heads, seq_len, head_dim), generator=gen, dtype=torch.float32)
k = torch.randn((batch, heads, seq_len, head_dim), generator=gen, dtype=torch.float32)
v = torch.randn((batch, heads, seq_len, head_dim), generator=gen, dtype=torch.float32)
_, _, noncausal_trace = spmd_flash_attention_fwd(
q, k, v, block_r=block_r, block_c=block_c, causal=False, hw=spec, tracer=tracer
)
_, _, causal_trace = spmd_flash_attention_fwd(
q, k, v, block_r=block_r, block_c=block_c, causal=True, hw=spec, tracer=tracer
)
# Non-divisible odd sequence length stress test (N=149 with Br=32, Bc=32)
q_odd = torch.randn((1, 2, 149, 32), generator=gen, dtype=torch.float32)
k_odd = torch.randn((1, 2, 149, 32), generator=gen, dtype=torch.float32)
v_odd = torch.randn((1, 2, 149, 32), generator=gen, dtype=torch.float32)
_, _, odd_causal_trace = spmd_flash_attention_fwd(
q_odd, k_odd, v_odd, block_r=32, block_c=32, causal=True, hw=spec, tracer=tracer
)
# Context scaling sweep modeling Llama-3 8B head layout (B=1, H=32, fp16)
scaling: list[dict[str, Any]] = []
for ctx in (512, 2048, 8192, 16384, 32768):
std_mb = (2 * 1 * 32 * ctx * ctx * 2) / (1024.0 * 1024.0)
flash_mb = (1 * 32 * ctx * 4) / (1024.0 * 1024.0)
scaling.append(
FlashAttnScalingPoint(
seq_len=ctx,
std_score_matrix_mb=round(std_mb, 3),
flash_logsumexp_mb=round(flash_mb, 3),
memory_reduction_x=round(std_mb / max(1e-9, flash_mb), 1),
exceeds_80gb_h100=std_mb > 81920.0,
).model_dump()
)
return {
"non_causal": noncausal_trace.model_dump(),
"causal": causal_trace.model_dump(),
"non_divisible_causal": odd_causal_trace.model_dump(),
"context_scaling_llama3_32h": scaling,
}
def run_matmul_autotune_sweep(
m: int = 512,
n: int = 512,
k: int = 256,
l2_capacity_bytes: int = 262_144,
seed: int = 42,
hw: HardwareSpec | None = None,
tracer: Tracer | None = None,
) -> AutotuneReport:
"""Sweep tile sizes, L2 swizzle & software pipeline stages respecting SM SRAM capacity."""
spec = hw or HardwareSpec()
gen = torch.Generator().manual_seed(seed)
a = torch.randn((m, k), generator=gen, dtype=torch.float32).to(torch.float16)
b = torch.randn((k, n), generator=gen, dtype=torch.float32).to(torch.float16)
candidates_cfg = [
AutotuneConfig(block_m=32, block_n=32, block_k=32, group_size_m=1, num_stages=1, num_warps=2),
AutotuneConfig(block_m=32, block_n=64, block_k=32, group_size_m=4, num_stages=2, num_warps=4),
AutotuneConfig(block_m=64, block_n=64, block_k=32, group_size_m=1, num_stages=2, num_warps=4),
AutotuneConfig(block_m=64, block_n=64, block_k=32, group_size_m=4, num_stages=3, num_warps=4),
AutotuneConfig(block_m=64, block_n=128, block_k=32, group_size_m=4, num_stages=3, num_warps=4),
AutotuneConfig(block_m=128, block_n=64, block_k=32, group_size_m=4, num_stages=3, num_warps=4),
AutotuneConfig(block_m=128, block_n=128, block_k=32, group_size_m=4, num_stages=4, num_warps=8),
AutotuneConfig(block_m=128, block_n=128, block_k=64, group_size_m=4, num_stages=3, num_warps=8),
# Intentionally exceeds H100 228 KB SMEM (4 * (256*64 + 64*256) * 2 = 256 KB > 228 KB)
AutotuneConfig(block_m=256, block_n=256, block_k=64, group_size_m=4, num_stages=4, num_warps=8),
]
total_flops = 2 * m * n * k
output_bytes = m * n * 2
evaluated: list[AutotuneCandidateResult] = []
valid_list: list[AutotuneCandidateResult] = []
for cfg in candidates_cfg:
sram_req = cfg.sram_required_bytes(elem_bytes=2)
valid_sram = sram_req <= spec.sram_limit_bytes
sched: Literal["row_major", "l2_swizzled"] = (
"row_major" if cfg.group_size_m == 1 else "l2_swizzled"
)
_, swz = spmd_tiled_matmul(
a,
b,
block_m=cfg.block_m,
block_n=cfg.block_n,
block_k=cfg.block_k,
group_size_m=cfg.group_size_m,
schedule_mode=sched,
l2_capacity_bytes=l2_capacity_bytes,
)
total_dram = swz.dram_bytes_fetched + output_bytes
ai = total_flops / max(1, total_dram)
# Roofline ceiling scaled by tile Tensor Core efficiency & software pipeline overlap
tile_eff = min(1.0, (cfg.block_m * cfg.block_n) / (128.0 * 128.0)) * 0.72 + 0.28
stage_overlap = 1.0 - 0.16 / float(cfg.num_stages)
roof_tflops = min(spec.fp16_tflops, (ai * spec.hbm_bw_gbps) / 1000.0)
pred_tflops = roof_tflops * tile_eff * stage_overlap if valid_sram else 0.0
est_ms = (total_flops / max(1e-9, pred_tflops * 1e12)) * 1e3 if pred_tflops > 0 else 999.0
cand = AutotuneCandidateResult(
config=cfg,
valid_sram=valid_sram,
sram_required_bytes=sram_req,
l2_hit_rate=swz.l2_hit_rate,
dram_bytes=total_dram,
arithmetic_intensity=round(ai, 2),
predicted_tflops=round(pred_tflops, 2),
estimated_latency_ms=round(est_ms, 5),
)
evaluated.append(cand)
if valid_sram:
valid_list.append(cand)
best = max(valid_list, key=lambda c: c.predicted_tflops)
naive = evaluated[0]
if tracer is not None:
with tracer.start_as_current_span("triton.autotune_sweep") as span:
span.set_attribute("total_candidates", len(evaluated))
span.set_attribute("pruned_candidates", len(evaluated) - len(valid_list))
span.set_attribute("best_block_m", best.config.block_m)
span.set_attribute("best_predicted_tflops", best.predicted_tflops)
return AutotuneReport(
matrix_shape=(m, n, k),
sram_limit_bytes=spec.sram_limit_bytes,
total_candidates=len(evaluated),
valid_candidates_count=len(valid_list),
pruned_candidates_count=len(evaluated) - len(valid_list),
best_config=best.config,
best_predicted_tflops=best.predicted_tflops,
baseline_naive_tflops=naive.predicted_tflops,
speedup_over_naive=round(best.predicted_tflops / max(1e-6, naive.predicted_tflops), 3),
candidates=evaluated,
)
def run_full_triton_lab_benchmark(
seed: int = 42,
quick: bool = False,
triton_kernels_dir: Path | None = None,
) -> dict[str, Any]:
"""Run complete deterministic Lab 15 suite with OpenTelemetry span telemetry."""
provider, exporter, tracer = create_in_memory_otel_tracer("lab15_triton_kernels")
hw = HardwareSpec()
vec_n = 10_003 if quick else 100_003
sm_rows, sm_cols = (32, 777) if quick else (128, 777)
mm_m, mm_n, mm_k = (256, 256, 128) if quick else (512, 512, 256)
l2_cap = 65_536 if quick else 262_144
fa_seq = 256 if quick else 512
vec_res = run_vector_add_ablation(
n_elements=vec_n, block_size=256, seed=seed, hw=hw, tracer=tracer
)
softmax_res = run_softmax_ablation(
rows=sm_rows, cols=sm_cols, block_size=256, seed=seed, hw=hw, tracer=tracer
)
rmsnorm_res = run_rmsnorm_ablation(
rows=sm_rows, cols=1024, seed=seed, hw=hw, tracer=tracer
)
l2_res = run_l2_swizzle_ablation(
m=mm_m,
n=mm_n,
k=mm_k,
block_m=64,
block_n=64,
block_k=32,
group_size_m=4,
l2_capacity_bytes=l2_cap,
seed=seed,
tracer=tracer,
)
flash_res = run_flash_attention_benchmark(
batch=1 if quick else 2,
heads=2 if quick else 4,
seq_len=fa_seq,
head_dim=64,
block_r=64,
block_c=64,
seed=seed,
hw=hw,
tracer=tracer,
)
autotune_res = run_matmul_autotune_sweep(
m=mm_m,
n=mm_n,
k=mm_k,
l2_capacity_bytes=l2_cap,
seed=seed,
hw=hw,
tracer=tracer,
)
kdir = triton_kernels_dir or (Path(__file__).resolve().parents[2] / "triton_kernels")
ast_audit = audit_tier1_triton_kernels_ast(kdir) if kdir.is_dir() else {"all_expected_present": False}
spans = exporter.get_finished_spans()
span_names = sorted({s.name for s in spans})
total_spans = len(spans)
provider.shutdown()
return {
"config": {
"seed": seed,
"quick": quick,
"hardware": hw.model_dump(),
},
"tier1_ast_audit": ast_audit,
"vector_add_ablation": vec_res,
"softmax_ablation": softmax_res,
"rmsnorm_ablation": rmsnorm_res,
"l2_swizzle_ablation": l2_res,
"flash_attention_ablation": flash_res,
"autotune_report": autotune_res.model_dump(),
"otel_telemetry": {
"total_spans_recorded": total_spans,
"distinct_span_names": span_names,
},
}
"""CLI Benchmark & Artifact Generator for Lab 15 (`T1-P6-U02`: Triton Kernel Engineering from Scratch)."""
from __future__ import annotations
import argparse
import json
import sys
from pathlib import Path
from typing import Any
_LAB_ROOT = Path(__file__).resolve().parents[1]
_SRC_DIR = str(_LAB_ROOT / "src")
if _SRC_DIR not in sys.path:
sys.path.insert(0, _SRC_DIR)
from triton_kernels_lab.flash_attn_and_autotune import run_full_triton_lab_benchmark # noqa: E402
def _fmt_kb(nbytes: int | float) -> str:
return f"{nbytes / 1024.0:.1f} KB"
def _fmt_mb(nbytes: int | float) -> str:
return f"{nbytes / (1024.0 * 1024.0):.2f} MB"
def run_lab15_benchmark(seed: int = 42, quick: bool = False) -> dict[str, Any]:
"""Execute complete Lab 15 benchmark and assemble 6 KPIs, 4 bar charts, and 4 workbench tables."""
bench = run_full_triton_lab_benchmark(
seed=seed,
quick=quick,
triton_kernels_dir=_LAB_ROOT / "triton_kernels",
)
vec = bench["vector_add_ablation"]
sm = bench["softmax_ablation"]
rms = bench["rmsnorm_ablation"]
l2 = bench["l2_swizzle_ablation"]
fa = bench["flash_attention_ablation"]
auto = bench["autotune_report"]
otel = bench["otel_telemetry"]
fa_nc = fa["non_causal"]
fa_c = fa["causal"]
fa_odd = fa["non_divisible_causal"]
scaling_pts = fa["context_scaling_llama3_32h"]
pt_2k = next(pt for pt in scaling_pts if pt["seq_len"] == 2048)
pt_8k = next(pt for pt in scaling_pts if pt["seq_len"] == 8192)
pt_32k = next(pt for pt in scaling_pts if pt["seq_len"] == 32768)
eager_sm = sm["eager_unfused"]
sram_sm = sm["fused_sram_resident"]
online_sm = sm["fused_online_tiled"]
bug_sm = sm["buggy_zero_pad"]
eager_rms = rms["eager_unfused"]
fused_rms = rms["fused_rmsnorm"]
rm_mm = l2["row_major"]
sw_mm = l2["l2_swizzled"]
best_cfg = auto["best_config"]
best_cfg_str = (
f"BM={best_cfg['block_m']} BN={best_cfg['block_n']} "
f"BK={best_cfg['block_k']} G={best_cfg['group_size_m']} S={best_cfg['num_stages']}"
)
autotune_bar_items: list[dict[str, Any]] = []
for c in auto["candidates"]:
cfg = c["config"]
bm, bn, g, stg = cfg["block_m"], cfg["block_n"], cfg["group_size_m"], cfg["num_stages"]
include = (
(bm == 32 and bn == 32)
or (bm == 64 and bn == 64 and g in (1, 4))
or (bm == 128 and bn == 128)
)
if not include:
continue
css_cls = (
"is-fast"
if c["predicted_tflops"] == auto["best_predicted_tflops"]
else ("is-mid" if c["valid_sram"] else "is-slow")
)
autotune_bar_items.append(
{
"label": f"BM{bm}_BN{bn}_G{g}_S{stg}",
"value": c["predicted_tflops"],
"display": f"BM={bm} BN={bn} G={g} S={stg}: {c['predicted_tflops']:.1f} TFLOP/s",
"css_class": css_cls,
}
)
workbench_panels: dict[str, Any] = {
"kpis": [
{
"id": "kpi_fused_softmax_hbm_cut",
"label": "Fused Softmax HBM Traffic Cut",
"value": f"{sm['hbm_reduction_sram_x']:.2f}x",
"unit": f"(-{sm['hbm_savings_pct_sram']:.1f}% | err {sram_sm['max_abs_err']:.1e})",
"status": "ok",
"detail": (
f"Eliminates 5 eager HBM passes ({_fmt_kb(eager_sm['total_hbm_bytes'])} -> "
f"{_fmt_kb(sram_sm['total_hbm_bytes'])}); "
f"online tiled max err {online_sm['max_abs_err']:.1e}."
),
},
{
"id": "kpi_fused_rmsnorm_speedup",
"label": "Fused RMSNorm HBM Cut & Speedup",
"value": f"{rms['hbm_reduction_x']:.2f}x",
"unit": (
f"(Roofline {rms['speedup_roofline_x']:.2f}x | "
f"err {fused_rms['max_abs_err']:.1e})"
),
"status": "ok",
"detail": (
f"Single-kernel fp32 RMSNorm collapses 5 launches "
f"({_fmt_kb(eager_rms['total_hbm_bytes'])}) "
f"to 1 launch ({_fmt_kb(fused_rms['total_hbm_bytes'])})."
),
},
{
"id": "kpi_l2_swizzle_hit_lift",
"label": "L2 Swizzled GEMM Cache Hit Rate",
"value": f"{sw_mm['l2_hit_rate'] * 100.0:.1f}%",
"unit": (
f"(vs Row-Major {rm_mm['l2_hit_rate'] * 100.0:.1f}% | "
f"{l2['dram_traffic_reduction_x']:.2f}x DRAM cut)"
),
"status": "ok",
"detail": (
f"GROUP_SIZE_M={sw_mm['group_size_m']} cuts DRAM tile fetches from "
f"{_fmt_kb(rm_mm['dram_bytes_fetched'])} to "
f"{_fmt_kb(sw_mm['dram_bytes_fetched'])}."
),
},
{
"id": "kpi_flash_attn_hbm_reduction",
"label": "FlashAttention-2 Peak HBM Cut",
"value": f"{fa_c['hbm_memory_reduction_x']:.0f}x",
"unit": f"(@N={fa_c['seq_len']} | @32K: {pt_32k['memory_reduction_x']:.0f}x)",
"status": "ok",
"detail": (
f"Avoids O(N^2) S,P materialization ({_fmt_mb(fa_c['std_hbm_peak_bytes'])} -> "
f"{_fmt_kb(fa_c['flash_hbm_peak_bytes'])}), "
f"max causal err {fa_c['max_abs_err']:.1e}."
),
},
{
"id": "kpi_autotune_pareto_tflops",
"label": "Autotune Pareto H100 Roofline",
"value": f"{auto['best_predicted_tflops']:.1f} TFLOP/s",
"unit": f"({auto['speedup_over_naive']:.2f}x vs 32x32 naive)",
"status": "ok",
"detail": (
f"Winner {best_cfg_str}; pruned {auto['pruned_candidates_count']} config(s) "
f"exceeding {_fmt_kb(auto['sram_limit_bytes'])} SMEM."
),
},
{
"id": "kpi_otel_and_ast_gate",
"label": "Tier-1 AST & OTel Telemetry",
"value": f"{len(bench['tier1_ast_audit']['jitted_kernels'])}/5 kernels",
"unit": f"({otel['total_spans_recorded']} OTel spans)",
"status": "ok",
"detail": (
f"Verified @triton.jit/@triton.autotune AST & "
f"{len(otel['distinct_span_names'])} distinct OpenTelemetry span types."
),
},
],
"bars": [
{
"id": "bar_fusion_hbm_traffic_kb",
"title": (
"HBM Traffic Footprint (KB): Eager Unfused vs Triton Fused Softmax & RMSNorm"
),
"metric_label": "HBM Bytes (KB)",
"items": [
{
"label": "eager_softmax",
"value": round(eager_sm["total_hbm_bytes"] / 1024.0, 2),
"display": (
f"Eager Unfused Softmax (5 ops): {_fmt_kb(eager_sm['total_hbm_bytes'])}"
),
"css_class": "is-slow",
},
{
"label": "fused_online_softmax",
"value": round(online_sm["total_hbm_bytes"] / 1024.0, 2),
"display": (
f"Triton Online Softmax: {_fmt_kb(online_sm['total_hbm_bytes'])}"
),
"css_class": "is-mid",
},
{
"label": "fused_sram_softmax",
"value": round(sram_sm["total_hbm_bytes"] / 1024.0, 2),
"display": (
f"Triton SRAM Softmax: {_fmt_kb(sram_sm['total_hbm_bytes'])}"
),
"css_class": "is-fast",
},
{
"label": "eager_rmsnorm",
"value": round(eager_rms["total_hbm_bytes"] / 1024.0, 2),
"display": (
f"Eager Unfused RMSNorm (5 ops): {_fmt_kb(eager_rms['total_hbm_bytes'])}"
),
"css_class": "is-slow",
},
{
"label": "fused_rmsnorm",
"value": round(fused_rms["total_hbm_bytes"] / 1024.0, 2),
"display": (
f"Triton Fused RMSNorm (1 kernel): {_fmt_kb(fused_rms['total_hbm_bytes'])}"
),
"css_class": "is-fast",
},
],
},
{
"id": "bar_l2_swizzle_cache_hit",
"title": "Tiled GEMM L2 Cache Hit Rate (%): Naive Row-Major vs GROUP_SIZE_M Swizzle",
"metric_label": "L2 Hit Rate (%)",
"items": [
{
"label": "row_major_hit",
"value": round(rm_mm["l2_hit_rate"] * 100.0, 2),
"display": f"Row-Major Schedule (G=1): {rm_mm['l2_hit_rate'] * 100.0:.2f}%",
"css_class": "is-slow",
},
{
"label": "l2_swizzled_hit",
"value": round(sw_mm["l2_hit_rate"] * 100.0, 2),
"display": (
f"L2 Swizzled (GROUP_SIZE_M={sw_mm['group_size_m']}): "
f"{sw_mm['l2_hit_rate'] * 100.0:.2f}%"
),
"css_class": "is-fast",
},
{
"label": "dram_traffic_saved_pct",
"value": round(l2["dram_traffic_savings_pct"], 2),
"display": (
f"DRAM Tile Fetches Eliminated: {l2['dram_traffic_savings_pct']:.1f}%"
),
"css_class": "is-fast",
},
],
},
{
"id": "bar_flash_attn_memory_mb",
"title": "Attention Intermediate Peak Memory (MB) at Llama-3 32 Heads, Seq=8192",
"metric_label": "Peak Intermediate (MB)",
"items": [
{
"label": "std_attn_8k",
"value": round(pt_8k["std_score_matrix_mb"], 2),
"display": (
f"Standard O(N^2) S+P HBM (@8K): {pt_8k['std_score_matrix_mb']:.1f} MB"
),
"css_class": "is-slow",
},
{
"label": "std_attn_2k",
"value": round(pt_2k["std_score_matrix_mb"], 2),
"display": (
f"Standard O(N^2) S+P HBM (@2K): {pt_2k['std_score_matrix_mb']:.1f} MB"
),
"css_class": "is-mid",
},
{
"label": "flash_attn_8k",
"value": round(pt_8k["flash_logsumexp_mb"], 2),
"display": (
f"FlashAttention-2 O(N) LogSumExp (@8K): "
f"{pt_8k['flash_logsumexp_mb']:.2f} MB"
),
"css_class": "is-fast",
},
],
},
{
"id": "bar_autotune_tile_tflops",
"title": "Autotune Sweep Predicted Roofline Throughput (TFLOP/s on H100 SXM)",
"metric_label": "TFLOP/s",
"items": autotune_bar_items[:5],
},
],
"tables": [
{
"id": "tbl_fusion_hbm_and_masking",
"title": "Failure Cases 1 & 2: Boundary Masking, Tail Padding & Kernel Fusion HBM Audit",
"columns": [
"Kernel / Regime",
"Launches / HBM Bytes",
"Max Abs Err vs PyTorch",
"Diagnosis",
],
"rows": [
[
f"VecAdd Masked (N={vec['n_elements']})",
f"1 / {_fmt_kb(vec['masked']['total_hbm_bytes'])}",
f"{vec['masked']['max_abs_err']:.1e}",
f"Guarded {vec['tail_elements']} tail elems; Canary OK",
],
[
f"VecAdd Unmasked Bug (N={vec['n_elements']})",
f"1 / {_fmt_kb(vec['unmasked']['total_hbm_bytes'])}",
f"{vec['unmasked']['max_abs_err']:.1e}",
f"OOB Canary CORRUPTED ({vec['unmasked']['oob_corrupted_elements']} elems)",
],
[
f"Softmax Eager Unfused ({sm['rows']}x{sm['cols']})",
f"5 / {_fmt_kb(eager_sm['total_hbm_bytes'])}",
f"{eager_sm['max_abs_err']:.2e}",
"Bandwidth-bound HBM round-trips",
],
[
"Softmax Zero-Pad Bug (other=0.0)",
f"1 / {_fmt_kb(bug_sm['total_hbm_bytes'])}",
f"{bug_sm['max_abs_err']:.2e}",
"Corrupts denominator on non-divisible cols",
],
[
"Softmax Triton Online Tiled / SRAM",
f"1 / {_fmt_kb(online_sm['total_hbm_bytes'])} -> "
f"{_fmt_kb(sram_sm['total_hbm_bytes'])}",
f"{sram_sm['max_abs_err']:.2e}",
f"{sm['hbm_reduction_sram_x']:.2f}x HBM cut; 0 NaN on [-1000,+1000]",
],
[
f"RMSNorm Eager vs Triton Fused ({rms['rows']}x{rms['cols']})",
f"{_fmt_kb(eager_rms['total_hbm_bytes'])} -> "
f"{_fmt_kb(fused_rms['total_hbm_bytes'])}",
f"{fused_rms['max_abs_err']:.2e}",
f"{rms['hbm_reduction_x']:.2f}x HBM cut ({rms['speedup_roofline_x']:.2f}x)",
],
],
},
{
"id": "tbl_l2_swizzle_gemm",
"title": "Failure Case 3: Tiled GEMM Scheduling (Row-Major vs GROUP_SIZE_M L2 Swizzle)",
"columns": [
"Schedule Mode",
"L2 Tile Hits / Misses",
"L2 Hit Rate & DRAM Amp",
"Max Abs Err vs PyTorch",
],
"rows": [
[
f"Row-Major (G=1, {rm_mm['m']}x{rm_mm['n']}x{rm_mm['k']})",
f"{rm_mm['l2_tile_hits']} / {rm_mm['l2_tile_misses']}",
f"{rm_mm['l2_hit_rate'] * 100.0:.2f}% "
f"({rm_mm['dram_amplification']:.2f}x compulsory)",
f"{rm_mm['max_abs_err']:.2e}",
],
[
f"L2 Swizzled (G={sw_mm['group_size_m']}, "
f"{sw_mm['m']}x{sw_mm['n']}x{sw_mm['k']})",
f"{sw_mm['l2_tile_hits']} / {sw_mm['l2_tile_misses']}",
f"{sw_mm['l2_hit_rate'] * 100.0:.2f}% "
f"({sw_mm['dram_amplification']:.2f}x compulsory)",
f"{sw_mm['max_abs_err']:.2e}",
],
[
"Swizzle Gain Summary",
f"-{rm_mm['l2_tile_misses'] - sw_mm['l2_tile_misses']} DRAM misses",
f"+{l2['l2_hit_rate_lift_pp']:.2f} pp "
f"({l2['dram_traffic_reduction_x']:.2f}x DRAM cut)",
"Exact Tile Equivalence PASS",
],
],
},
{
"id": "tbl_flash_attention_scaling",
"title": "Failure Case 4: FlashAttention-2 Numerical Parity & O(N^2) -> O(N) HBM Scaling",
"columns": [
"Regime / Context Length",
"Std HBM Peak O(N^2)",
"FlashAttn Peak O(N)",
"Reduction & Fidelity",
],
"rows": [
[
f"Live Non-Causal (N={fa_nc['seq_len']}, D=64)",
_fmt_mb(fa_nc["std_hbm_peak_bytes"]),
_fmt_kb(fa_nc["flash_hbm_peak_bytes"]),
f"{fa_nc['hbm_memory_reduction_x']:.0f}x (err {fa_nc['max_abs_err']:.2e})",
],
[
f"Live Causal (N={fa_c['seq_len']}, D=64)",
_fmt_mb(fa_c["std_hbm_peak_bytes"]),
_fmt_kb(fa_c["flash_hbm_peak_bytes"]),
f"{fa_c['hbm_memory_reduction_x']:.0f}x (err {fa_c['max_abs_err']:.2e})",
],
[
f"Odd Tail Causal (N={fa_odd['seq_len']}, Br=32)",
_fmt_kb(fa_odd["std_hbm_peak_bytes"]),
_fmt_kb(fa_odd["flash_hbm_peak_bytes"]),
f"{fa_odd['hbm_memory_reduction_x']:.0f}x "
f"(err {fa_odd['max_abs_err']:.2e})",
],
*[
[
f"Llama-3 32H Projection (N={pt['seq_len']})",
f"{pt['std_score_matrix_mb']:.1f} MB"
+ (" [OOM >80GB]" if pt["exceeds_80gb_h100"] else ""),
f"{pt['flash_logsumexp_mb']:.2f} MB",
f"{pt['memory_reduction_x']:.0f}x peak reduction",
]
for pt in scaling_pts
if pt["seq_len"] in (2048, 8192, 32768)
],
],
},
{
"id": "tbl_autotune_pareto",
"title": "Triton @autotune Sweep: SRAM Capacity Pruning & Roofline Pareto Selection",
"columns": [
"Tile Config (BM, BN, BK, G, S)",
"SMEM Footprint",
"L2 Hit / AI (FLOP/B)",
"Predicted TFLOP/s",
],
"rows": [
[
(
f"({c['config']['block_m']}, {c['config']['block_n']}, "
f"{c['config']['block_k']}, G={c['config']['group_size_m']}, "
f"S={c['config']['num_stages']})"
),
f"{_fmt_kb(c['sram_required_bytes'])}"
+ (" OK" if c["valid_sram"] else " PRUNED"),
f"{c['l2_hit_rate'] * 100.0:.1f}% / {c['arithmetic_intensity']:.1f}",
(
f"{c['predicted_tflops']:.1f} TFLOP/s"
+ (
" [BEST]"
if c["predicted_tflops"] == auto["best_predicted_tflops"]
else ""
)
),
]
for c in auto["candidates"]
],
},
],
}
return {**bench, "workbench_panels": workbench_panels}
def main() -> None:
parser = argparse.ArgumentParser(description="Run Lab 15 Triton Kernels From Scratch benchmark.")
parser.add_argument("--seed", type=int, default=42)
parser.add_argument("--quick", action="store_true")
parser.add_argument(
"--output",
type=Path,
default=_LAB_ROOT / "artifacts" / "ch27_lab15_results.json",
)
args = parser.parse_args()
result = run_lab15_benchmark(seed=args.seed, quick=args.quick)
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(json.dumps(result, indent=2), encoding="utf-8")
print(f"Wrote Lab 15 artifact to {args.output}")
if __name__ == "__main__":
main()
"""Automated verification suite for Lab 15 (`triton_kernels_lab`, Unit T1-P6-U02)."""
from __future__ import annotations
import ast
import json
import subprocess
import sys
from pathlib import Path
import pytest
import torch
import torch.nn.functional as F
from hypothesis import given, settings
from hypothesis import strategies as st
from pydantic import ValidationError
from triton_kernels import HAS_REAL_TRITON, tl, triton
from triton_kernels.tiled_matmul_and_flash_attn import (
flash_attn_fwd_kernel,
tiled_matmul_swizzled_kernel,
)
from triton_kernels.vector_and_fused_norm import (
fused_online_softmax_kernel,
fused_rmsnorm_kernel,
launch_vec_add,
vec_add_kernel,
)
from triton_kernels_lab.flash_attn_and_autotune import (
AutotuneReport,
FlashAttnTraceResult,
create_in_memory_otel_tracer,
run_flash_attention_benchmark,
run_full_triton_lab_benchmark,
run_matmul_autotune_sweep,
spmd_flash_attention_fwd,
)
from triton_kernels_lab.spmd_tile_engine import (
AutotuneConfig,
HardwareSpec,
HBMTraceStats,
L2SwizzleResult,
audit_tier1_triton_kernels_ast,
compute_swizzled_cta_coords,
run_l2_swizzle_ablation,
run_rmsnorm_ablation,
run_softmax_ablation,
spmd_fused_online_softmax,
spmd_fused_rmsnorm,
spmd_tiled_matmul,
spmd_vector_add,
)
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 deserialization libraries."""
py_files = (
list((LAB_ROOT / "src").rglob("*.py"))
+ list((LAB_ROOT / "scripts").rglob("*.py"))
+ list((LAB_ROOT / "triton_kernels").rglob("*.py"))
)
assert len(py_files) >= 6
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_schemas_extra_forbid() -> None:
"""All Lab 15 Pydantic v2 models enforce `extra='forbid'` and hardware bounds."""
hw = HardwareSpec()
assert hw.ridge_point_flops_per_byte > 290.0
assert hw.sram_limit_bytes == 228 * 1024
with pytest.raises(ValidationError):
HardwareSpec.model_validate({"unknown_gpu_flag": True})
with pytest.raises(ValidationError):
AutotuneConfig.model_validate(
{
"block_m": 64,
"block_n": 64,
"block_k": 32,
"group_size_m": 4,
"num_stages": 3,
"num_warps": 4,
"extra_field": 123,
}
)
with pytest.raises(ValidationError):
HBMTraceStats.model_validate(
{
"kernel_name": "test",
"kernel_launches": 0, # ge=1 violated
"hbm_bytes_read": 0,
"hbm_bytes_written": 0,
"total_hbm_bytes": 0,
"flops": 0,
"arithmetic_intensity": 0.0,
"peak_intermediate_hbm_bytes": 0,
"estimated_gpu_time_us": 0.0,
"effective_bandwidth_gbps": 0.0,
"max_abs_err": 0.0,
"mean_abs_err": 0.0,
}
)
with pytest.raises(ValidationError):
L2SwizzleResult.model_validate({"m": 64, "extra": 1})
with pytest.raises(ValidationError):
FlashAttnTraceResult.model_validate({"seq_len": 128, "extra": 1})
def test_03_vector_add_masking_and_tail_canary_guard() -> None:
"""Failure Case 2: Masking prevents OOB canary corruption on non-power-of-two tails."""
gen = torch.Generator().manual_seed(42)
n = 1003 # 4 * 256 = 1024 -> 21 tail elements
x = torch.randn(n, generator=gen, dtype=torch.float32)
y = torch.randn(n, generator=gen, dtype=torch.float32)
out_masked, st_masked, corrupt_masked = spmd_vector_add(x, y, block_size=256, enable_mask=True)
_, st_unmasked, corrupt_unmasked = spmd_vector_add(x, y, block_size=256, enable_mask=False)
assert not corrupt_masked
assert st_masked.oob_guarded_elements == 21
assert st_masked.oob_corrupted_elements == 0
assert st_masked.max_abs_err == 0.0
assert torch.allclose(out_masked, launch_vec_add(x, y), atol=1e-6)
assert corrupt_unmasked
assert st_unmasked.oob_corrupted_elements == 21
def test_04_online_softmax_numerical_equivalence_and_extreme_logits() -> None:
"""Online Milakov-Gimelshein Softmax matches torch.softmax (<1e-5) & resists [-1000, +1000]."""
extreme = torch.linspace(-1000.0, 1000.0, steps=513).unsqueeze(0).expand(8, 513).clone()
unsafe = torch.exp(extreme) / torch.exp(extreme).sum(dim=-1, keepdim=True)
assert torch.isnan(unsafe).any().item()
fused, st_fused = spmd_fused_online_softmax(extreme, block_size=128, pad_with_neg_inf=True)
ref = torch.softmax(extreme, dim=-1)
assert not st_fused.has_nan_or_inf
assert st_fused.max_abs_err < 1e-6
assert torch.allclose(fused, ref, atol=1e-6, rtol=1e-5)
def test_05_softmax_tail_padding_neg_inf_vs_zero_bug_and_hbm_cut() -> None:
"""Forgetting `other=-float('inf')` corrupts Softmax; Fused SRAM Softmax cuts HBM >= 3.5x."""
ablation = run_softmax_ablation(rows=64, cols=777, block_size=256, seed=42)
assert ablation["buggy_zero_pad"]["max_abs_err"] > 1e-3
assert ablation["fused_online_tiled"]["max_abs_err"] < 1e-5
assert ablation["fused_sram_resident"]["max_abs_err"] < 1e-5
assert ablation["hbm_reduction_sram_x"] >= 3.5
assert ablation["hbm_reduction_online_x"] >= 2.5
assert ablation["extreme_logits_naive_nan"] is True
assert ablation["extreme_logits_fused_nan"] is False
def test_06_fused_rmsnorm_equivalence_and_hbm_traffic_reduction() -> None:
"""Fused Triton RMSNorm matches PyTorch reference (<1e-5) & cuts HBM traffic >= 3.0x."""
gen = torch.Generator().manual_seed(42)
x = torch.randn((64, 777), generator=gen, dtype=torch.float32)
w = torch.randn((777,), generator=gen, dtype=torch.float32)
out, st_rms = spmd_fused_rmsnorm(x, w, eps=1e-6, block_size=256)
ref = x * torch.rsqrt(x.pow(2).mean(dim=-1, keepdim=True) + 1e-6) * w
assert st_rms.max_abs_err < 1e-5
assert torch.allclose(out, ref, atol=1e-5)
ablation = run_rmsnorm_ablation(rows=128, cols=1024, seed=42)
assert ablation["hbm_reduction_x"] >= 3.0
assert ablation["speedup_roofline_x"] >= 2.5
def test_07_tiled_matmul_exact_equivalence_and_l2_swizzle_hit_lift() -> None:
"""Failure Case 3: GROUP_SIZE_M L2 Swizzle preserves exact parity & cuts DRAM >= 2.0x."""
res = run_l2_swizzle_ablation(
m=512,
n=512,
k=256,
block_m=64,
block_n=64,
block_k=32,
group_size_m=4,
l2_capacity_bytes=262_144,
seed=42,
)
rm = res["row_major"]
sw = res["l2_swizzled"]
assert rm["max_abs_err"] < 1e-3
assert sw["max_abs_err"] < 1e-3
assert sw["l2_hit_rate"] > rm["l2_hit_rate"] + 0.25
assert res["dram_traffic_reduction_x"] >= 2.5
assert sw["tile_order_preview"][:4] == [(0, 0, 0), (1, 1, 0), (2, 2, 0), (3, 3, 0)]
def test_08_l2_swizzle_coord_bijection_all_pids() -> None:
"""CTA swizzle schedule maps every pid bijectively onto all (pid_m, pid_n) tiles."""
for num_m, num_n, g in [(8, 8, 4), (7, 5, 3), (11, 9, 4)]:
total = num_m * num_n
coords = {
compute_swizzled_cta_coords(pid, num_m, num_n, group_size_m=g, schedule_mode="l2_swizzled")
for pid in range(total)
}
expected = {(r, c) for r in range(num_m) for c in range(num_n)}
assert coords == expected
def test_09_flash_attention_non_causal_equivalence_vs_sdpa() -> None:
"""FlashAttention-2 Forward (causal=False) matches PyTorch SDPA within < 1e-5."""
gen = torch.Generator().manual_seed(42)
q = torch.randn((2, 3, 192, 64), generator=gen, dtype=torch.float32)
k = torch.randn((2, 3, 192, 64), generator=gen, dtype=torch.float32)
v = torch.randn((2, 3, 192, 64), generator=gen, dtype=torch.float32)
out, lse, trace = spmd_flash_attention_fwd(q, k, v, block_r=64, block_c=64, causal=False)
ref = F.scaled_dot_product_attention(q, k, v, is_causal=False)
assert not trace.has_nan_or_inf
assert trace.max_abs_err < 1e-5
assert torch.allclose(out, ref, atol=1e-5, rtol=1e-5)
assert lse.shape == (2, 3, 192)
assert torch.isfinite(lse).all().item()
def test_10_flash_attention_causal_equivalence_and_non_divisible_seq() -> None:
"""FlashAttention-2 Forward (causal=True) handles odd non-divisible seq_len=149 cleanly."""
gen = torch.Generator().manual_seed(123)
q = torch.randn((2, 2, 149, 48), generator=gen, dtype=torch.float32)
k = torch.randn((2, 2, 149, 48), generator=gen, dtype=torch.float32)
v = torch.randn((2, 2, 149, 48), generator=gen, dtype=torch.float32)
out, _, trace = spmd_flash_attention_fwd(q, k, v, block_r=32, block_c=32, causal=True)
ref = F.scaled_dot_product_attention(q, k, v, is_causal=True)
assert not trace.has_nan_or_inf
assert trace.max_abs_err < 1e-5
assert torch.allclose(out, ref, atol=1e-5, rtol=1e-5)
def test_11_flash_attention_hbm_peak_reduction_and_oom_prevention() -> None:
"""Failure Case 4: FlashAttention reduces O(N^2) peak HBM to O(N) & prevents 32K OOM."""
fa = run_flash_attention_benchmark(batch=2, heads=4, seq_len=512, head_dim=64)
assert fa["causal"]["max_abs_err"] < 1e-5
assert fa["causal"]["hbm_memory_reduction_x"] >= 500.0
assert fa["causal"]["fits_h100_sram"] is True
pt_32k = next(p for p in fa["context_scaling_llama3_32h"] if p["seq_len"] == 32768)
assert pt_32k["exceeds_80gb_h100"] is True
assert pt_32k["flash_logsumexp_mb"] < 10.0
assert pt_32k["memory_reduction_x"] >= 30000.0
def test_12_autotune_sram_pruning_and_pareto_winner() -> None:
"""`@triton.autotune` sweep prunes oversized SMEM configs & achieves >1.5x speedup."""
report = run_matmul_autotune_sweep(m=512, n=512, k=256, l2_capacity_bytes=262_144, seed=42)
assert isinstance(report, AutotuneReport)
assert report.pruned_candidates_count >= 1
assert report.valid_candidates_count >= 6
assert report.best_config.sram_required_bytes() <= report.sram_limit_bytes
assert report.speedup_over_naive >= 1.5
assert report.best_config.group_size_m >= 4
def test_13_tier1_triton_kernels_ast_and_shim_structural_audit() -> None:
"""Tier-1 `triton_kernels/` exposes genuine Triton decorators, `tl` ops, & offline shims."""
triton_dir = LAB_ROOT / "triton_kernels"
audit = audit_tier1_triton_kernels_ast(triton_dir)
assert audit["all_expected_present"] is True
assert set(audit["autotuned_kernels"]) >= {
"fused_online_softmax_kernel",
"fused_rmsnorm_kernel",
"tiled_matmul_swizzled_kernel",
"flash_attn_fwd_kernel",
}
for req_op in (
"program_id",
"arange",
"load",
"store",
"dot",
"make_block_ptr",
"advance",
"exp",
"minimum",
"maximum",
):
assert req_op in audit["tl_primitives"]
kernel_defs: dict[str, ast.FunctionDef] = {}
file_trees: dict[str, ast.Module] = {}
for py_path in sorted(triton_dir.glob("*.py")):
tree = ast.parse(py_path.read_text(encoding="utf-8"), filename=str(py_path))
file_trees[py_path.name] = tree
for node in ast.walk(tree):
if isinstance(node, ast.FunctionDef):
decs = [ast.unparse(d) for d in node.decorator_list]
if any("triton.jit" in d for d in decs):
kernel_defs[node.name] = node
for sub in ast.walk(node):
if not isinstance(sub, ast.Call):
continue
if isinstance(sub.func, ast.Name) and sub.func.id == "min":
raise AssertionError(
f"Python min() disallowed inside @triton.jit kernel {node.name}"
)
if (
isinstance(sub.func, ast.Attribute)
and isinstance(sub.func.value, ast.Name)
and sub.func.value.id == "tl"
and sub.func.attr in {"full", "zeros"}
):
shape_arg = (
sub.args[0]
if sub.args
else next(
(kw.value for kw in sub.keywords if kw.arg == "shape"),
None,
)
)
if (
isinstance(shape_arg, (ast.List, ast.Tuple))
and len(shape_arg.elts) == 1
and isinstance(shape_arg.elts[0], ast.Constant)
and shape_arg.elts[0].value == 1
):
raise AssertionError(
f"1D shape [1] disallowed in {node.name}: {ast.unparse(sub)}"
)
mm_fa_tree = file_trees["tiled_matmul_and_flash_attn.py"]
store_calls = [
sub
for sub in ast.walk(mm_fa_tree)
if isinstance(sub, ast.Call)
and isinstance(sub.func, ast.Attribute)
and isinstance(sub.func.value, ast.Name)
and sub.func.value.id == "tl"
and sub.func.attr == "store"
]
assert len(store_calls) >= 3
for sc in store_calls:
assert "tl.float16" not in ast.unparse(sc), (
f"Hardcoded tl.float16 store disallowed: {ast.unparse(sc)}"
)
for kname in ("tiled_matmul_swizzled_kernel", "flash_attn_fwd_kernel"):
k_stores = [
ast.unparse(sub)
for sub in ast.walk(kernel_defs[kname])
if isinstance(sub, ast.Call)
and isinstance(sub.func, ast.Attribute)
and isinstance(sub.func.value, ast.Name)
and sub.func.value.id == "tl"
and sub.func.attr == "store"
]
assert any(".dtype.element_ty" in s for s in k_stores), (
f"{kname} must cast output via .dtype.element_ty on tl.store"
)
for kname in ("fused_online_softmax_kernel", "flash_attn_fwd_kernel"):
alpha_assigns = [
ast.unparse(sub)
for sub in ast.walk(kernel_defs[kname])
if isinstance(sub, ast.Assign)
and len(sub.targets) == 1
and isinstance(sub.targets[0], ast.Name)
and sub.targets[0].id == "alpha"
]
assert alpha_assigns, f"Missing alpha rescaling in {kname}"
assert any(
"tl.where" in expr and "float('inf')" in expr and "tl.exp" in expr
for expr in alpha_assigns
), f"Missing -inf NaN guard on alpha in {kname}: {alpha_assigns}"
sm_node = kernel_defs["fused_online_softmax_kernel"]
sram_if_branches = [
sub
for sub in ast.walk(sm_node)
if isinstance(sub, ast.If)
and (
"n_cols <= BLOCK_SIZE" in ast.unparse(sub.test)
or "BLOCK_SIZE >= n_cols" in ast.unparse(sub.test)
)
]
assert len(sram_if_branches) == 1, "Missing n_cols <= BLOCK_SIZE single-pass specialization"
sram_branch = sram_if_branches[0]
assert not any(isinstance(n, ast.For) for n in sram_branch.body), (
"Single-pass SRAM branch must not contain a multi-tile loop"
)
assert sum(isinstance(n, ast.For) for n in sram_branch.orelse) == 2, (
"Multi-tile fallback branch must keep 2-pass online loop"
)
assert isinstance(HAS_REAL_TRITON, bool)
assert triton.cdiv(1003, 256) == 4
assert tl.float32 is not None
dry = vec_add_kernel[(4,)](None, None, None, 1003, BLOCK_SIZE=256)
if not HAS_REAL_TRITON:
assert dry["status"] == "offline_shim_dry_run"
assert len(fused_online_softmax_kernel.triton_meta.autotune_configs) == 3
assert len(fused_rmsnorm_kernel.triton_meta.autotune_configs) == 3
assert len(tiled_matmul_swizzled_kernel.triton_meta.autotune_configs) == 3
assert len(flash_attn_fwd_kernel.triton_meta.autotune_configs) == 2
@given(
cols=st.integers(min_value=17, max_value=199),
block_size=st.sampled_from([16, 32, 64]),
causal=st.booleans(),
)
@settings(max_examples=12, deadline=None)
def test_14_hypothesis_property_non_divisible_block_and_seq_lens(
cols: int,
block_size: int,
causal: bool,
) -> None:
"""Property test: Online Softmax & FlashAttention stay exact for arbitrary odd shapes."""
gen = torch.Generator().manual_seed(cols * 31 + block_size)
x = torch.randn((4, cols), generator=gen, dtype=torch.float32) * 4.0
sm_out, sm_st = spmd_fused_online_softmax(x, block_size=block_size, pad_with_neg_inf=True)
assert sm_st.max_abs_err < 1e-5
assert torch.allclose(sm_out.sum(dim=-1), torch.ones(4), atol=1e-5)
q = torch.randn((1, 2, cols, 32), generator=gen, dtype=torch.float32)
k = torch.randn((1, 2, cols, 32), generator=gen, dtype=torch.float32)
v = torch.randn((1, 2, cols, 32), generator=gen, dtype=torch.float32)
fa_out, _, fa_tr = spmd_flash_attention_fwd(
q, k, v, block_r=block_size, block_c=block_size, causal=causal
)
assert fa_tr.max_abs_err < 1e-5
assert torch.isfinite(fa_out).all().item()
def test_15_opentelemetry_real_span_instrumentation() -> None:
"""OpenTelemetry InMemorySpanExporter collects all 6 kernel/autotune span types."""
provider, exporter, tracer = create_in_memory_otel_tracer("test_lab15")
x = torch.randn(300)
y = torch.randn(300)
spmd_vector_add(x, y, block_size=128, tracer=tracer)
spmd_fused_online_softmax(torch.randn(8, 130), block_size=64, tracer=tracer)
spmd_fused_rmsnorm(torch.randn(8, 128), torch.randn(128), block_size=64, tracer=tracer)
spmd_tiled_matmul(torch.randn(64, 64), torch.randn(64, 64), block_m=32, block_n=32, tracer=tracer)
spmd_flash_attention_fwd(
torch.randn(1, 2, 64, 32),
torch.randn(1, 2, 64, 32),
torch.randn(1, 2, 64, 32),
block_r=32,
block_c=32,
tracer=tracer,
)
run_matmul_autotune_sweep(m=128, n=128, k=64, l2_capacity_bytes=32768, tracer=tracer)
names = {s.name for s in exporter.get_finished_spans()}
provider.shutdown()
assert {
"triton.vec_add",
"triton.fused_softmax",
"triton.fused_rmsnorm",
"triton.tiled_matmul_swizzle",
"triton.flash_attn_fwd",
"triton.autotune_sweep",
} <= names
def test_16_benchmark_determinism_and_cli_workbench_panels_schema(tmp_path: Path) -> None:
"""Full Lab 15 benchmark is deterministic (`seed=42`) & CLI builds 6 KPI, 4 bar, 4 tables."""
b1 = run_full_triton_lab_benchmark(seed=42, quick=True)
b2 = run_full_triton_lab_benchmark(seed=42, quick=True)
assert b1 == b2
out_file = tmp_path / "ch27_lab15_quick.json"
proc = subprocess.run(
[sys.executable, str(LAB_ROOT / "scripts" / "run_lab_demo.py"), "--quick", "--output", str(out_file)],
cwd=str(LAB_ROOT),
capture_output=True,
text=True,
check=True,
)
assert "Wrote Lab 15 artifact" in proc.stdout
payload = json.loads(out_file.read_text(encoding="utf-8"))
panels = payload["workbench_panels"]
assert len(panels["kpis"]) == 6
assert len(panels["bars"]) == 4
assert len(panels["tables"]) == 4
for kpi in panels["kpis"]:
assert {"id", "label", "value", "unit", "status", "detail"} <= set(kpi.keys())
for bar in panels["bars"]:
assert len(bar["items"]) >= 3
for tbl in panels["tables"]:
assert len(tbl["rows"]) >= 3
def test_17_hardware_roofline_ridge_point_and_memory_bound_classification() -> None:
"""Verify H100 Ridge Point (~295.2 FLOP/B) classifies Softmax as memory-bound & GEMM compute-bound."""
hw = HardwareSpec()
assert hw.ridge_point_flops_per_byte == pytest.approx(295.22388, rel=1e-4)
sm = run_softmax_ablation(rows=64, cols=512, block_size=256)
assert sm["fused_sram_resident"]["arithmetic_intensity"] < hw.ridge_point_flops_per_byte
assert sm["fused_sram_resident"]["arithmetic_intensity"] > sm["eager_unfused"]["arithmetic_intensity"]
SIMT cấp luồng của CUDA, điểm khác biệt cốt lõi của mô hình SPMD cấp khối trong OpenAI Triton (Lab 15, Test 17) và phân loại Roofline của Vector Add fp32 là gì?Triton diễn đạt phép toán trên cả khối véc-tơ/tile và ủy quyền tối ưu luồng/SMEM cho trình biên dịch MLIR/LLVM. VecAdd fp32 thực hiện 1 FLOP cho 12 bytes đọc/ghi (0.0833 FLOP/B), nằm sâu trong vùng nghẽn băng thông bộ nhớ (Test 17).
spmd_vector_add (N = 100,003) và spmd_fused_online_softmax (128 x 777) với BLOCK_SIZE = 256 trên kích thước không chia hết (Lab 15, Tests 03–05), hậu quả nào xảy ra nếu bỏ qua mask hoặc đặt sai other=0.0 cho Softmax?mask = offsets < limit; riêng phép tính cực đại và Softmax phải điền other=-float('inf') để phần tử đệm cho \(\exp(-\infty) = 0\) (Tests 03 & 05).
Online Safe Softmax (Milakov–Gimelshein) kiểm chứng trong Lab 15 (Test 04) trên dải logits cực trị [-1000.0, +1000.0], nhận định nào ĐÚNG?exp(+1000) (4.66e-10 vs torch.softmax, Test 04).
5 toán tử PyTorch Eager rời rạc bằng nhân Triton dung hợp duy nhất cho Softmax (128 x 777) và RMSNorm (128 x 1024) trong Lab 15 (Tests 05–06), mức cải thiện định lượng là bao nhiêu?Softmax và RMSNorm đều nằm sâu trong vùng memory-bound: dung hợp giữ hàng trên SRAM/thanh ghi loại bỏ các lần ghi/đọc trung gian ra HBM (4.00x / 3.49x cắt traffic) và triệt tiêu trễ phóng nhân (Tests 05–06).
Tiled MatMul (512 x 512 x 256, khối 64x64x32, L2 = 256 KB) của Lab 15 (Test 07), vì sao chuyển từ lập lịch Row-Major sang L2 Cache Swizzling (GROUP_SIZE_M = 4) cải thiện mạnh hiệu năng?GROUP_SIZE_M=4 thu hẹp cửa sổ làm việc đồng thời của A và B vừa khít bộ đệm L2 256 KB, giảm số lần trượt L2 từ 576 -> 192 (-66.7% DRAM traffic) mà vẫn bảo toàn kết quả tích ma trận (3.43e-05 err, Tests 07–08).
@triton.autotune trên NVIDIA H100 (SMEM limit = 228.0 KB) trong Lab 15 (Test 12), khẳng định nào CHÍNH XÁC?num_stages giúp cp.async/TMA nạp trước khối \(k+1\) gối đầu lên tl.dot, nhưng nhân bội dung lượng SRAM cần cấp phát. @triton.autotune loại các cấu hình tràn 228 KB và chọn cấu hình Pareto tối ưu (Test 12).
FlashAttention-2 Forward (Lab 15, Tests 09–11), cơ chế nào giúp xóa bỏ bùng nổ bộ nhớ \(O(N^2)\) và tránh sập OOM ở ngữ cảnh dài 32,768 token (Llama-3 32 Heads)?FlashAttention-2 tính chính xác 100% (3.58e-07 vs SDPA), giữ \(\mathbf{S}, \mathbf{P}\) thuần trong SRAM (512x giảm HBM tại N=512, 32,768x tại 32K), bỏ qua các khối tam giác trên khi IS_CAUSAL=True (3.26x giảm traffic), và chỉ xuất LogSumExp \(O(N)\) (Tests 09–11).
tl.make_tensor_descriptor (TMA/Ragged TMA), WarpSpec/Proton, @torch.library.triton_op, Liger-Kernel và FlashAttention-3/4, kết luận nào CHÍNH XÁC?tl.make_tensor_descriptor (TMA/Ragged TMA), WarpSpec và Proton đưa lập lịch Hopper/Blackwell về Python; @torch.library.triton_op + wrap_triton + opcheck tránh đứt gãy torch.compile/AOTInductor; Liger-Kernel (Fused Linear CrossEntropy), FlashAttention-3 (H100, ~75%) và FlashAttention-4 (CuTe-DSL trên B200 dùng software exp + selective rescaling đạt 1,613 TFLOPS / 71%) giải quyết nút thắt bất đối xứng Tensor Core–SFU.
Hướng dẫn & Gợi ý Từng bước cho 6 Bài tập Trụ cột 5
Bài tập 1 — Phân tích Roofline và Mặt nạ Biên trên Vector Add 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Tính số byte đọc/ghi HBM và số phép toán trên mỗi phần tử cho VecAdd ở fp32 (4B) và fp16 (2B). So sánh cường độ số học thu được với điểm gãy 295.2 FLOP/B của NVIDIA H100 SXM.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Kiểm tra spmd_vector_add trong spmd_tile_engine.py (Test 03) tại N = 100,003 và BLOCK_SIZE = 256 khi tắt và bật enable_mask trên vùng đệm canary.
Tiêu chí Đáp án & Số đối chứng
VecAdd fp32 đạt \(I_{\text{arith}} = 1 / 12 = 0.0833\;\text{FLOP/B}\) (fp16: \(0.1667\;\text{FLOP/B}\)), thấp hơn >1,700x điểm gãy Roofline 295.2 FLOP/B nên bị nghẽn băng thông HBM tuyệt đối. Bật mask = offsets < n bảo vệ trọn 93 phần tử đuôi (canary_corrupted = False, max_abs_err = 0.0), trong khi tắt mask làm hỏng 93 ô canary lân cận.
Bài tập 2 — Dẫn xuất Online Safe Softmax và Bẫy Đệm other=0.0 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Viết bước cập nhật \((m_i, \ell_i)\) khi nối hai khối cột liên tiếp và chứng minh biểu thức tổng \(\sum_j \exp(x_j - m_{\text{new}})\) giữ nguyên không phụ thuộc kích thước chia khối.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Đối chiếu run_softmax_ablation và run_rmsnorm_ablation (Tests 04–06) với dải logits [-1000, +1000] và cột lẻ 777 khi đệm other=0.0 vs other=-float('inf').
Tiêu chí Đáp án & Số đối chứng
Thừa số \(\exp(m_{\text{old}} - m_{\text{new}}) \le 1\) loại bỏ tràn số trên [-1000, +1000] (4.66e-10 err, 0 NaN vs NaN khi không trừ max). Đặt nhầm other=0.0 làm sai số vọt lên 3.00e-03. Dung hợp cắt 4.00x (-75.0%) HBM cho Softmax (3,110 -> 777 KB) và 3.49x (-71.4%) HBM (4.91x Roofline speedup) cho RMSNorm.
Bài tập 3 — Toán học L2 Cache Swizzling GROUP_SIZE_M trên Tiled MatMul 20%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Áp dụng công thức compute_swizzled_cta_coords cho lưới 8 x 8 (M=512, N=512, K=256, BM=64, BN=64, BK=32) với GROUP_SIZE_M = 4 để liệt kê 16 cặp (pid_m, pid_n) đầu tiên.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy run_l2_swizzle_ablation trên bộ đệm LRU L2 = 256 KB (Tests 07–08) và giải thích vì sao Row-Major đẩy cột của B khỏi L2 sau mỗi hàng.
Tiêu chí Đáp án & Số đối chứng
Với GROUP_SIZE_M = 4, thứ tự CTA là (0,0),(1,0),(2,0),(3,0),(0,1),(1,1),(2,1),(3,1)..., giữ đồng thời 4 hàng khối A[0..3] (32 tiles) và cột B[:,j] nóng trong L2 256 KB. Nhờ đó L2 Hit Rate nhảy từ 43.75% -> 81.25% (+37.50 pp), giảm L2 misses 576 -> 192 và cắt 3.00x lưu lượng DRAM (2,304 -> 768 KB), vẫn giữ song ánh 100% trên cả lưới lẻ (7, 5).
Bài tập 4 — Chứng minh FlashAttention-2 Forward và Ngân sách HBM 32K 20%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Chứng minh đẳng thức cập nhật tích lũy chưa chia \(\tilde{\mathbf{O}}_i^{\text{new}} = \operatorname{diag}(\alpha)\tilde{\mathbf{O}}_i^{\text{old}} + \tilde{\mathbf{P}}_{ij}\mathbf{V}_j\) và vai trò của vectơ LogSumExp \(L_i = m_i + \ln(\ell_i)\) cùng guard chống -inf - (-inf) -> NaN.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Tính dung lượng trung gian \(\mathbf{S} + \mathbf{P}\) (fp16) vs L (fp32) cho Llama-3 32 Heads tại N=512..32,768, và chạy Tests 09–11 kiểm tra cả chuỗi lẻ N=149.
Tiêu chí Đáp án & Số đối chứng
FlashAttention-2 giữ trọn \(\mathbf{S}_{ij}, \mathbf{P}_{ij}\) trong SRAM (40.0 KB tại Br=64, Bc=64 <= 228 KB), giảm đỉnh HBM 512x tại N=512 (8.00 MB -> 16.0 KB) và 32,768x tại N=32,768 (131,072 MB OOM -> 4.00 MB). Nhờ bỏ khối tam giác trên khi IS_CAUSAL=True, traffic HBM cắt 3.26x với sai số 3.58e-07 (và 2.38e-07 trên chuỗi lẻ N=149).
Bài tập 5 — Autotuning Cắt tỉa SMEM, TMA và Kiến trúc FlashAttention-3 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Viết công thức dung lượng SRAM phụ thuộc num_stages và chỉ ra ngưỡng khiến cấu hình (256, 256, 64, S=4) thất bại trên H100 (228 KB).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
So sánh ranh giới giữa TorchInductor (torch.compile) và nhân viết tay (Liger-Kernel, Unsloth, FlashAttention-3), kiểm chứng qua Test 12.
Tiêu chí Đáp án & Số đối chứng
S_SMEM = S * (BM*BK + BK*BN) * 2B: cấu hình (256, 256, 64, S=4) đòi hỏi 256.0 KB > 228.0 KB nên bị loại tự động, còn (128, 128, 32, G=4, S=4) (64.0 KB) đạt 235.2 TFLOP/s (9.55x). TorchInductor tự sinh nhân dung hợp đồ thị nhưng không tự phát minh Online CrossEntropy (Liger-Kernel) hay warp Producer/Consumer TMA + WGMMA (FlashAttention-3).
Bài tập 6 — Kiểm toán AST Triton Tầng 1 và Nghiệm thu Toàn trình Lab 15 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Kiểm tra triton_kernels/ bảo đảm cả 5 nhân đều có @triton.jit, @triton.autotune, nguyên thủy tl.make_block_ptr/tl.dot và tách rời khỏi src/triton_kernels_lab/ để chạy sạch mypy --strict.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy uv.exe lock --check, ruff check, mypy src triton_kernels, scripts/run_lab_demo.py, và 17/17 pytest -p no:cacheprovider -v (Tests 01–02, 13–17).
Tiêu chí Đáp án & Số đối chứng
Cổng AST xác nhận đủ 5/5 nhân @triton.jit, 4/4 @triton.autotune và 0 thư viện pickle/joblib; uv lock --check, ruff, mypy --strict đạt 0 lỗi; 17/17 pytest (kể cả kiểm thử thuộc tính Hypothesis và 11 spans OpenTelemetry across 6 loại sự kiện) đạt xanh hoàn toàn, xuất ch27_lab15_results.json chuẩn 6 KPI, 4 bar, 4 bảng.