Inferensys

Glossary

Fusion in TVM

Fusion in TVM is the process within the Apache TVM deep learning compiler where multiple computational operators are combined into a single, optimized kernel to minimize memory transfers and kernel launch overhead.
Stylish WeWork-like workspace with hot desks and document wall, professional searching through enterprise knowledge base on a mounted ultrawide display, warm industrial pendants overhead.
COMPILER OPTIMIZATION

What is Fusion in TVM?

Fusion in TVM is the core compiler optimization within the Apache TVM deep learning compiler that combines multiple low-level computational operators into a single, highly efficient kernel.

Fusion in TVM is the automated process of merging adjacent operators in a neural network's computational graph into unified kernels. This optimization, performed by TVM's graph-level optimizer and scheduling language (TensorIR), primarily aims to reduce kernel launch overhead and minimize costly intermediate memory transfers to global DRAM. The compiler identifies fusion groups based on data dependencies and applies fusion heuristics to determine profitable combinations.

TVM implements fusion through both ahead-of-time (AOT) and just-in-time (JIT) compilation paths. Its auto-scheduler (Ansor) can automatically generate high-performance fused kernels for novel operator patterns. Key targets include elementwise fusion (e.g., combining ReLU and Add) and canonical patterns like fused Conv-BN-ReLU. This reduces execution latency and improves arithmetic intensity, making it a foundational technique within the broader pillar of Inference Optimization and Latency Reduction.

ARCHITECTURE

Key Features of TVM's Fusion System

TVM's fusion system is a core optimization that transforms computational graphs into high-performance kernels. It operates through a multi-stage process combining graph-level pattern matching with low-level schedule generation.

01

Relay IR and Graph-Level Fusion

Fusion begins in TVM's high-level Relay Intermediate Representation (IR). The compiler performs graph-level pattern matching to identify subgraphs of operators that are profitable to combine. Common patterns like Conv2D + BatchNorm + ReLU are detected and replaced with a single, compound CallNode representing the fused operator. This high-level fusion reduces the number of operators passed to the low-level scheduler and defines the fusion boundaries.

02

Tensor Expression (TE) and Schedule Primitives

Each fused operator group is lowered to Tensor Expressions (TE), a domain-specific language for describing tensor computations. The key to TVM's flexibility is its scheduling primitives applied to these TEs:

  • compute_inline: Fuses a producer operation directly into the consumer's loop nest.
  • compute_at: Computes a producer tensor within a specific loop iteration of the consumer.
  • cache_read / cache_write: Explicitly manages data movement, creating fusion opportunities by keeping intermediate results in fast memory (e.g., shared memory on GPUs). These primitives give fine-grained control over loop fusion, tiling, and memory hierarchy mapping.
03

Auto-Scheduling (Ansor) for Fusion

TVM's Ansor auto-scheduler automatically generates high-performance schedules, including fusion decisions, without manual tuning. It:

  • Explores a search space of possible loop transformations, including various fusion strategies (e.g., inline, compute_at).
  • Uses a cost model to predict the performance of different fused kernel implementations.
  • Learns over time which fusion patterns are most effective for the target hardware (CPU/GPU). This automates the complex trade-off between reduced memory traffic (from fusion) and potential loss of parallelism.
04

Target-Specific Kernel Code Generation

After scheduling, TVM generates highly optimized, target-specific low-level code for the fused kernel. It leverages:

  • LLVM for CPUs and ARM architectures.
  • CUDA/NVPTX or ROCm for GPUs.
  • OpenCL for diverse accelerators. The code generator applies final low-level optimizations like vectorization and register allocation to the fused loop structure. The output is a minimal kernel launch overhead, as many primitive ops are executed within a single kernel.
05

Memory Coalescing and Data Locality

A primary benefit of TVM's fusion is optimized memory access patterns. By fusing operators:

  • Intermediate tensors are kept in registers or thread-local memory, eliminating costly writes and reads to global GPU memory (DRAM).
  • Memory accesses are coalesced across fused operations, improving bandwidth utilization.
  • Data reuse is maximized within cache hierarchies (L1/L2 on CPU, shared memory on GPU). This transforms memory-bound operations (like element-wise activations) into compute-bound kernels when fused with compute-intensive ops like convolutions.
