You are viewing a plain text version of this content. The canonical link for it is here.
Posted to discuss-archive@tvm.apache.org by "tlopex (via GitHub)" <gi...@apache.org> on 2026/04/12 05:44:36 UTC

[PR] [Docs] Add operator fusion architecture documentation [tvm]

tlopex opened a new pull request, #19394:
URL: https://github.com/apache/tvm/pull/19394

   as per title


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] [Docs] Add operator fusion architecture documentation [tvm]

Posted by "MasterJH5574 (via GitHub)" <gi...@apache.org>.
MasterJH5574 merged PR #19394:
URL: https://github.com/apache/tvm/pull/19394


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] [Docs] Add operator fusion architecture documentation [tvm]

Posted by "gemini-code-assist[bot] (via GitHub)" <gi...@apache.org>.
gemini-code-assist[bot] commented on code in PR #19394:
URL: https://github.com/apache/tvm/pull/19394#discussion_r3069032832


##########
docs/arch/fusion.rst:
##########
@@ -0,0 +1,391 @@
+..  Licensed to the Apache Software Foundation (ASF) under one
+    or more contributor license agreements.  See the NOTICE file
+    distributed with this work for additional information
+    regarding copyright ownership.  The ASF licenses this file
+    to you under the Apache License, Version 2.0 (the
+    "License"); you may not use this file except in compliance
+    with the License.  You may obtain a copy of the License at
+
+..    http://www.apache.org/licenses/LICENSE-2.0
+
+..  Unless required by applicable law or agreed to in writing,
+    software distributed under the License is distributed on an
+    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+    KIND, either express or implied.  See the License for the
+    specific language governing permissions and limitations
+    under the License.
+
+.. _fusion-arch:
+
+Operator Fusion
+===============
+
+Operator fusion is one of the most impactful optimizations in TVM. Instead of launching one kernel
+per operator (e.g., conv2d, bias_add, relu), fusion merges multiple operators into a single kernel,
+eliminating intermediate memory allocations and kernel launch overhead.
+
+TVM provides two complementary fusion mechanisms:
+
+- **Automatic fusion** (``FuseOps`` + ``FuseTIR``): groups operators based on their computational
+  patterns using a post-dominator analysis algorithm.
+- **Pattern-based fusion** (``FuseOpsByPattern``): groups operators that match user-defined
+  dataflow patterns, typically for offloading to external backends (cuBLAS, CUTLASS, DNNL, etc.).
+
+Both produce the same output: Relax functions marked with ``Primitive=True`` that are later
+lowered to fused TIR kernels or dispatched to external libraries.
+
+Overview
+--------
+
+Fusion involves three passes:
+
+.. code-block:: text
+
+   IRModule (after LegalizeOps)
+        │
+        ▼  AnnotateTIROpPattern        ← label each op (elementwise, reduce, etc.)
+   IRModule (annotated)
+        │
+        ▼  FuseOps                     ← group ops into fused Relax functions
+   IRModule (with fused functions marked Primitive=True)
+        │
+        ▼  FuseTIR                     ← merge TIR PrimFuncs inside each group
+   IRModule (fused TIR kernels)
+
+In the compilation pipeline, these passes appear in the backend-specific ``legalize_passes``
+phase. For example, the CUDA pipeline (``python/tvm/relax/backend/cuda/pipeline.py``) runs:
+
+.. code-block:: python
+
+   LegalizeOps()          # lower Relax ops to call_tir
+   AnnotateTIROpPattern() # annotate pattern kinds
+   FoldConstant()
+   FuseOps()              # group ops
+   FuseTIR()              # merge TIR functions
+
+
+Operator Pattern Classification
+-------------------------------
+
+Before fusion, ``AnnotateTIROpPattern`` analyzes each TIR function in the module and assigns
+an ``OpPatternKind``. The fusion algorithm uses these pattern kinds to decide which operators
+can be fused together.
+
+.. list-table::
+   :header-rows: 1
+   :widths: 20 10 70
+
+   * - Pattern Kind
+     - Value
+     - Description
+   * - ``kElemWise``
+     - 0
+     - Elementwise: one-to-one input/output mapping (e.g., ``add``, ``relu``, ``exp``).
+   * - ``kBroadcast``
+     - 1
+     - Broadcasting: output axes map to input axes in order, but some input axes may be
+       broadcast (e.g., ``bias_add``). Note: ``transpose`` is **not** broadcast because axes
+       are reordered.
+   * - ``kInjective``
+     - 2
+     - Injective: each output element depends on a single input element, but the mapping may
+       be non-trivial (e.g., ``reshape``, ``concatenate``, ``transpose``).
+   * - ``kCommReduce``
+     - 3
+     - Communicative reduction: output elements aggregate over input elements
+       (e.g., ``sum``, ``max``, ``mean``).
+   * - ``kOutEWiseFusable``
+     - 4
+     - Complex operation whose output can accept elementwise followers, but cannot chain
+       with another complex op (e.g., ``conv2d``, ``matmul``, ``dense``).
+   * - ``kTuple``
+     - 7
+     - Tuple node. Can fuse into subsequent injective ops but is treated specially.
+   * - ``kOpaque``
+     - 8
+     - Opaque: cannot be fused (e.g., external function calls, operations with side effects).
+
+These kinds form an ordering: lower values are "simpler" and more fusable. The fusion algorithm
+uses ``CombinePattern(lhs, rhs) = max(lhs, rhs)`` when merging patterns along a path.
+
+
+FuseOps: Automatic Fusion
+-------------------------
+
+``FuseOps`` (``src/relax/transform/fuse_ops.cc``) groups bindings in a dataflow block into
+new Relax functions. It operates only within ``DataflowBlock``\ s — if your module doesn't have
+any, run ``ConvertToDataflow`` first.
+
+Algorithm
+~~~~~~~~~
+
+The fusion algorithm addresses diamond-shaped dataflow branches, where a single producer
+(e.g., conv2d) has multiple consumers that eventually reconverge:
+
+.. code-block:: text
+
+            conv2d
+            /  |  \
+           /   |   \
+         op    op   op
+          \    |    /
+           \   |   /
+          elemwise add
+
+At the point of ``conv2d``, we don't know if all future paths will merge. The algorithm uses
+**post-dominator analysis** to resolve this:
+
+1. **Build forward graph**: construct an ``IndexedForwardGraph`` from the dataflow block.
+   Each node has an ``OpPatternKind`` and a list of forward edges.
+
+2. **Build post-dominator tree**: compute the immediate post-dominator of each node using
+   Least Common Ancestor (LCA) on the DAG. The post-dominator of a node is the closest
+   downstream node where **all** future paths converge.
+
+3. **Fuse groups**: for each node in topological order, check if it can be fused with its
+   immediate post-dominator:
+
+   - **CheckPath**: verify that all paths from the node to its post-dominator satisfy the
+     fusion conditions (pattern compatibility, depth limits, argument limits).
+   - **CommitFuse**: mark all intermediate nodes as belonging to the same group using a
+     Union-Find data structure.
+
+4. **Create grouped functions**: extract each group into a new ``relax.Function`` with the
+   attribute ``Primitive=True``. Replace the original bindings with a call to the grouped
+   function.
+
+Fusion rules
+~~~~~~~~~~~~
+
+The key fusion decisions depend on the ``OpPatternKind`` of the source, the path, and the
+post-dominator. The algorithm runs in three phases (via ``GraphPartitioner::RunFuse``) so that
+higher-complexity ops get a chance to fuse first:
+
+- **Phase 0**: ``kOutEWiseFusable`` ops (e.g., ``conv2d``) can fuse with their elementwise
+  post-dominator if all intermediate ops are broadcast or simpler. This enables patterns like
+  conv2d + bias_add + relu. Two ``kOutEWiseFusable`` ops cannot fuse together.
+- **Phase 1**: ``kInjective`` and ``kTuple`` ops can fuse only when all paths to the
+  post-dominator are injective or simpler. This is deferred to phase 1 so that
+  ``kOutEWiseFusable`` groups are finalized first.
+- **Phase 2**: fuse injective ops into intermediate tuple nodes that have already been absorbed
+  by subsequent injective groups.
+
+``kElemWise`` / ``kBroadcast`` ops are processed in **every** phase (not restricted to one):
+they can fuse into a post-dominator that is injective or reduction. The sink (final node) may
+also be a ``kOutEWiseFusable`` group that was formed in phase 0 — this is how elementwise
+producers merge into an existing conv2d fusion group.
+
+Additional constraints:
+
+- **Reduction** (``kCommReduce``) ops never initiate fusion — they act as sinks only. Elementwise
+  and broadcast producers can fuse *into* a reduction, but a reduction cannot fuse forward.
+- **Opaque** ops are fusion barriers.
+- A group cannot exceed ``kMaxFusedOps`` (256) nodes or the maximum function argument count.

Review Comment:
   ![medium](https://www.gstatic.com/codereviewagent/medium-priority.svg)
   
   It would be beneficial to mention that the `kMaxFusedOps` limit is configurable via the `relax.FuseOps.max_depth` pass configuration option, as this provides users with control over the fusion granularity.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org