Inferensys

Glossary

Fusion Heuristics

Fusion heuristics are rule-based or cost-model-driven algorithms used by compilers to decide which sets of neural network operators are profitable to fuse for optimal performance.
ML engineer working on model compression and quantization, laptop showing performance benchmarks, technical workspace.
INFERENCE OPTIMIZATION

What is Fusion Heuristics?

Fusion heuristics are the decision-making algorithms used by compilers to determine which neural network operators should be combined into a single, optimized kernel.

Fusion heuristics are rule-based or cost-model-driven algorithms used by compilers—such as XLA, TVM, or MLIR—to decide which sets of operators are profitable to fuse. This decision is based on analyzing the computational graph for factors like data dependency, memory access patterns, operation type, and the target hardware's characteristics. The primary goal is to reduce kernel launch overhead and improve data locality by minimizing intermediate memory transfers.

A cost model for fusion is central to these heuristics, estimating the performance impact of merging a fusion group. The analysis weighs the benefits of reduced data movement against potential downsides like increased register pressure or reduced parallelism. This enables optimizations like fused Conv-BN-ReLU or FlashAttention, transforming a sequence of operations into one efficient fused kernel for significant latency and throughput gains during model inference.

FUSION HEURISTICS

Key Factors in Fusion Decisions

Fusion heuristics are rule-based or cost-model-driven algorithms used by compilers to decide which sets of operators are profitable to fuse. This decision is based on a multi-dimensional analysis of computational characteristics.

01

Data Dependency and Graph Topology

The primary constraint for fusion is the dataflow graph. Heuristics analyze producer-consumer relationships to identify valid fusion groups.

  • Vertical Fusion: Merges sequentially dependent operators (e.g., a Convolution followed by BatchNorm).
  • Horizontal Fusion: Merges independent operators that share a common input or operate in parallel.
  • Fusion Group Discovery: Algorithms traverse the graph to find connected subgraphs where intermediate tensors are only consumed within the group, making them candidates for elimination.
02

Memory Access Patterns & Locality

A core goal of fusion is to reduce memory bandwidth pressure. Heuristics evaluate the memory-bound vs. compute-bound nature of operations.

  • Fusion for Cache: Prefers fusing operations where intermediate results can stay in fast cache (L1, shared memory), avoiding costly trips to global GPU memory.
  • Kernel Launch Overhead: Combining ops amortizes the fixed cost of launching a GPU kernel.
  • Elementwise Ops: Operations like ReLU or Add are ideal fusion targets as they are memory-intensive; fusing them with a compute-heavy op (like a MatMul) hides their memory latency.
03

Operation Type and Arithmetic Intensity

Heuristics classify operators by their computational profile to balance the fused kernel's workload.

  • Compute-Bound Operations: Dense matrix multiplications (MatMul, Conv) have high arithmetic intensity. Fusing lighter ops with them improves overall utilization.
  • Memory-Bound Operations: Pointwise activations (Sigmoid, Tanh) and reductions are limited by memory speed. They benefit greatly from fusion.
  • Canonical Patterns: Compilers use pattern matching to recognize and fuse known profitable sequences like Conv-BN-ReLU or Linear-GELU automatically.
04

Hardware-Specific Constraints & Cost Models

Profitability is hardware-dependent. Heuristics use a cost model to estimate execution time on the target accelerator (e.g., NVIDIA GPU, Google TPU).

  • Register Pressure: Fusing too many ops can exceed the GPU's register file, causing register spilling to slower memory and degrading performance.
  • Thread Block Scheduling: The fused kernel must efficiently map to the GPU's execution units (SMs).
  • Compiler Backends: Heuristics differ between XLA, TVM, and torch.compile's Inductor, as each has unique optimization passes and hardware targets.
05

Fusion Profitability Analysis

The final decision is a trade-off analysis. A fusion planner evaluates potential groups against a cost model.

  • Benefit: Reduced global memory accesses, lower launch overhead, improved cache locality.
  • Cost: Potential for increased register usage, reduced parallelism, and more complex kernel code.
  • Search Space: For complex graphs, the planner may explore multiple fusion plans to find a near-optimal solution, as exhaustive search is often intractable.
