ELLMEngineering Large
Language Models
Download PDF

Chapter 35

Kernel Engineering, Profiling, and Correctness

On this page

Kernel work is complete only when the optimization is reproducible across representative shapes, numerically valid, integrated into the application, and understandable from evidence.

The preceding sections built a schedule for the running example's layer and decode step. This final section is how you defend that schedule: benchmarks that match the claim, profiler hypotheses tied to resources, and correctness layers that catch the shapes serving actually produces.

A numerical teaching roofline with 1 TB/s memory bandwidth and a 100 TFLOP/s arithmetic ceiling. The knee is at 100 FLOP/byte. The highlighted point lies on a theoretical ceiling, not a measured kernel result; actual throughput can be lower.
Open full diagram ↗

A numerical teaching roofline with 1 TB/s memory bandwidth and a 100 TFLOP/s arithmetic ceiling. The knee is at 100 FLOP/byte. The highlighted point lies on a theoretical ceiling, not a measured kernel result; actual throughput can be lower.

Build a trustworthy benchmark

Specify:

  • device, architecture, clocks or power mode, toolkit, driver, and compiler flags;
  • input shapes and their production frequency;
  • dtype, layout, alignment, sparsity, and value distribution;
  • warmup, iteration count, synchronization boundary, and cache policy;
  • reference implementation and numerical tolerance;
  • whether allocation, transfer, launch, and framework dispatch are included.

For this part's running example, a minimum matrix includes prefill [B=1, S=2048] attention and GEMM shapes, decode [B=8, S=4096] paged attention, and the corresponding linear layers at D=4096. Random inputs can hide value-dependent behavior such as histogram contention, sparsity, overflow, or early exit. Include adversarial and production-derived distributions.

Cold, warm, and steady-state claims

Cold latency may include CUDA context initialization, module load, JIT compilation, graph instantiation, allocation, and cache miss. Warm latency may assume all of these are complete. Both are legitimate if labeled.

For interactive systems, report p50 and tail distributions over the real request mix. Median kernel time alone does not predict queueing or graph-cache miss.

Roofline analysis

Arithmetic intensity is useful operations divided by bytes moved across a chosen boundary. The simple roofline bound is:

2026-10-12T12:02:55.916937 image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/

Choose the correct work units and peak. Tensor-core FLOPs, scalar FP32 FLOPs, integer operations, and special functions have different ceilings. Choose the correct bytes: requested HBM bytes, measured HBM traffic, or cache-level traffic.

A hierarchical roofline adds L1 and L2 ceilings. A kernel may sit below the HBM roof because it is actually limited by L1 bandwidth, shared-memory conflicts, instruction issue, or dependency latency.

Place the running example on that roof deliberately: decode linear layers and paged attention belong near the bandwidth side; large prefill GEMMs and well-tiled FlashAttention can approach the compute side. If a decode kernel claims compute-bound behavior, demand the intensity calculation.

Completed accelerator experiment: resident RMSNorm on Apple MPS

The repository now includes one executed accelerator comparison, examples/accelerators/mps_rmsnorm.py. It compares a tensor-expression RMSNorm with PyTorch's framework operator on Apple MPS using FP32 resident tensors, epsilon 1e-6, ten warmups, and thirty synchronized repetitions per shape. A separate FP64 CPU expression supplies forward and backward references. Both paths pass at absolute and relative tolerance 2e-5 on the tested random inputs.

Shape / layout Expression warm median Framework warm median Maximum forward error across the two paths
1 × 127, contiguous 0.221 ms 0.133 ms 2.06e-7
64 × 4096, contiguous 0.390 ms 0.148 ms 1.68e-6
64 × 4097, contiguous 0.401 ms 0.146 ms 1.83e-6
16 × 127, stride two 0.210 ms 0.157 ms 7.45e-7

These are one local run's measurements, including dispatch and completion synchronization but excluding host/device copies. First-call times, ranges, errors, software versions, and device identification are in the experiment record. First calls occur in one process and can share runtime initialization; they are not isolated cold-start comparisons. Differences should be remeasured with randomized order and repeated runs before a deployment decision.

The framework path wins on these shapes, so this experiment gives no reason to maintain the longer expression as an optimization. It does not prove which underlying kernel or fusion explains the difference. A device timeline is the next diagnostic instrument; the CPU reference and wall-clock timings do not identify the internal schedule. No CUDA, HIP, Triton, Blackwell, or multi-GPU performance result is inferred from MPS.

This evidence is deliberately narrower than a custom-kernel acceptance report. The CUDA excerpts still need compilation, sanitizer checks, edge-shape runs, and profiler evidence on their target. Keep those cells unmeasured rather than treating an unrelated accelerator result as a substitute.

A compiled Metal baseline and its rejection

