Precision Speed: 14 Techniques for High-Performance ML Inference
“In the world of high-scale inference, 100 milliseconds isn’t just a delay; it’s a cost center. When serving millions of users, every nanosecond shaved off a kernel launch translates directly into throughput, compute efficiency, and bottom-line savings.”
TL;DR
Real ML inference speedups come from mastering 14 techniques at the hardware-software boundary. Fused attention kernels keep computation in fast SRAM instead of slow HBM, with FlashAttention-3 reaching close to 1.2 PFLOPs/s in FP8 on Hopper GPUs. CUDA graphs eliminate CPU overhead by recording the entire computation as a static graph. PagedAttention manages KV cache like virtual memory with dynamic block allocation. Speculative decoding uses a small drafter model to predict multiple tokens verified in a single pass, typically cutting decode latency 2-3x at small batch sizes. Tensor parallelism handles intra-node sharding over NVLink, while pipeline parallelism splits layers across nodes. For the systems that deploy these techniques at scale, see the chatbot system design and the open models retrospective covering the architectures being served.

1. Introduction: The Billion-Dollar Latency Problem
The field of Machine Learning System Design has shifted. We are no longer in an era where “just adding more GPUs” is a viable scaling strategy. The modern challenge is Inference Efficiency. While many talk about quantization or pruning, those are often just the first steps. Real speedups, the kind that allow a startup to compete with giants or a giant to reduce its burn by millions, come from a deep understanding of the hardware-software boundary.
This guide is a deep dive into the 14 techniques that actually move the needle. We are moving past the high-level abstractions and into the world of fused kernels, CUDA graphs, and memory-aligned tensors. If you want to build systems that handle the demands of 2026, these are the concepts you must master.
2. Kernel-Level Mastery: The Front Lines of Speed
2.1 Fused Attention Kernels
Standard attention implementations calculate Q, K and V, then perform a series of operations: Softmax, Dropout, and Weighted Sum. Each of these typically involves a separate kernel launch and a trip back to Global Memory (HBM).
Architecture Diagram: Fused vs. Unfused Execution
[ UNFUSED ATTENTION ] [ FUSED ATTENTION (Flash) ]
| |
+-----+-----+ (Launch 1) +-----+-----+
| Q*K.T | ----> [HBM] | Load Q,K |
+-----+-----+ | Compute |
| | Softmax | (On-SRAM)
+-----+-----+ (Launch 2) | Update V |
| Softmax | ----> [HBM] +-----+-----+
+-----+-----+ |
| [ Final Out ]
+-----+-----+ (Launch 3)
| Output |
+-----+-----+
- Technique: Combining multiple mathematical operations into a single GPU kernel.
- Why it works: It minimizes the “Memory Wall” bottleneck. By keeping intermediate results in fast SRAM (L1/Shared Memory) instead of writing them back to slow HBM, you reduce data movement significantly.
- Deep Dive: In a fused kernel, the entire attention mechanism for a small “tile” of the matrices is performed by a single thread block. The threads use Warp-Level Primitives (like
__shfl_sync) to communicate and perform reductions without ever hitting the L2 cache. This allows the model to compute attention in a single pass over the data.
2.2 FlashAttention Variants (v1, v2, v3)
FlashAttention isn’t just a kernel; it’s a re-imagining of how attention is calculated.
- FlashAttention-1: Introduced Tiling and Recomputation. By computing the attention scores and the weighted sum tile by tile with an online softmax, it never materializes the N×N score matrix, so memory grows linearly with sequence length instead of O(N²).
- FlashAttention-2: Optimized for parallelism across the sequence length and query heads. It redistributed the work across SMs and optimized the “Online Softmax” update, reducing the non-compute instruction overhead.
- FlashAttention-3: Designed for NVIDIA Hopper (H100). It utilizes the TMA (Tensor Memory Accelerator), a hardware block that moves tensors between HBM and Shared Memory asynchronously. By overlapping the Producer (TMA) and Consumer (Tensor Cores) warps, it achieves up to 740 TFLOPs/s in FP16 (about 75% of H100 peak). Using FP8, it reaches close to 1.2 PFLOPs/s (Shah et al., 2024).
2.3 RoPE Kernel Optimizations
Rotary Positional Embeddings (RoPE) are applied to Q and K before every attention call, so a naive implementation adds a kernel launch and an HBM round trip per layer.
- Technique: Sin/Cos Pre-computation. Instead of calculating sines and cosines on the fly, pre-calculate the rotation values for all positions up to the maximum context once and keep them in a cached lookup table.
- Fusion: Some attention libraries (FlashInfer, for example) apply the rotation inside the attention kernel as Q and K are loaded into registers. The rotation is cheap arithmetic hidden under memory loads, so fusing it mostly saves the separate kernel and its extra read and write of Q and K.
3. High-Performance Execution & Graph Optimization
3.1 CUDA Graph Capture: Masterclass
The standard PyTorch execution model is “Eager Mode.” Every operation is a separate kernel launch issued by the CPU through the driver. Launches are asynchronous, but each still costs a few microseconds of CPU and driver time. For a model with 80 layers and 5-6 operations per layer, that is hundreds of launches per token, and at small decode batch sizes the GPU can finish each kernel faster than the CPU issues the next one.
Architecture Diagram: CUDA Graph Capture
[ EAGER MODE ] [ CUDA GRAPH MODE ]
(CPU) (GPU) (CPU) (GPU)
|--Launch 1--> | [Step 1] | |
|--Launch 2--> | [Step 2] |--Launch--> | (Entire Graph)
|--Launch 3--> | [Step 3] | | [Step 1]
| ... | (idle gaps between | | [Step 2]
| | launches) | | [Step 3]
- Technique: Record a “Static Graph.”
- Why it works: The CPU is removed from the inner loop. The whole sequence of kernels, with fixed memory addresses and dependencies, is replayed with a single launch.
- Restriction: Static graphs require static tensor shapes. This is why inference engines pad to pre-defined sizes. vLLM, for example, captures graphs for a set of decode batch sizes and pads each batch up to the nearest captured size.
3.2 Operator Fusion (Vertical & Horizontal)
- Horizontal Fusion: Independent operations on the same input can share one kernel. The classic example is concatenating the Q, K and V projection weights so one GEMM produces all three instead of three separate launches.
- Vertical Fusion: When you have a
Bias Addfollowed by aGELUactivation, merge them into the output phase of the precedingLinearlayer kernel. - Impact: Reductions in kernel launch overhead and intermediate memory reads.
4. The Decode-Stage Architecture: Memory-Bound Reality
In LLM inference, the “Prefill” stage (processing input) is compute-bound, but the “Decode” stage (generating tokens one by one) is memory-bound.
4.1 PagedAttention: Internals of memory management
The KV-cache is the largest memory consumer in serving.
- Fragmented Memory Problem: In standard systems, you must pre-allocate memory for the maximum possible sequence length. A request requiring 17 tokens would waste 2031 tokens worth of VRAM in a 2048-token context.
- The PagedAttention Solution: Split the KV-cache into “Physical Blocks.” The default Block Size is 16 tokens. This allows dynamic allocation and non-contiguous storage.
- Tuning: Smaller blocks waste less memory at the tail of each sequence; larger blocks mean shorter block tables and longer contiguous reads. Some kernels fix the size for you (DeepSeek’s FlashMLA uses 64-token pages). Benchmark your own workload before changing the default.
- Copy-on-Write: This also allows for efficient Prefix Sharing. Multiple requests sharing a system prompt can point to the same physical memory blocks, enabling massive fan-out at minimal memory cost.
4.2 Persistent Kernels for Decode
A 70B model has 80 layers, each launching several kernels, so one decode step means hundreds of launches.
- Technique: A Persistent Kernel is launched once. It stays on the GPU and “polls” a memory flag to know when the next token is ready.
- Advantage: It bypasses the driver’s kernel launch logic entirely, reducing the gap between token generations to the speed of the hardware itself.
4.3 Speculative Decoding: The Algorithmic Speedup
Instead of predicting one token with a 70B model, we predict 5 tokens with a 1B “Drafter” model and verify them in a single pass with the 70B “Verifier.”
Architecture Diagram: Speculative Decoding Timeline
[ TIME T1 ] Drafter: "The", "cat", "sat", "in" (High Speed)
[ TIME T2 ] Verifier: Check all 4.
Result: [OK, OK, OK, FAIL]
Token 4 rejected. Verifier samples its own token: "on".
[ OUTPUT ] "The cat sat on" (4 tokens from one verifier pass)
- The Math of Speculation: At small batch sizes, decode is memory-bound, so verifying 5 tokens costs only marginally more than generating 1: the weights are read once for all 5 positions. As the batch grows and the GPU becomes compute-bound, that advantage shrinks. Newer variants (EAGLE-3, Saguaro, Nightjar) are covered in speculative decoding in 2026.
5. Memory & Hardware Alignment
5.1 Memory-Aligned Tensors
GPUs are most efficient when accessing memory in 128-byte or 256-byte aligned chunks.
- Technique: Pad your tensor dimensions to be multiples of 8 or 16. For example, if your head size is 120, pad it to 128.
- Impact: Enables Coalesced Memory Access, where multiple threads in a warp can be served by a single memory transaction, and lets Tensor Core kernels use their fastest tile shapes. Misaligned shapes can fall back to slower code paths.
5.2 Custom Sampling Kernels (Logits to Tokens)
The last step of any LLM is selecting the next token. A naive implementation sorts the full vocabulary (100K+ entries) for every sequence at every step before applying top-k or top-p.
- Technique: Use a sampling kernel that avoids the full sort. FlashInfer’s sampling kernels, for example, use rejection sampling to draw top-k/top-p samples without sorting the logits, and serving engines such as vLLM can use them.
6. Distributed Parallelism: Scaling to the Cluster
6.1 Tensor Parallelism (TP)
Splitting a single matrix multiplication across multiple GPUs (Megatron-LM style).
- Mechanism: Each GPU holds a slice of every weight matrix and computes a partial result. The GPUs combine partial results with an
AllReduce(twice per Transformer layer in the Megatron layout). - Interconnect Factor: This is strictly designed for intra-node sharding. It requires the high bandwidth of NVLink (300GB/s - 1.8TB/s) or NVSwitch. Attempting TP over standard Ethernet or even InfiniBand (200-400Gbps) will cause communication latency to dwarf the compute gains.
6.2 Pipeline Parallelism (PP)
Splitting layers across GPUs (Layers 0-10 on GPU 1, 11-21 on GPU 2).
- Optimization: In training, the 1F1B (One-Forward, One-Backward) schedule keeps memory bounded. Inference has no backward pass, but the same fill-and-drain bubble applies when micro-batches flow through the stages.
- Bubble Formula: With M micro-batches and S pipeline stages, pipeline efficiency is roughly:
To keep the “Bubble” (idle time) small, keep M much larger than S.
7. Compiler & Logic Optimization
7.1 Triton: Beyond the DSL
Triton allows you to write C-like kernels in Python.
- L2 Cache Swizzling: Triton handles the memory hierarchy inside a block for you, and the order in which blocks run is yours to choose. The Triton matmul tutorial remaps program IDs into “grouped” order so neighboring blocks reuse the same tiles from L2, reducing trips to HBM.
7.2 Memory-Efficient Tensors (FP8 & BF16)
The transition from BF16 to FP8 (on Hopper/Blackwell) doubles the peak Tensor Core throughput.
- Block-wise Scaling: Using a separate scale factor for each small block of values preserves precision during 8-bit quantization. DeepSeek-V3 trains with 128×128 blocks for weights and 1×128 tiles for activations; the MXFP8 format supported on Blackwell uses one shared scale per 32 elements. For which quantization method to pick on which hardware, see the quantization decision tree.
8. Illustrative design: a large-scale chat service
Here is how these techniques could combine in a hypothetical service built for very high concurrency. The numbers are worked examples, not measurements.
- Orchestration: A global load balancer directs traffic to regional clusters of 8-GPU nodes.
- Model Layout: Within a node, we use Tensor Parallelism (TP=8) over NVLink to minimize latency for a Llama-3 70B model.
- Memory Management: PagedAttention is configured with a block size of 16, and the shared system prompt is stored once through prefix sharing. Llama-3-70B keeps about 0.31 MiB of KV cache per token in FP16 (2 for K and V × 80 layers × 8 KV heads × 128 head dim × 2 bytes). With a 1,000-token system prompt and 128 concurrent sequences on a node, sharing saves about 127 × 1,000 × 0.31 MiB ≈ 39 GiB.
- Inference Pass:
- Prefill: Uses FlashAttention-3 to process the system prompt and history.
- Decode: Swaps to a Persistent Decode Kernel.
- Algorithmic Speedup: Speculative Decoding with a 1B Llama-distilled drafter, enabled at low load and turned down as batches grow.
- Synchronization: CUDA Graphs are captured for a set of decode batch sizes, removing per-kernel launch overhead from every decode step.
9. Summary Checklist: The Mastery Roadmap
If you are auditing an inference system for speed, check these 14 points:
- Are attention kernels fused (FlashAttention-3)?
- Is CUDA Graph Capture enabled for fixed-length buckets?
- Are small successive layers vertically fused?
- Is the kernel launch overhead masked by graphs or streams?
- Is Tensor Parallelism restricted to NVLink domains?
- Is Pipeline Parallelism utilizing optimal micro-batches?
- Are the decode-step kernels persistent?
- Is Speculative Decoding enabled for large models?
- Are Sin/Cos RoPE factors pre-computed (and fused into attention where supported)?
- Is the KV-cache managed via PagedAttention?
- Are sampling kernels running on-GPU in a single pass?
- Are all tensors memory-aligned to 128-byte boundaries?
- Is kernel launch priority set to High for user requests?
- Are you utilizing Triton for custom activation layers?
10. Conclusion: The Engineering of the Invisible
Speed in ML systems is rarely about a single “magic bullet.” It is about a relentless focus on data movement and hardware utilization. When you master these 14 techniques, you aren’t just making a model faster; you are changing the economics of AI. You are moving from a world where your infrastructure dictates your capabilities to a world where your engineering dictates your competitive advantage.
The fastest model is the one that never waits for memory.
FAQ
What are fused attention kernels and why do they improve ML inference speed?
Fused kernels combine multiple operations like the QK matrix multiply, softmax normalization, and weighted sum into a single GPU kernel. This keeps intermediate results in fast SRAM (L1/Shared Memory) instead of writing them back to slow HBM global memory. Thread blocks use warp-level primitives for communication without hitting the L2 cache, dramatically reducing the memory wall bottleneck that dominates inference latency.
How do CUDA graphs speed up LLM inference?
CUDA graphs record the entire model computation as a static graph that the GPU replays without per-kernel CPU launches. In eager mode, each of the hundreds of operations per token is a separate asynchronous launch that costs CPU and driver time, and at small batch sizes the GPU often waits on the CPU. With graphs, a single launch triggers the entire pre-recorded sequence. The tradeoff is that shapes must be static, so engines capture graphs for a set of batch sizes and pad to the nearest one.
What is the difference between FlashAttention versions 1, 2, and 3?
FlashAttention-1 introduced tiling and recomputation to avoid O(N-squared) memory for attention. FlashAttention-2 optimized parallelism across sequence length and query heads with improved online softmax updates. FlashAttention-3 exploits NVIDIA Hopper hardware features like the Tensor Memory Accelerator for asynchronous data movement, overlapping producer and consumer warps to achieve up to 740 TFLOPs/s in FP16 and close to 1.2 PFLOPs/s in FP8.
How does speculative decoding achieve faster LLM token generation?
A small 1B drafter model predicts several tokens quickly, then the large model verifies all of them in a single parallel forward pass. At small batch sizes the cost of verifying 5 tokens is only marginally higher than generating 1 token (the weights are read once for all drafted positions), so each accepted draft saves a full generation round-trip. Typical decode speedups are 2-3x at batch size 1, shrinking as batches grow, and rejection sampling keeps the output distribution identical to the target model’s.