06

Fusion Profitability Analysis

TVM does not fuse blindly; it uses heuristics and models to assess fusion profitability. Key considerations include:

  • Operator Dependencies: Only fusible within data-flow paths.
  • Memory Footprint: Fusing very large operators can exceed register pressure or shared memory limits, causing spills.
  • Parallelism: Fusion can sometimes reduce opportunities for parallel execution.
  • Hardware Characteristics: The optimal fusion strategy differs for a multi-core CPU versus a massively parallel GPU. TVM's cost models encode these hardware traits to make profitable decisions.
COMPARISON

Fusion in TVM vs. Other Compilers

A technical comparison of operator and kernel fusion capabilities across major deep learning compilers, highlighting distinct design philosophies and optimization targets.

Feature / MechanismApache TVMXLA (TensorFlow/JAX)torch.compile (PyTorch Inductor)MLIR-Based Compilers (e.g., IREE)

Primary Fusion Strategy

Explicit scheduling via TE/Schedule primitives & Ansor auto-scheduler

Aggressive, heuristic-driven HLO-level fusion

Graph capture & pattern matching via TorchDynamo, kernel fusion in Inductor

Declarative, dialect-based rewriting (e.g., Linalg, Affine)

Programmer Control

High (manual schedule) to automatic (Ansor)

Low (fully automatic, limited user directives)

Medium (automatic, with user hints via torch.compile flags)

High (explicit pass pipelines, pattern rewrite rules)

Fusion Granularity

Fine-grained (loop-level, tensor expressions)

Medium to coarse-grained (HLO operations)

Operator-level, moving to finer-grained kernel fusion

Multi-level (dialect-dependent, from tensors to loops)

Target Hardware Scope

Extensive (CPU, GPU, NPU, custom accelerators via VTA)

Primarily Google TPU, also GPU/CPU

Primarily NVIDIA GPU via Triton, expanding CPU

Vendor-agnostic, targeting CPUs, GPUs, and custom ASICs

Kernel Generation Method

TVM's Tensor Expression (TE) & code generation (LLVM, CUDA, OpenCL)

LLVM-based codegen from fused HLO

Triton for GPU, C++/OpenMP for CPU via Inductor

LLVM/SPIR-V codegen from lowered MLIR dialects

Just-In-Time (JIT) Fusion

Supported (via Relay VM)

Core execution model (JIT compilation)

Core execution model (Eager-mode graph capture)

Supported, but often used for Ahead-of-Time (AOT)

Ahead-of-Time (AOT) Fusion

Primary strength (export standalone fused modules)

Supported (e.g., for mobile deployment via TF Lite)

Evolving (torch.export for static graphs)

Primary strength (AOT compilation for deployable binaries)

Canonical Fused Patterns

Fused Conv-BN-ReLU, arbitrary TE-defined patterns

Fused Conv-BN-ReLU, dot-general fusions

Fused Multi-Head Attention (via FlashAttention), pointwise fusions

Pattern-defined via rewrite rules (e.g., linalg.fusion)

Cost Model for Profitability

Ansor uses ML-based cost model; manual schedules bypass

Rule-based heuristics on HLO graph

Heuristic-based within Inductor scheduler

Pattern benefit predicates and machine learning models

Memory Optimization Focus

Explicit via cache reads/writes, storage flattening, and folding

Implicit via buffer assignment and HLO fusion analysis

Automatic kernel fusion to reduce intermediate allocations

Explicit via memory layout transformations and fusion on buffers

FUSION PATTERNS

Common Fused Patterns in TVM

TVM's fusion compiler identifies and optimizes specific subgraph patterns within a computational graph. These patterns represent common, performance-critical sequences of operations that benefit significantly from being combined into a single kernel.

01

Elementwise Fusion