examples/accelerators/metal_rmsnorm.py completes a small custom-kernel investigation on the available Apple MPS device. PyTorch 2.8 compiles the Metal source at runtime. One GPU thread owns a row, accumulates its squared values in FP32, computes the inverse RMS with epsilon 1e-6, and writes that row's weighted output. Input row/column strides are explicit; output is contiguous. Different rows own disjoint output addresses. This is a deliberately simple serial reduction within each row, not a parallel reduction optimized for the device.

The kernel and PyTorch baseline both passed comparison with an independent FP64 CPU expression for zero, 1e-7, unit-scale and 1e4 inputs across four shapes, including width 4097 and a stride-two view. All 32 operator/shape/stress checks passed with atol=rtol=3e-5. This tolerance and finite FP32 range define the numerical claim; no FP16, backward or arbitrary-overflow guarantee is inferred.

Shape and input stride Custom Metal, ms PyTorch RMSNorm, ms
1 x 127, contiguous 0.206 0.139
64 x 4096, contiguous 1.029 0.133
64 x 4097, contiguous 1.660 0.139
16 x 127, stride two 0.167 0.124

These are medians of three block medians, with thirty synchronized measurements per candidate per block. Candidate order is randomized within each block. Inputs and weights are resident; output allocation, dispatch and synchronization are included. Compilation took about 36.5 ms separately. The three blocks share one process and device session, so they are not independent machine-day replications. The raw JSON retains all samples rather than only the winning minimum.

The host profiler on the stride-two case records PyTorch's contiguous-copy path and fused operator. It records the custom output allocation but does not expose the shader's device instruction timeline. Consequently the trace establishes host operations, not occupancy, achieved bandwidth or a complete account of device time. The source shows serial column accumulation, and the larger-width slowdown is consistent with that schedule, but a device trace would be needed to attribute the entire gap to it.

The decision is to reject this custom dispatch on all four tested shapes. Even avoiding the framework's strided-input copy did not repay the slower custom execution. A next candidate would distribute each row across a reduction group and preserve its ownership/synchronization contract. It would then repeat these same stress and timing checks. Metal execution does not validate the separate CUDA excerpts; CUDA sanitizer output and Blackwell device profiling remain target-specific exercises rather than completed evidence.

Interpret profiler evidence at its actual boundary

A disciplined Nsight Compute investigation asks:

  1. Is the kernel compute-, bandwidth-, latency-, or synchronization-limited?
  2. Is achieved occupancy different from theoretical occupancy?
  3. Are there enough eligible warps per scheduler?
  4. Which stall reasons are large, and which instructions create them?
  5. Are global and shared transactions efficient?
  6. Are tensor-core, scalar, load/store, and special-function pipes balanced?
  7. Is the tail caused by grid size or per-block imbalance?

Do not optimize a counter in isolation. A higher cache hit rate can hurt if obtaining it adds instructions or reduces occupancy. A lower stall percentage can mean the denominator changed.

Read generated code

Compiler reports show registers, shared memory, and spills. SASS or disassembly confirms vectorization, tensor-core instructions, local-memory traffic, and unexpected conversions. Source code expresses intent; generated instructions determine the schedule.

Inspect generated code after large performance changes, unexpected register cliffs, or architecture/compiler upgrades. Avoid hand-tuning assembly before proving the compiler path is the bottleneck.

Correctness layers

  1. Semantic reference: compare with a simple CPU or high-level implementation.
  2. Shape coverage: zero, singleton, odd, prime, aligned, maximum, ragged, and empty slices.
  3. Value coverage: zeros, infinities where valid, NaNs, extreme magnitude, repeated keys, adversarial masks.
  4. Concurrency: run with multiple streams, cancellation, reused buffers, and sanitizer tools.
  5. Numerical analysis: absolute/relative error, ULP where useful, distributional error, and model-level quality.
  6. Gradient checks: finite difference on tiny cases plus reference backward.
  7. Determinism: define and test the promised level.

Serving kernels add cases that dense unit tests miss: partially filled final pages, GQA head mapping, sequence packing boundaries, and graph replay with reused device addresses.

Tolerances

Use a combined test such as:

2026-10-12T12:02:55.929553 image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/

Choose tolerances from dtype, operation count, accumulation, and downstream sensitivity. One global tolerance can hide large error near zero or reject harmless scale-proportional error.

For softmax and probabilities, check normalization and KL or output behavior in addition to elementwise error. For top-k, ties require a declared ordering. For quantization, test task quality and long-context behavior.

Race and memory checking

Run compute-sanitizer modes appropriate to memory access, race, initialization, and synchronization. Debug variants may reduce optimization or alter timing, so sanitizer success complements rather than replaces stress tests.

Add canaries around buffers and test noncontiguous strides. Many kernels are correct for dense tensors and silently wrong when framework views carry a different stride.

Make the hardware acceptance gate reproducible

