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.
Glossary
Fusion in TVM

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.
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.
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.
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.
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.
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.
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.
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.
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.
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 / Mechanism | Apache TVM | XLA (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 |
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.
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
Add→ReLU→Sigmoid. - 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.
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
MatMulwith a subsequentBiasAdd. - TVM Implementation: TVM's
compute_atandfuseprimitives 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.
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
ReLUandTanhactivations 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_inlineor parallel scheduling constructs. - Benefit: Amortizes kernel launch overhead across multiple operations and can improve cache locality if the inputs are related.
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
rfactorto manage parallel reduction strategies. - Benefit: Intermediate reduction values are computed and consumed on-chip, avoiding multiple sweeps through large tensors in global memory.
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
conv2d→batch_norm→reluand 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.
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:
matmul→add(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.
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.
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Related Terms
Fusion in TVM is part of a broader compiler ecosystem for optimizing neural network execution. These related concepts define the techniques, tools, and patterns that enable high-performance fused kernels.
Kernel Fusion
Kernel fusion is the foundational low-level compiler optimization that combines multiple GPU or accelerator kernels into a single, unified kernel. This directly reduces kernel launch overhead—the latency of submitting work to the GPU—and improves data locality by keeping intermediate results in fast registers or shared memory instead of writing them to slow global memory. It is the mechanical implementation of the fusion concept.
Operator Fusion
Operator fusion is the graph-level optimization that identifies and merges adjacent computational nodes (operators) in a neural network's computational graph. While kernel fusion works at the hardware instruction level, operator fusion works at the framework abstraction level (e.g., combining a Conv2d, BatchNorm, and ReLU). TVM's fusion capabilities bridge these levels by transforming fused operator patterns into optimized fused kernels.
Fusion Compiler
A fusion compiler is a specialized compiler or compiler pass designed to automate fusion optimizations. Key examples include:
- XLA (Accelerated Linear Algebra): Google's compiler for TensorFlow/JAX, known for aggressive fusion.
- MLIR (Multi-Level Intermediate Representation): Provides dialects (like Linalg) and transformation infrastructure for fusion.
- TVM's Relay and TIR: TVM uses its Relay frontend for graph-level fusion and its TensorIR (TIR) for scheduling and kernel generation. These compilers use fusion heuristics and cost models to decide fusion profitability.
Fusion Patterns
Canonical fusion patterns are pre-defined, high-value operator sequences that compilers target for fusion. Common examples include:
- Fused Conv-BN-ReLU: The quintessential CNN layer fusion, combining Convolution, Batch Normalization, and activation.
- Fused Multi-Head Attention: A complex fusion that combines projection, scoring, softmax, and aggregation into one kernel, as seen in FlashAttention.
- Elementwise Fusion: Merging pointwise ops like
Add,Mul,Sigmoidthat operate independently on each tensor element. TVM's pattern matching infrastructure automatically identifies and applies these patterns.
Fusion Strategies
Fusion decisions are guided by the nature of the workload and hardware constraints:
- Vertical Fusion: Merging a producer operator with its consumer (sequential dependency).
- Horizontal Fusion: Merging independent operators that share an input or run in parallel.
- Memory-Bound Fusion: Focused on reducing data movement between GPU memory hierarchies.
- Compute-Bound Fusion: Aimed at increasing arithmetic intensity to saturate GPU compute units. TVM's fusion-aware scheduling and fusion planner evaluate these strategies to generate an optimal execution plan.
Compilation Modes
Fusion can be applied at different stages of the compilation lifecycle:
- Ahead-of-Time Fusion (AOT Fusion): Fusion and kernel generation occur statically before deployment, producing a portable, optimized binary. Ideal for fixed model architectures and target hardware.
- Just-In-Time Fusion (JIT Fusion): Fusion decisions are made dynamically at runtime (e.g., on first model execution). This allows optimization based on actual input shapes and hardware context, as used by torch.compile in PyTorch. TVM supports both modes, allowing engineers to choose the appropriate trade-off between compilation time and runtime flexibility.

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.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us