The combination of multiple pointwise operations that apply an independent function to each element of a tensor. This is one of the most fundamental and profitable fusion patterns.

  • Examples: A sequence like AddReLUSigmoid.
  • Mechanism: TVM's scheduler can fuse these operations by generating a single loop that applies all functions in one pass over the data.
  • Benefit: Eliminates multiple passes over the same memory, drastically reducing memory bandwidth pressure and kernel launch overhead.
02

Vertical (Producer-Consumer) Fusion

The fusion of a producer operator with its immediate consumer operator along the dataflow edge of the graph. This chains sequentially dependent operations.

  • Example: Fusing a MatMul with a subsequent BiasAdd.
  • TVM Implementation: TVM's compute_at and fuse primitives allow the computation of the consumer to be scheduled "inside" the loop nest of the producer.
  • Benefit: The intermediate result from the producer is kept in fast registers or cache for immediate consumption, avoiding a costly write and read to global memory.
03

Horizontal (Parallel) Fusion

The fusion of multiple independent operators that share a common input or operate in parallel on different tensors. This pattern increases thread utilization.

  • Example: Applying separate ReLU and Tanh activations to two different tensors produced from the same layer.
  • TVM Implementation: Achieved by computing the independent operations within the same loop nest or kernel, often using TVM's compute_inline or parallel scheduling constructs.
  • Benefit: Amortizes kernel launch overhead across multiple operations and can improve cache locality if the inputs are related.
04

Reduction Fusion

Fusing an operation that performs a reduction (like sum or max) with preceding elementwise operations. This is critical for patterns like batch normalization.

  • Example: Fusing the mean (sum/N) and variance calculations in a BatchNorm layer with the subsequent normalization and scaling operations.
  • TVM Mechanism: TVM's scheduler can fuse the reduction loops with the computation loops, often using rfactor to manage parallel reduction strategies.
  • Benefit: Intermediate reduction values are computed and consumed on-chip, avoiding multiple sweeps through large tensors in global memory.
05

Conv-BN-ReLU (Canonical CNN Fusion)

The canonical deep learning fusion pattern that combines a Convolution, Batch Normalization, and ReLU activation into a single kernel. This is a prime target for TVM's graph-level pattern matcher.

  • Pattern Recognition: TVM identifies the subgraph conv2dbatch_normrelu and marks it as a fusion group.
  • Kernel Generation: TVM's schedule fuses the loops, applying the BN scaling/shifting and the ReLU clamp directly to the convolution's output before it is written to memory.
  • Impact: This fusion can provide a >2x speedup for CNN inference by eliminating two intermediate tensor writes and reads.
06

MatMul + Bias + GELU (Transformer FFN Fusion)

A critical pattern in Transformer feed-forward networks, fusing the matrix multiplication, bias addition, and non-linear GELU activation. This is a key optimization for LLM inference.

  • Pattern: matmuladd (bias) → gelu.
  • TVM Approach: TVM's Ansor auto-scheduler or manual TE scheduling can generate a single kernel where the GELU approximation is applied elementwise to the MatMul result in registers.
  • Benefit: Significantly reduces latency in the transformer block, which is often memory-bound. This fusion is analogous to the FusedMultiplyAdd + activation fusion in libraries like cuDNN and oneDNN.
FUSION IN TVM

Frequently Asked Questions

Fusion in TVM refers to the operator fusion capabilities within the Apache TVM deep learning compiler stack, which uses its scheduling language and auto-scheduling to generate high-performance fused kernels. Below are key questions about its mechanisms and benefits.

Fusion in TVM is a compiler optimization that combines multiple low-level computational operators from a neural network's computational graph into a single, unified fused kernel. It works by analyzing the dataflow graph, identifying groups of operators (called fusion groups) that can be profitably combined, and then using TVM's Tensor Expression (TE) language and AutoTVM or Ansor schedulers to generate highly optimized CUDA/OpenCL/Metal code for the fused operation. The primary goal is to minimize kernel launch overhead and reduce costly transfers of intermediate tensors between global GPU memory and on-chip registers or caches.

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.