Stanford CS336: Language Modeling from Scratch
Lecture 6 — Benchmarking, Profiling, and GPU Kernels
From Hardware Execution to Fused Triton Kernels on NVIDIA BlackwellLate 2026 Edition
From Hardware Mental Models to Fast Kernels
1. GPU Model
B200 memory, SMs,
warps, occupancy
2. Measure
Benchmark, profile,
check invariance
3. Kernel DSLs
CUDA, Triton, Gluon,
TileLang, cuTile, CuTe
4. Write Kernels
GeLU, softmax,
row sum, tiled GEMM
The programming model gives you correctness; the hardware model gives you speed
Never guess bottlenecks: benchmark end-to-end latency, then profile kernel execution
Core optimization levers: kernel fusion , tiling , and cutting launch overhead
Concrete hardware target: NVIDIA Blackwell (B200) with CUDA and Triton
Blackwell B200 Memory Hierarchy
Inside each SM (148 SMs on B200)
Registers — 256 KB / SM
~447 TB/s aggregate
Tensor Memory (TMEM) — Tensor Cores
L1 Cache + Shared Memory — 256 KB / SM
~40 TB/s aggregate (rough estimate)
L2 Cache (Shared Across GPU) — 96–126 MB
~17 TB/s (rough estimate)
HBM (Global Memory) — 192 GB
8 TB/s — largest, slowest tier
Bandwidth drops sharply as capacity grows: ~447 TB/s at registers down to 8 TB/s at HBM
Fast kernels keep data on-chip (registers and shared memory) and minimize HBM round-trips
Blackwell adds Tensor Memory (TMEM) between registers and shared memory to feed tensor cores
L1/L2 bandwidth numbers are rough estimates; HBM bandwidth and capacities are architectural specs.
B200 vs. Historical GPU Baselines (A100, H100)
Specification
A100 (Historical)
H100 (Historical)
B200 (Current)
# Streaming Multiprocessors (SMs) 108 132 148
Register file (per SM) 256 KB 256 KB 256 KB
L1 cache + shared memory (per SM) 192 KB 256 KB 256 KB
L2 cache size 40 MB 50 MB 96–126 MB
HBM capacity 80 GB 80 GB 192 GB
Register bandwidth ~116 TB/s ~401 TB/s ~447 TB/s
L1 + shared memory bandwidth ~19 TB/s ~33 TB/s ~40 TB/s
L2 cache bandwidth ~5–8 TB/s ~12 TB/s ~17 TB/s
HBM bandwidth 2 TB/s 3.35 TB/s 8 TB/s
Register and shared memory per SM barely grew across generations, while HBM capacity and bandwidth jumped dramatically—keeping on-chip tile budgets tight.
Programming Model: Threads, Blocks, and Grids
Software Hierarchy
Grid
Collection of thread
blocks (1D / 2D / 3D)
Thread Block (CTA)
Cooperating threads
with fast local sync
Thread
Executes kernel code
on a slice of data
Hardware Scope
Entire GPU
HBM (global memory)
Single SM
Shared memory
Execution Lane
Private registers
Thread : private registers, executes scalar instructions
Thread block (CTA) : scheduled onto one SM; threads share its shared memory
Grid : all thread blocks launched by one kernel; communicates via HBM
Thread block clusters (H100 and B200): group blocks across SMs to enable distributed shared memory
Why Do Thread Blocks Exist?
Elementwise operations (e.g., GeLU): each output $y_i = f(x_i)$ is independent
One thread per element (or small chunk) requires zero communication
Non-elementwise operations (e.g., softmax, matrix multiply): threads must exchange intermediate values
Communicating through HBM is slow (8 TB/s vs. ~40 TB/s shared memory on B200)
Instead, place collaborating threads in one thread block on the same SM
Every thread in a block reads and writes the same SM-local shared memory
In Triton , you program directly at the thread-block level rather than per thread
Next: four hardware realities that determine whether a correct kernel is actually fast.
Warps and Control Divergence
Thread block (64 threads) = 2 warps of 32 threads
Warp 0: T0 … T31 (lockstep)
Warp 1: T32 … T63 (lockstep)
Control divergence inside one warp: if (cond) A else B
Pass 1 (A):
Active: A A A A A A A
masked off (idle lanes)
Pass 2 (B):
masked off
Active: B B B B B B B B B B B B B B B
Both branches execute sequentially — total warp time = time(A) + time(B)
Hardware schedules threads in warps of 32 threads executing the same instruction in lockstep
Control divergence serializes taken and untaken paths within a warp
Latency hiding : an SM holds many warps and switches to a ready warp with zero cost when another stalls on HBM
Register Pressure and Warp Occupancy
Each thread uses between 0 and 255 registers
Each SM has 65,536 32-bit registers (256 KB) and supports up to 64 concurrent warps
More registers per thread → fewer resident blocks → lower warp occupancy
Low occupancy is not always bad if each thread does more work (thread coarsening )
Worked Occupancy Calculation
Block size: $128$ threads ($4$ warps)
Register usage: $160$ registers / thread
$\text{Regs / block} = 128 \times 160 = 20{,}480$
$\text{Blocks / SM} = \lfloor 65{,}536 / 20{,}480 \rfloor = 3$
$\text{Active warps} = 3 \times 4 = 12$
$\text{Occupancy} = \dfrac{12}{64} = \mathbf{18.75\%}$
Even with ample SM warp slots, register usage caps concurrency to 3 blocks per SM.
Shared Memory Bank Conflicts and Swizzling
32 banks × 4 bytes wide (each bank serves 1 address/cycle)
B00
B01
B02
B03
…
B31
M[0,0]
M[0,1]
M[0,2]
M[0,3]
row 0 → 1 cycle
M[0,31]
M[1,0]
M[1,1]
M[1,2]
M[1,3]
…
M[1,31]
M[2,0]
… rows 2–30 …
M[31,0]
col 0 all hits B00 → 32-way conflict!
Fix: swizzling (e.g., bank = row XOR col)
B00
B01
B02
B03
… B31
M[0,0]
M[0,1]
M[0,2]
M[0,3]
row 0 → distinct banks
M[1,1]
M[1,0]
M[1,3]
M[1,2]
…
M[2,2]
M[2,3]
M[2,0]
M[2,1]
col 0 spread across banks
M[3,3]
M[3,2]
M[3,1]
M[3,0]
Both row & col conflict-free
Unavoidable in matmul A @ B without swizzling: we need rows of A and columns of B.
Shared memory has 32 banks (4 bytes wide); simultaneous hits to different addresses in the same bank serialize
Swizzling permutes shared-memory indices (row ^ col) so both row and column reads stay conflict-free
HBM Memory Coalescing
Coalesced: 32 threads × 4 bytes = 1 transaction (one 128-byte cache line)
Warp: T0 T1 T2 T3 … T31 (contiguous addresses)
Cache Line 0: M00 … M31 (128 B — 100% used)
Cache Line 1: M32 … M63 (not fetched)
Strided / uncoalesced: threads hit separate cache lines → wasted HBM bandwidth
Line 0: only M00 used
Line 1: only M32 used
Line 2: only M64 used
… up to 32 cache lines
The memory controller combines a warp's HBM accesses into 128-byte cache-line transactions
Best case: all 32 threads read consecutive 4-byte words (full coalescing, zero wasted bytes)
Ensure inner loops stride along the contiguous dimension (stride 1 in memory)
Block Occupancy and Wave Quantization
Launching 160 thread blocks on a B200 (148 SMs)
Wave 1
148 blocks running across all 148 SMs (100% SM utilization)
Wave 2
12
136 SMs sit idle waiting for the tail wave to finish
SM 0
Streaming Multiprocessors on B200
SM 147
Thread blocks are scheduled onto SMs in waves
Wave quantization : a tiny tail wave can nearly double kernel runtime while leaving most SMs idle
Mitigation: choose tile sizes so total blocks are a multiple of # SMs (148 on B200) or use persistent kernels
Programming Model vs. Hardware Reality
Level Programming Abstraction (Correctness) Hardware Mechanism (Performance)
Grid Independent thread blocks Wave quantization across 148 SMs (B200)
HBM Flat global address space 128-byte coalesced cache-line transactions
Thread Block Shared scratchpad + barrier sync 32 shared-memory banks (4 B wide) & swizzling
Warp / Thread SIMT threads with private state 32-thread lockstep, divergence, register occupancy
Understand the programming model to write correct kernels; understand the hardware to make them fast.
The Performance Engineering Loop
1. Benchmark
How long does it take?
2. Profile
Where is time spent?
3. Change
Fuse, tile, tune
4. Verify
Accuracy & CI
Re-benchmark and re-profile after every change
Benchmarking measures end-to-end wall-clock time to compare implementations and study scaling
Profiling breaks time down by individual CUDA kernel so you fix the real bottleneck
Verification checks numerical closeness and batch invariance before trusting any speedup
Benchmarking GPU Kernels Correctly
def benchmark(run, num_warmups=1, num_trials=3):
for _ in range(num_warmups):
run() # compile / cache warmup
torch.cuda.synchronize() # wait for warmup to finish
times = []
for _ in range(num_trials):
start = torch.cuda.Event(enable_timing=True)
end = torch.cuda.Event(enable_timing=True)
start.record()
run()
end.record()
torch.cuda.synchronize() # wait for GPU work!
times.append(start.elapsed_time(end)) # milliseconds on GPU
return sum(times) / len(times)
CUDA launches are asynchronous : omitting torch.cuda.synchronize() only times CPU dispatch
Warmup excludes one-time JIT compilation and allocator setup; CUDA events exclude CPU overhead
Run multiple trials (or use torch.utils.benchmark) to capture steady-state variance
How Latency Scales with Problem Size
Overhead-bound
(roughly flat)
Compute-bound
cubic scaling O(N³)
256
512
1024
2048
4096
8192
Matrix dimension N (N × N matmul)
Wall-clock latency (schematic)
Sweep dim across 256, 512, 1024, 2048, 4096, 8192 for square matmul
At small dimensions , latency is roughly constant: kernel launch overhead and under-filled SMs dominate
At large dimensions , the GPU saturates and latency follows cubic $O(N^3)$ scaling
Small-batch autoregressive decode lives in the left regime—where launch overhead matters most.
Small Batch: Launch Overhead, CUDA Graphs, and Megakernels
1. Eager PyTorch (many small kernels)
RMSNorm
gap
QKV GEMV
gap
RoPE
gap
Attention
gap
MLP / MoE
2. CUDA Graph (single replay removes CPU dispatch overhead; inter-kernel boundaries remain)
RMSNorm
QKV GEMV
RoPE
Attention
MLP / MoE
3. Persistent Megakernel (entire decode step in one kernel launch)
One persistent launch: RMSNorm → QKV → RoPE → Attn → MLP
no launch gaps, on-chip handoff
At small batch, launch overhead and gaps between kernels dominate GPU runtime
CUDA Graphs capture a static kernel sequence and replay it in one CPU call, shrinking dispatch overhead
A persistent megakernel goes further: it runs an entire decode step in a single launch, eliminating inter-kernel drains
Profiling: Seeing What Actually Executes
def profile(run, num_warmups=1):
for _ in range(num_warmups):
run()
torch.cuda.synchronize()
with torch.profiler.profile(activities=[ProfilerActivity.CUDA]) as prof:
run()
torch.cuda.synchronize()
return prof.key_averages().table(sort_by="cuda_time_total", row_limit=10)
Reveals the exact CUDA kernels invoked under the hood and how long each spends on the GPU
Dispatch depends on tensor shape: add(2048), matmul(2048), and matmul(128) select different kernels
Use NVIDIA Nsight when you need hardware counters (SM utilization, achieved HBM bandwidth, stall reasons)
Decoding a Profiled CUDA Kernel Name
cutlass3x _sm100 _simt_sgemm_f32 _f32_f32_f32_f32_64x64x16 _1x1x1_3_nnn_align1_bi…
cutlass3x
NVIDIA's CUDA
linear algebra
template library
sm100
NVIDIA Blackwell
architecture
(B200)
f32
32-bit floating
point operand
and accumulator
64x64x16
Thread-block tile
shape (M × N × K)
chosen for this size
Kernel names expose library, target architecture, precision, and tile shape directly in the profile
PyTorch dispatches different tile shapes and algorithms as tensor dimensions change (128 vs. 2048)
Case Study: Naive vs. Built-in vs. Compiled GeLU
Tanh approximation of GeLU: $\;\text{GeLU}(x) = 0.5\,x\left(1 + \tanh\!\left(\sqrt{2/\pi}\,(x + 0.044715\,x^3)\right)\right)$
# 1. Naive PyTorch (many separate elementwise ops)
def naive_gelu(x):
return 0.5 * x * (1 + torch.tanh(0.79788456 * (x + 0.044715 * x * x * x)))
# 2. Built-in PyTorch (fused CUDA kernel)
def builtin_gelu(x):
return torch.nn.functional.gelu(x, approximate="tanh")
# 3. PyTorch compiler (automatically generates a fused Triton kernel)
compiled_gelu = torch.compile(naive_gelu)
All three produce the same output (verified with torch.allclose)
Benchmarked on a $16{,}384 \times 16{,}384$ tensor: builtin_gelu and compiled_gelu are dramatically faster than naive_gelu
Why Kernel Fusion Wins on GeLU
Naive GeLU (no fusion): every op launches a kernel and round-trips HBM
HBM (8 TB/s — bottleneck for elementwise ops)
x * x * x
mul / add
scale
tanh
+ 1
0.5 * x * …
Built-in / torch.compile GeLU (fused): 1 kernel, 1 HBM read, 1 HBM write
Single fused Triton/CUDA kernel: all intermediates stay in registers (~447 TB/s)
read x once
write y once
Elementwise math is memory-bandwidth bound , not compute bound
torch.compile automatically lowers naive_gelu into a single fused Triton kernel
Correctness Testing: Numerical Accuracy & Batch Invariance
Standard kernel checks compare against a PyTorch reference with torch.allclose
Subtle production bug: a kernel's output changes with batch size
Because floating-point addition is not associative: $(a + b) + c \neq a + (b + c)$
Split-K reductions and tile-shape dispatch change with batch size, altering summation order
In LLM serving, the same prompt can produce different tokens depending on co-batched requests
Batch invariance must be tested alongside benchmarking and profiling
vLLM keeps batch-invariance tests for matmul and fused all-reduce + RMSNorm in CI
Fast kernels are only shippable if they pass both accuracy and batch-invariance checks.
Writing Kernels: CUDA vs. Triton
CUDA (NVIDIA)
Program at the thread level
Specify what each individual thread executes
Pros : fine-grained control over registers, warp intrinsics, shared-memory layouts, and async pipelines
Cons : must manually manage coalescing, bank conflicts, shared memory, and synchronization
Triton (OpenAI)
Program at the thread-block level
Specify operations on whole blocks (tiles) of data in Python
Mental model : load tile into on-chip memory, compute (with fusion), store back to HBM
Compiler automates coalescing, shared-memory allocation, and scheduling within a block
The Modern Kernel DSL Landscape
← Higher level (more compiler automation)
Lower level (more explicit hardware control) →
Triton
High level
Block-level Python;
torch.compile backend;
fast prototyping
NVIDIA cuTile
High level
NVIDIA's tile-based
programming model
for GPUs
TileLang
Middle level
Explicit tile buffers
& scheduling; powers
DeepSeek TileKernels
Gluon
Lower-level Triton
Triton dialect with
explicit layouts,
used for Blackwell
CuTe DSL
Lowest level
Python CUTLASS;
FlashAttention-4 is
written in it
Kernel authoring now spans a continuum from Triton / cuTile down to Gluon , CuTe DSL , and raw CUDA / CUTLASS
Trade-off : higher-level DSLs accelerate development, but give up some performance on the hardest kernels
We use Triton next to learn the core block-level patterns cleanly
The Triton Kernel Pattern
1. Identify Block
tl.program_id(axis)
2. Load Tile + Mask
tl.load(ptrs, mask)
3. Compute On-Chip
elementwise / reduce / dot
4. Store Tile
tl.store(ptrs, y)
We will build four kernels of increasing structure:
GeLU : 1D elementwise fusion
Softmax : row-wise reduction (entire row fits in one block)
Row sum : tiled reduction (row exceeds one block)
Matmul + ReLU : 2D tiling with shared-memory reuse and fused epilogue
Example 1: Elementwise GeLU — Partitioning the Grid
1D tensor of length num_elements split into chunks of BLOCK_SIZE = 1024
Block 0 (pid=0)
Block 1 (pid=1)
Block 2 (pid=2)
Block 3 (valid)
masked
mask = offsets < num_elements prevents out-of-bounds access
def triton_gelu(x: torch.Tensor):
assert x.is_cuda and x.is_contiguous()
y = torch.empty_like(x)
num_elements = x.numel()
BLOCK_SIZE = 1024
num_blocks = triton.cdiv(num_elements, BLOCK_SIZE) # ceil(N / BLOCK_SIZE)
triton_gelu_kernel[(num_blocks,)](x, y, num_elements, BLOCK_SIZE=BLOCK_SIZE)
return y
Launch syntax kernel[grid](args...) spawns num_blocks independent program instances.
Example 1: Triton GeLU Kernel
@triton.jit
def triton_gelu_kernel(x_ptr, y_ptr, num_elements, BLOCK_SIZE: tl.constexpr):
pid = tl.program_id(axis=0)
offsets = pid * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
mask = offsets < num_elements
x = tl.load(x_ptr + offsets, mask=mask)
# tanh(a) = (exp(2a) - 1) / (exp(2a) + 1)
a = 0.79788456 * (x + 0.044715 * x * x * x)
exp = tl.exp(2 * a)
tanh = (exp - 1) / (exp + 1)
y = 0.5 * x * (1 + tanh)
tl.store(y_ptr + offsets, y, mask=mask)
BLOCK_SIZE: tl.constexpr tells the compiler the tile length is a compile-time constant (power of 2)
Every intermediate (a, exp, tanh) lives in registers—one HBM read and one HBM write total
Under the Hood: Triton Compiles to PTX
Triton Python
@triton.jit kernel
PTX (Virtual GPU ISA)
kernel.asm["ptx"]
SASS (Blackwell Binary)
native sm100 instructions
Inspecting kernel.asm["ptx"] for triton_gelu reveals how Triton maps blocks to threads:
ld.global.* and st.global.* perform global HBM loads and stores
%ctaid.x is the block index; %tid.x is the thread index inside the block
%f* are floating-point registers; %r* are integer registers
Thread coarsening : Triton automatically assigns 8 elements per thread to amortize address math
Example 2: Fused Softmax — Counting HBM Traffic
Row-wise softmax subtracts the row max for numerical stability (e.g., [0, 0, 100] avoids overflow in $\exp$):
Naive PyTorch Step ($M \times N$ matrix) HBM Reads HBM Writes
x_max = x.max(dim=1)[0]$MN$ $M$
x = x - x_max[:, None]$MN + M$ $MN$
num = torch.exp(x)$MN$ $MN$
den = num.sum(dim=1)$MN$ $M$
y = num / den[:, None]$MN$ $MN$
Naive total $5MN + M$ $3MN + 2M$
Fused Triton kernel (ideal) $MN$ $MN$
Total memory traffic drops from $\approx 8MN$ to $2MN$ elements — up to a 4× memory-bandwidth speedup.
Example 2: Fused Softmax in Triton (Row Fits in One Block)
@triton.jit
def triton_softmax_kernel(
x_ptr, y_ptr, x_row_stride, y_row_stride,
num_cols, BLOCK_SIZE: tl.constexpr,
):
row_idx = tl.program_id(0)
col_offsets = tl.arange(0, BLOCK_SIZE)
x_ptrs = x_ptr + row_idx * x_row_stride + col_offsets
x_row = tl.load(x_ptrs, mask=col_offsets < num_cols,
other=float("-inf"))
x_row = x_row - tl.max(x_row, axis=0)
numerator = tl.exp(x_row)
y_row = numerator / tl.sum(numerator, axis=0)
y_ptrs = y_ptr + row_idx * y_row_stride + col_offsets
tl.store(y_ptrs, y_row, mask=col_offsets < num_cols)
Grid = (M,) — 1 block/row
Row 0 (0..N-1)
-inf
Row 1 (pid=1)
-inf
Row 2 …
-inf
BLOCK_SIZE = next_power_of_2(N)
Padding masked lanes with -inf ensures they contribute neither to tl.max nor to tl.exp ($e^{-\infty}=0$)
Triton handles the intra-block reduction automatically
Example 3: When a Row Does Not Fit in One Block
Example: row length N = 12 with BLOCK_SIZE = 4 (or N = 4096 with BLOCK_SIZE = 1024 → 4 tiles)
Tile 0
T0 T1 T2 T3
Tile 1
T0 T1 T2 T3
Tile 2
T0 T1 T2 T3
Per-lane accumulator acc[BLOCK_SIZE] (in registers)
Final block reduction: tl.sum(acc, axis=0)
Split the long row into tiles of size BLOCK_SIZE (e.g., 4 tiles for 4096 cols / 1024 block)
Each lane loops over tiles, adding into a private register accumulator acc
Run one final reduction across the block (via shared memory or warp shuffles) to get the scalar sum
Example 3: Tiled Row-Sum Kernel in Triton
@triton.jit
def row_sum_kernel(x_ptr, out_ptr, N, BLOCK_SIZE: tl.constexpr):
row = tl.program_id(0) # one block per row
acc = tl.zeros([BLOCK_SIZE], dtype=tl.float32)
for start in range(0, N, BLOCK_SIZE): # loop over tiles along row
cols = start + tl.arange(0, BLOCK_SIZE)
mask = cols < N
x = tl.load(x_ptr + row * N + cols, mask=mask, other=0.0)
acc += x
result = tl.sum(acc, axis=0) # reduce BLOCK_SIZE → scalar
tl.store(out_ptr + row, result)
Notice the identity element changes by reduction: other=0.0 for sum (vs. -inf for softmax max)
Accumulating in tl.float32 preserves precision across long reductions
This same tile-loop + register accumulator pattern scales directly to 2D matrix multiplication
Example 4: Matrix Multiplication — Why Tiling Is Essential
Computing $C = A B$ with $A \in \mathbb{R}^{M \times K}$, $B \in \mathbb{R}^{K \times N}$, $C \in \mathbb{R}^{M \times N}$:
Approach HBM Reads HBM Writes Arithmetic Intensity Feasible?
Naive (1 output $C[m,n]$ from HBM)
$MKN$ pairs
$MN$
$O(1)$
Memory-bound
Idealized (all of $A, B$ in SMEM)
$MK + KN$
$MN$
$O(N)$
Too large for 256 KB SMEM
Tiled (load $B_M \times B_K$, $B_K \times B_N$ tiles)
Reuse each tile across block
$MN$
$O(\text{tile\_size})$
Fits on-chip & compute-bound
Key insight: outputs in the same row of $C$ reuse the same row of $A$; outputs in the same column reuse the same column of $B$
Tiling loads each $A$ and $B$ block into shared memory once and reuses it across an entire output tile
2D Tiled Matrix Multiplication Dataflow
A (M × K)
A_k
step along K by BLOCK_K
B_M
×
B (K × N)
B_k
BLOCK_N
=
C (M × N)
acc
(pid_m,n)
Fused
ReLU /
GeLU
Each thread block owns one BLOCK_M × BLOCK_N output tile of C, accumulating Σ_k A_k @ B_k on-chip.
Bonus fusion : apply an activation (ReLU, GeLU) to acc before writing $C$ back to HBM—zero extra memory traffic
Each tile multiplication maps directly onto tensor cores via tl.dot(a, b)
Addressing 2D Tiles: Linearized Memory and Strides
Logical 2 × 4 matrix
0
1
2
3
4
5
6
7
element (row=1, col=2)
stride_row = 4, stride_col = 1
Flat 1D HBM layout
0
1
2
3
4
5
6
7
+0 +1 +2 +3
+4 +5 +6 +7
index = row × stride_row + col × stride_col = 1 × 4 + 2 × 1 = 6
Example 4: Triton Matmul + ReLU (Grid & Pointer Setup)
# Host launcher: 2D grid of output tiles
M, K = a.shape
K, N = b.shape
c = torch.empty((M, N), device=a.device)
BLOCK_M, BLOCK_N, BLOCK_K = 64, 64, 32
grid = (triton.cdiv(M, BLOCK_M), triton.cdiv(N, BLOCK_N))
matmul_relu_kernel[grid](
a, b, c, M, N, K,
a.stride(0), a.stride(1), b.stride(0), b.stride(1), c.stride(0), c.stride(1),
BLOCK_M, BLOCK_N, BLOCK_K,
)
# Inside @triton.jit matmul_relu_kernel:
pid_m, pid_n = tl.program_id(0), tl.program_id(1)
indices_m = pid_m * BLOCK_M + tl.arange(0, BLOCK_M)
indices_n = pid_n * BLOCK_N + tl.arange(0, BLOCK_N)
indices_k = tl.arange(0, BLOCK_K)
a_ptrs = a_ptr + indices_m[:, None] * stride_am + indices_k[None, :] * stride_ak
b_ptrs = b_ptr + indices_k[:, None] * stride_bk + indices_n[None, :] * stride_bn
a_ptrs has shape [BLOCK_M, BLOCK_K] and b_ptrs has shape [BLOCK_K, BLOCK_N].
Example 4: Triton Matmul + ReLU (K-Loop & Fused Epilogue)
acc = tl.zeros([BLOCK_M, BLOCK_N], dtype=tl.float32)
for k in range(0, K, BLOCK_K):
a = tl.load(a_ptrs, mask=(indices_m[:, None] < M) & (indices_k[None, :] + k < K), other=0.0)
b = tl.load(b_ptrs, mask=(indices_k[:, None] + k < K) & (indices_n[None, :] < N), other=0.0)
acc += tl.dot(a, b)
a_ptrs += BLOCK_K * stride_ak # advance along rows of A
b_ptrs += BLOCK_K * stride_bk # advance along cols of B
acc = tl.maximum(acc, 0.0) # fused ReLU epilogue (zero extra HBM traffic)
c_ptrs = c_ptr + indices_m[:, None] * stride_cm + indices_n[None, :] * stride_cn
tl.store(c_ptrs, acc, mask=(indices_m[:, None] < M) & (indices_n[None, :] < N))
2D masks with other=0.0 handle arbitrary non-multiple dimensions cleanly
tl.dot(a, b) lowers to tensor-core MMA instructions; ReLU runs in registers before the single HBM store
Lecture Recap
Hardware mental model (B200) : 148 SMs, 8 TB/s HBM vs. ~40 TB/s SMEM vs. ~447 TB/s registers; optimize for warps, register occupancy, coalescing, bank conflicts, and wave quantization
Measure and verify : benchmark with warmup + CUDA events + synchronize(); profile with PyTorch Profiler / Nsight; test batch invariance in CI (e.g., vLLM matmul and fused all-reduce+RMSNorm)
Small-batch overhead : CUDA Graphs cut CPU dispatch cost; persistent megakernels fuse an entire decode step into one launch
Kernel DSL spectrum : Triton and cuTile (high level) → TileLang (middle) → Gluon (Blackwell layouts) → CuTe DSL (Python CUTLASS) → CUDA / PTX
Four core Triton patterns : GeLU (elementwise fusion), softmax (block reduction), row sum (tiled reduction), and matmul + ReLU (2D tiling + fused epilogue)