Stanford CS336: Language Modeling from Scratch Lecture 6 — Benchmarking, Profiling, and GPU Kernels

From Hardware Execution to Fused Triton Kernels on NVIDIA Blackwell
Late 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

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)108132148
Register file (per SM)256 KB256 KB256 KB
L1 cache + shared memory (per SM)192 KB256 KB256 KB
L2 cache size40 MB50 MB96–126 MB
HBM capacity80 GB80 GB192 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 bandwidth2 TB/s3.35 TB/s8 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?

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)

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.

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

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

Programming Model vs. Hardware Reality

LevelProgramming Abstraction (Correctness)Hardware Mechanism (Performance)
GridIndependent thread blocksWave quantization across 148 SMs (B200)
HBMFlat global address space128-byte coalesced cache-line transactions
Thread BlockShared scratchpad + barrier sync32 shared-memory banks (4 B wide) & swizzling
Warp / ThreadSIMT threads with private state32-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 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)

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

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)

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

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)

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

Correctness Testing: Numerical Accuracy & Batch Invariance

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

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)

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)

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

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 ReadsHBM 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)

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)

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}$:

ApproachHBM ReadsHBM WritesArithmetic IntensityFeasible?
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

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.

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))

Lecture Recap