Use three separate failure boundaries: compilation for the selected architecture, immediate launch-error checking, and completion checking on the stream that owns the operation. A successful launch API return does not prove that asynchronous execution succeeded. Run edge shapes before timing: widths 1, 31, 32, 33, and 4097; nonmultiples of block tiles; zero-sized inputs handled by the host; and the explicitly supported alignment and stride cases.

The Compute Sanitizer manual distinguishes memory-access checks, shared-memory race checks, initialization checks, and synchronization checks. Run memcheck first, then the applicable additional tools. A clean sanitizer run covers the tested paths; it neither proves numerical correctness nor establishes race freedom for every launch configuration.

For each accepted configuration, retain the compiler version, architecture flags, GPU identity, input generator seed, shape and stride tuple, reference dtype, absolute and relative error maxima, sanitizer results, and timing protocol. Inspect register use and spills for the same binary being timed. Report resident-device timings separately from transfers and cold compilation. The October 12 follow-up runs host algebra and CPU/Gloo tests; no CUDA or NCCL execution was available on that host.

Autotuning without overfitting

Tune over a declared shape distribution and cache the result by device, toolkit, dtype, layout, and semantic options. Separate a training set of shapes from a validation set to catch over-specialization.

Constrain the search space with resource models. Reject configurations that exceed register/shared limits or produce poor transaction geometry before benchmarking. Retain a safe general fallback.

Integration and regression

A faster kernel can make the application slower through conversion, layout changes, synchronization, graph misses, or loss of fusion elsewhere. Benchmark the operator boundary and the end-to-end model.

Maintain performance thresholds by shape family, not one absolute number. Hardware load and clocks vary; use robust baselines, confidence bands, and dedicated performance workers where possible.

Code review checklist

Area Review questions
Ownership Which block, warp, and lane owns each output and partial?
Memory Are addresses in bounds, aligned, coalesced, and correctly scoped?
Synchronization Does every participant reach barriers? Are masks accurate?
Resources What limits resident blocks? Are there spills or bank conflicts?
Numerics What rounds, accumulates, rescales, or becomes nondeterministic?
Shapes Which cases use specialized paths and which use fallback?
Integration Which streams, graphs, allocations, and layouts are assumed?
Evidence Which measurement proves the optimization helps end to end?

Design Exercises

  1. Design a benchmark that distinguishes launch-bound from bandwidth-bound behavior.
  2. A profiler reports low occupancy. What do you do next?
  3. How do you interpret a high long-scoreboard stall percentage?
  4. What belongs in a correctness suite for a fused attention kernel?
  5. How do you choose numerical tolerances?
  6. When should an autotuner create a specialized kernel variant?

Worked Solutions

1. Launch-bound versus bandwidth-bound

Sweep problem size and iteration count. Measure device event time for the kernel, an empty or minimal launch baseline, achieved memory bytes, and end-to-end submission. A launch-bound kernel has a relatively flat time floor and improves materially under graph capture or fusion. A bandwidth-bound kernel scales with bytes and approaches sustainable memory throughput; graph capture changes little once the workload is large.

2. Low occupancy

Calculate the resource limiter: threads, registers, shared memory, or block limit. Then inspect achieved eligible warps and stall reasons. If execution units are busy and latency is hidden, do nothing. If exposed stalls correlate with too few warps, test a smaller tile, shorter live ranges, fewer stages, or launch bounds, watching for lost reuse and spills. Optimize performance, not the occupancy percentage.

3. Long-scoreboard stalls

They commonly indicate waiting on long-latency memory dependencies, but the counter alone is not a diagnosis. Locate the load instructions, inspect coalescing and cache behavior, measure eligible warps, and check dependency chains. Possible fixes are improved locality, prefetch, independent loads, more resident warps, or a different data layout. A correctly HBM-bound kernel may legitimately retain these stalls.

4. Fused-attention correctness

Compare forward and backward with a high-precision reference across causal/noncausal, ragged, boundary, GQA/MQA, masked, and extreme-logit cases. Test fully masked-row policy, dropout mask reproducibility, noncontiguous layouts, gradients, multiple streams, and sanitizer results. Verify no cross-sequence access and test tolerance by dtype and head dimension.

5. Numerical tolerances

Start from input and accumulation dtypes, reduction length, operation conditioning, and expected rounding order. Use combined absolute and relative error, add invariant checks such as softmax sums, and examine worst-case plus distributional error. Tighten or loosen only with a documented numerical model and downstream quality evidence, not to make a failing test pass.

6. Specialization

Create a variant when a frequent shape or semantic mode has a materially different optimal schedule and the end-to-end gain exceeds compile, binary, memory, dispatch, and test costs. Bucket nearby shapes when padding is cheaper than another variant. Require a fallback and monitor traffic hit rate so dead variants can be removed.

Further Study and Primary References

Final CUDA Principle

Keep the kernel reference, edge-case tests, and profiles for the running prefill and decode shapes. The next chapter uses those artifacts to distinguish portable computations from schedules that must change on another accelerator.