06

Static (AOT) vs. Dynamic (JIT) Fusion

The timing of the fusion decision introduces different heuristic considerations.

  • Ahead-of-Time (AOT) Fusion: Performed during compilation (e.g., with XLA). Heuristics can be more aggressive, using known tensor shapes and a comprehensive graph view.
  • Just-In-Time (JIT) Fusion: Performed at runtime (e.g., PyTorch's torch.compile). Heuristics must be faster and can adapt to dynamic shapes, but have less context for global optimization.
  • CUDA Graphs: Represent a launch-time fusion heuristic, capturing a sequence of kernels into a single, replayable unit to eliminate CPU launch overhead.
COMPILER OPTIMIZATION

How Fusion Heuristics Work

Fusion heuristics are the decision-making algorithms within a compiler that determine which operators to combine into a single kernel for optimal performance.

Fusion heuristics are rule-based or cost-model-driven algorithms used by compilers to decide which sets of operators are profitable to fuse. They analyze the computational graph for factors like data dependency, memory access patterns, and operation type. The primary goal is to construct a fusion plan that minimizes kernel launch overhead and maximizes data locality, directly reducing inference latency. This analysis is fundamental to compilers like XLA, TVM, and MLIR.

A cost model for fusion predicts the performance impact of merging a specific fusion group, weighing benefits like reduced global memory traffic against potential downsides like increased register pressure. Heuristics evaluate fusion profitability by comparing estimated execution cycles of fused versus unfused paths. Common strategies include vertical fusion of dependent ops and horizontal fusion of parallel ops. The resulting fused kernel, such as Fused Conv-BN-ReLU, executes multiple primitive operations in one GPU launch.

FUSION HEURISTICS

Implementation in Major Compilers

Fusion heuristics are the decision-making engines within compilers that determine which groups of operators are profitable to combine. This section examines how major deep learning compilers implement these critical algorithms.

01

XLA's Greedy Fusion Algorithm

Google's Accelerated Linear Algebra (XLA) compiler employs a greedy, producer-consumer fusion strategy. It traverses the HLO (High-Level Optimizer) graph in reverse post-order, prioritizing the fusion of operations that:

  • Are elementwise, broadcast, or reduction operations.
  • Have a producer-consumer data dependency.
  • Will not create a cycle in the fused computation graph. Its primary heuristic is to fuse to create larger, more complex operations that can be efficiently lowered to a single LLVM IR kernel, aggressively minimizing intermediate tensor materialization.
02

TVM's Auto-Scheduling & Sketch-Based Fusion

Apache TVM uses a cost-model-driven approach via its Ansor auto-scheduler. Instead of hardcoded patterns, it:

  • Generates fusion sketches as high-level loop structures for potential fused subgraphs.
  • Samples promising programs by applying transformations like loop tiling and vectorization.
  • Measures actual hardware performance on the target device to build a dataset.
  • Trains a ML-based cost model to predict the runtime of unseen programs, guiding the search for the optimal fused kernel schedule. This makes it highly adaptive to new hardware.
03

MLIR's Declarative Fusion via Linalg Dialect

The Multi-Level Intermediate Representation (MLIR) enables fusion through its Linalg dialect, which represents operations declaratively using indexing maps. Key heuristics include:

  • Tile and fuse loop transformations that reorder tiling and fusion steps to maximize data locality.
  • Use of the Affine dialect to analyze loop nests for fusion legality (no negative distance dependencies).
  • Pattern rewriting rules (e.g., linalg.fuse) that merge operations based on their iterator types (parallel, reduction). This provides a structured, multi-level framework for fusion that is easier to reason about and customize than graph-level approaches.
04

PyTorch Inductor's Pattern Matcher & Kernel Fusion

PyTorch's torch.compile backend, Inductor, performs fusion in two primary phases:

  1. Graph-Level Fusion: Uses a pattern matcher on the FX graph to identify and replace subgraphs (e.g., sigmoid + mul -> silu) with single, predefined Composite Automatic Registration (CARD) kernels.
  2. Loop-Level Fusion: In the subsequent triton or C++ codegen phase, it applies horizontal fusion heuristics to merge independent pointwise operations that share the same loop iteration space into a single kernel, reducing global memory accesses. Its heuristics are tuned for dynamic Python graphs.
05

TensorRT's Layer & Plugin Fusion

NVIDIA's TensorRT applies fusion during the network optimization phase. Its heuristics are highly specialized for NVIDIA GPUs and involve:

  • Vertical fusion of adjacent layers (e.g., Convolution + Bias + ReLU) into a single CUDNN or CUBLAS call.
  • Horizontal fusion of operations that can be executed in a single kernel to improve occupancy.
  • Automatic precision layer fusion, where it may fuse operations before and after a precision conversion (e.g., FP16 -> FP32).
  • Heavy use of hand-written, optimized kernel libraries (cuDNN, cuBLAS) for fused patterns, making its heuristics a blend of pattern matching and library dispatch.
06

Common Heuristic Factors & Cost Models

Across compilers, fusion decisions are guided by a common set of profitability factors evaluated by a cost model:

  • Data Locality: Will fusion keep intermediate tensors in registers or shared memory, avoiding costly DRAM trips?
  • Kernel Launch Overhead: How many synchronization points and kernel launches are eliminated?
  • Arithmetic Intensity: Does fusion increase the compute-to-memory-access ratio?
  • Parallelism Constraints: Does fusion create a sequential bottleneck or reduce occupancy by increasing register pressure?
  • Operator Type: Is the pattern elementwise (highly fusible), a reduction, or a complex operation (e.g., convolution)? The cost model estimates speedup, often using roofline model analysis, to accept or reject a fusion candidate.
DECISION METHODOLOGY

Types of Fusion Heuristics

Comparison of the primary algorithmic approaches used by compilers to determine which operators to fuse for optimal performance.

Heuristic TypeRule-BasedCost-Model-DrivenHybrid (Rule + Cost)

Decision Logic

Pre-defined patterns and static rules

Dynamic performance estimation via a predictive model

Rules for initial candidate selection, cost model for final decision

Primary Inputs

Operator type, data dependency graph

Tensor shapes, memory bandwidth, compute throughput estimates

Both rule-based and cost-model inputs

Optimization Goal

Minimize intermediate memory transfers

Maximize predicted speedup (latency/throughput)

Balance compile-time speed with performance gain

Compile-Time Overhead

< 1 ms per fusion group

10-100 ms per fusion group (model evaluation)

5-50 ms per fusion group

Adaptability to Hardware

Handles Novel Operators

Typical Use Case

Ahead-of-Time (AOT) compilation for known models

Just-in-Time (JIT) compilation for dynamic graphs

Production compilers (e.g., XLA, TVM, torch.compile)

Key Limitation

Cannot optimize for unseen patterns or data shapes

Cost model inaccuracy can lead to suboptimal fusions

Increased implementation and maintenance complexity

FUSION HEURISTICS

Frequently Asked Questions

Fusion heuristics are the decision-making algorithms within a compiler that determine which operators to combine into a single, optimized kernel. This FAQ addresses how these heuristics work, their impact on performance, and their implementation in modern ML compilers.

Fusion heuristics are rule-based or cost-model-driven algorithms used by compilers to decide which sets of operators in a computational graph are profitable to fuse into a single kernel. They work by analyzing the graph structure and estimating the performance impact of potential fusions. Key factors considered include:

  • Data dependency and producer-consumer relationships.
  • Memory access patterns and the potential for improved data locality.
  • Operation type (e.g., elementwise, reduction) and their combined arithmetic intensity.
  • Hardware-specific constraints like register pressure and shared memory usage. The heuristics apply a cost model to score candidate fusion groups, selecting those with the highest predicted performance gain while avoiding fusions that could cause resource exhaustion or inhibit parallelism.
Prasad Kumkar

About the author

Prasad Kumkar

CEO & MD, Inference Systems

Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.

His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.