32 Commits

Author SHA1 Message Date
Tianqi Chen 3918e14389 [REFACTOR][IR] Inline ApplyPassToFunction into relax decompose_ops, delete the util (#19612)
## Summary

`ApplyPassToFunction` is a general-purpose wrapper that runs a pass on
only the functions in an IRModule whose name matches a regex. Its sole
in-tree production callers are `DecomposeOpsForInference` /
`DecomposeOpsForTraining` in `src/relax/transform/decompose_ops.cc`, and
both callers always supply a literal function name (never a regex
pattern). Inlining the logic as a file-local helper simplifies the
module-level context and removes an abstraction that exists only to
support one use case.

- Inline the helper as `ApplyDecomposeToFunction` (exact-name match, not
regex) in `src/relax/transform/decompose_ops.cc`
- Delete `src/ir/apply_pass_to_function.cc`, its `transform.h`
declaration, and the Python wrapper in `python/tvm/ir/transform.py`
- Remove two DCE tests
(`test_compatibility_with_apply_pass_to_function`,
`test_well_formed_output_with_restricted_scope`) that tested the
utility's plumbing rather than DCE behavior
2026-05-26 15:30:20 -04:00
Tianqi Chen 44dbd138d5 [FFI] Bump tvm-ffi to 63224e3 and fix regressions (#18938)
## Summary

Bump tvm-ffi submodule from c85fd42 (#471) to 63224e3 (#512), spanning
41 commits with 7 breaking changes. Fix regressions introduced by the
bump:

### Fixes

1. **Duplicate field declarations in C++ types** — New tvm-ffi
auto-wires `__init__` from C++ reflection by walking the parent type
chain. Child types that re-declared parent fields
(`RXPlaceholderOpNode`, `FunctionFrameNode`) caused duplicate parameter
errors. Fixed by removing duplicate field registrations from child
types.

2. **Repr format regression** (7 tests) — New tvm-ffi `CObject.__repr__`
uses dataclass repr. Added `Node.__repr__` in `python/tvm/ir/base.py` to
use TVMScript printer for IR nodes.

3. **Host/device function split** (3 tests) — `str(target.kind)` now
returns full dataclass repr instead of kind name. Changed to
`target.kind.name` in `python/tvm/tirx/build.py`.

4. **`__slots__` enforcement** — New tvm-ffi enforces `__slots__=()` on
Object subclasses. Added `__slots__ = ("__dict__",)` to classes that
need instance attributes: `Pass`, `BlockBuilder`, `TVMDerivedObject`.

### Changes
- `3rdparty/tvm-ffi` — submodule bump c85fd42 → 63224e3
- `python/tvm/ir/base.py` — `Node.__repr__` using TVMScript printer
- `python/tvm/ir/transform.py` — `Pass.__slots__ = ("__dict__",)`
- `python/tvm/tirx/build.py` — `target.kind.name` instead of
`str(target.kind)`
- `python/tvm/relax/block_builder.py` — `BlockBuilder.__slots__ =
("__dict__",)`
- `python/tvm/runtime/support.py` — `TVMDerivedObject.__slots__ =
("__dict__", "__weakref__")`
- `python/tvm/s_tir/meta_schedule/utils.py` —
`TVMDerivedObject.__slots__ = ("__dict__",)`
- `include/tvm/script/ir_builder/relax/frame.h` — remove duplicate field
registrations
- `src/relax/ir/emit_te.h` — remove duplicate field registrations

## Test plan
- [x] tirx-base: 251 passed, 23 skipped
- [x] relax import + build: verified
- [ ] Full CI
2026-03-28 09:38:18 -04:00
Tianqi Chen 9a8320acbd [LINT][PYTHON] Modernize annotations with ruff UP rules (#18830)
This PR enables ruff pyupgrade (UP) rules with py310 target, auto-fixing
~5600 annotation modernizations (PEP 585 generics, PEP 604 unions,
deprecated typing imports).

Also removes from __future__ import annotations from ir/module.py and
rmsnorm.py, bumps requires-python to >=3.10, and removes absolute_import
aliases from topi/contrib files.
2026-02-27 21:29:47 -05:00
Tianqi Chen aa2e609136 [LINT] Modernize lint to use pre-commit hooks (#18807)
This PR migrates existing lint to use pre-commit hooks
2026-02-22 11:03:21 -05:00
Siyuan Feng 6e0d4d51a3 [MISC] Fix compilation warnings (#18509)
This commit addresses various compilation warnings across the codebase:

- Fixed warnings in IR transform infrastructure (transform.h,
transform.cc)
- Updated Python bindings to resolve type-related warnings
(transform.py)
- Addressed warnings in Relax alter_op_impl transformation
- Fixed compilation warnings in TIR schedule compute_inline primitive

These changes improve code quality and ensure clean compilation across
different compilers and platforms.
2025-11-26 07:01:39 -05:00
Tianqi Chen a7a0168be5 [FFI][REFACTOR] Establish tvm_ffi python module (#18226)
* [FFI][REFACTOR] Establish tvm_ffi as a standalone python module

This PR establishes tvm_ffi as a standalone python module.
The ffi is structured as a minimal pip module that can be
directly install by path or url.

examples/get_started provided a minimal example.
This is a major change as we are decoupling tvm_ffi as a
separate package, users need to install tvm_ffi separately.

Thanks to its minimal dependency, tvm_ffi can be easily installed
even just from the source by pip install ./ffi

This change would enable future improvement for library plugins
to have lightweight dependencies by just working on top of
the tvm_ffi, while the main compiler toolchain and runtime
can be layered on top.

* [FFI] Improve traceback setups

This PR improves traceback related setups
2025-08-24 15:46:20 -07:00
Tianqi Chen b2b7c62fb5 [REFACTOR] Phase out the relax tuning_api (#18043)
This PR phases out relax tuning api since we don't need the
logic for per function tuning which is main need.
2025-06-05 23:49:39 -04:00
Tianqi Chen 4289efa0d5 [REFACTOR][PYTHON] Phase out tvm._ffi and Limited API support (#18020)
This PR phases out tvm._ffi redirections in favor of new FFI
new functions are now called via tvm.ffi.

We also enabled limited API support for python 3.12+
so the compiled binary can be forward compatible to future
python versions.
2025-05-28 16:52:36 -04:00
Tianqi Chen 95d1268982 [REFACTOR] Introduce and modernize FFI system (#17920)
This PR modernizes the FFI foundation of the project and introduce
a new minimal and lightweight module [tvm ffi](https://github.com/apache/tvm/tree/refactor-s3/ffi)
based on our lessons in the past few years. It implements a modern
version of the [Unified Packed and Object RFC](https://github.com/apache/tvm-rfcs/blob/main/rfcs/0097-unify-packed-and-object.md)
that unifies the packed function call and object systems.

Summary of the change:
- A dedicated clean Any/AnyView that can store strong and weak
references of items
- Function(previously PackedFunc) system built on top of the Any/AnyView
- A minimal C API that backs the overall calls. We are stabilizing the
API with a goal to bring clean, stable FFI conventions for both compiled
and registered code
- A rewrite of core python binding and generated code based on the module
- Update existing code and test cases to the new module
- Latest dlpack support
 
The new module brings many benefits thanks to the cleaner design,
to name a few:
- Any can support both POD types(int) and object types.
- Containers (e.g. Array) can now also contain Any value, e.g. now
`Array<int>` is supported, no need for boxed types
- Error handling now upgrades to object-based, allowing cleaner
traceback across languages
- Map now preserves insertion orders
- Path toward isolated stabilize minimum core ABI/API foundation module
- Type traits based design that cleanly defines how values interact
with Any system
- Automatic conversion of different types based on traits if needed 

Because FFI upgrade is at heart of the project, the change touches every
component of the system. Importantly, this is an upgrade of the ABI so the
change is not backward compatible.  The code compiled under the old
FFI won't work under the new one. We did provide example ABI translation
(e.g. LegacyTVMArgValueToFFIAny) functions for compatibility. 
The PR tries to leave files in their old places while creating redirections.
The goal is to have the first milestone landed and infrastructure in place,
so we can do further refactors to complete features and cleanup legacy code
as trackable PRs. As of now, python binding and compiled code are under the
new convention while RPC and some  other bindings still relies on legacy ABI
translation. We will work on upgrades in the coming PRs, including areas such
as reflection, phasing out legacy redirections etc.
2025-05-06 19:18:33 -04:00
Siyuan Feng cd92392d34 [Refactor] Clean up Relay references in the codebase (#17733)
Removing relay references and statements in the codebase.
2025-03-12 09:20:11 -04:00
Tianqi Chen c81fccaa2f [REFACTOR] Phase out te.Schedule c++ components (#17662)
* cleanup schedule c++

* remove vitis ai

* remove VERILATOR

* remove aocl and sdaccel

* remove opengl

* remove microdev and antlr

* remove frontends

* fix

* Cleanup relay related legacy components

* fix

---------

Co-authored-by: Siyuan Feng <hzfengsy@sjtu.edu.cn>
2025-02-17 17:03:09 -05:00
Eric Lunderberg 8da3de1522 [Redo][Unity] Split DecomposeOpsForTraining into two steps (#16465)
* [Support] Add PackedFunc "tvm.support.regex_match"

This function should be used instead of `std::regex` within C++ call
sites, to avoid ABI incompatibilities with pytorch.

Currently, the pytorch wheels available through pip install use the
pre-C++11 ABI by setting `-DUSE_CXX11_ABI=0` [0]. If TVM were to user
the pre-C++11 ABI, this would cause breakages with dynamically-linked
LLVM environments.

Use of the `<regex>` header in TVM should be avoided, as its
implementation is not supported by gcc's dual ABI. This ABI
incompatibility results in runtime errors either when `std::regex` is
called from TVM, or when `std::regex` is called from pytorch,
depending on which library was loaded first.  This restriction can be
removed when a version of pytorch compiled using `-DUSE_CXX11_ABI=1`
is available from PyPI.

[0] https://github.com/pytorch/pytorch/issues/51039

* [Redo][Unity] Split DecomposeOpsForTraining into two steps

This is a reapplication of https://github.com/apache/tvm/pull/15954,
after resolving the breakages that required reverting in
https://github.com/apache/tvm/pull/16442.  The regex matching is now
implemented without the `#include <regex>` from the C++ stdlib, to
avoid ABI incompatibility with pytorch.

Prior to this commit, the `DecomposeOpsForTraining` transform directly
replaced `relax.nn.batch_norm` into more primitive relax operations.
This required the decomposed form of `relax.nn.batch_norm` to be
duplicated with `DecomposeOpsForInference`.  This commit refactors the
pass to occur in two steps, first to apply training-specific
mutations, and then to decompose.

Having a clear `DecomposeOps` pass also has a clear single location
for operator decomposition, which may be migrated into the operator
definition in the future, similar to `FLegalize`.
2024-02-06 08:02:40 -06:00
Eldar Yusupov 6dd431b430 [TIR][Doc] Fix formatting in pop_trace docstring (#14894) 2023-05-20 11:38:00 +09:00
Sunghyun Park 30a5669b8a [Unity][Pass][TuningAPI] Introduce TuningAPI and MetaSchedule pass (#14014)
Add TuningAPI and MetaSchedule tuning pass
2023-04-01 15:31:36 -04:00
Eric Lunderberg 92de8e9afe [Transform] Use callable() instead of isinstance() for type checking (#14248)
Previously, type-checking of a callable arguments, such as to
`tvm.ir.transform.module_pass`, was done using
`isinstance(arg, (types.FunctionType, types.LambdaType))`.  This check
can give false negatives for valid python types, such as a bound
method or an instance of a class that implements `__call__`.

This commit replaces the checks with the builtin function `callable()`,
which handles any Python object that can be called using function-like
syntax.
2023-03-11 11:41:10 -05:00
Qiang Zhang b9204cd33e [Relay] Change Default "opt_level" of Sequantial from 2 to 0 (#8634) 2021-08-04 10:32:58 +09:00
chiwwang a4775c23cf [DOCS] Add docs for Pass Instrument (#8220)
* Fix AttributeError when TEST_DATA_ROOT_PATH is set

Initiate a Path object from TEST_DATA_ROOT_PATH to fix the error:
AttributeError: 'str' object has no attribute 'mkdir'

* [DOCS] Add docs for Pass Instrument

 - Add a tutorial about how to use pass instrument.
 - Add related sections in Pass Infrastructure documents.

* Fix ir.rst, the length of separator.

* Fix unused local name

* Fix linting errors

* Fix linting errors

* Fix linting errors

* Address code-review feedbacks

* Fix linting

* Fix the order of tutorial.

* Add exception handling. Address feedbacks.

* Fix CI error -- clearing instruments in global pass_ctx

* Clarify section hierachy.

* Emphasize to use decorator instead of subclassing

* Add a sentence to explain Pass Instrument. Fix typo.

* Shrink python docs a little.

* Fix tag name.

* Address feedbacks.
2021-07-07 11:03:24 -07:00
Leandro Nunes a468f08d77 Add metadata information to the listing of PassContext configuration listing function (#8226)
* Rename PassContext::ListConfigNames() to PassContext::ListConfigs() and its
   Python counterpart tvm.ir.transform.PassContext.list_config_names -> list_configs()

 * Adjust PassContext::ListConfigs() to include also metadata (currently only including the data type)

 * Adjust unit tests
2021-06-10 11:14:05 +08:00
Leandro Nunes 1f2ca068c7 Expose list of PassContext configurations to the Python APIs (#8212)
* Expose C++ PassContext::ListAllConfigs via its Python counterpart
   tvm.ir.transform.PassContext.list_configs()

 * Add unit tests for the C++ and Python layers
2021-06-09 12:07:45 -07:00
zackcquic ece644c5ed [IR][Pass][Instrument] Pass instrument framework (#7952)
* [IR][Pass][Instrument] Pass instrument framework

This commit provides utilies to instrument passes:
  1. Add a new namespace tvm.instrument
  2. Introduce PassInstrument and PassInstrumentor to PassContext

     Example
     -------
    passes_mem = #... Impl of memory instrument
    passes_time = tvm.instrument.PassesTimeInstrument()

    with tvm.transform.PassContext(
        pass_instrumentor=PassInstrumentor([passes_mem, passes_time])):

        tvm.relay.build(mod, 'llvm')

        passes_mem.rendor()
        passes_time.rendor()

  3. Integrate existing PassContext::Trace() and timing profile

* [IR][Pass][Instrument] Fix python test_pass_manager.py

* Fix comment

* Fix lint

* Fix test_pass_annotation

* Fix test_pass_annotation.py

* Fix lint

* Fix test_pass_annotation.py

* Fix test_pass_annotation.py

* Fix review comments

* Fix tutorial use_pass_infra.py

* Fix review comments

* Fix review comments

* Fix typo

* Fix review comments

* Fix review comments

* Fix unittest error: test_cow_pass

* Fix unittest error

* Add more test cases for exceptions

* Fix nit

* Doc override_instruments()

* Fix review comments

* Fix lint

* Fix EnterContext exception behavior
2021-05-28 13:44:09 -04:00
Altan Haan 3a02e0b443 [Pass] Profiling TVM compiler passes (#7500)
* basic pass profiler prototype

* allow enable/disable of pass profiling

* lint

* add example pass profiler usage as test

* render pass profiles to String instead of stdout
2021-03-02 16:44:00 -08:00
Jared Roesch f13fed55cf [Format] Convert all Python code w/o CI (#6448)
* Add black setup

* Tweak pyproject.toml

* Fix syntax issues

* Fix

* Tweak

* Black all Python code
2020-09-11 22:17:24 +09:00
Zhi ddf7190846 [REFACTOR][RELAY] move fallback_device to config (#5690) 2020-05-29 07:52:03 -07:00
Tianqi Chen b2640260cd [REFACTOR][TIR][API-Change] Migrate BuildConfig to PassContext. (#5668)
* [REFACTOR][TIR] Migrate BuildConfig to PassContext.

This PR migrates the TIR configurations from BuildConfig to the
PassContext used by the unified IR.
Moving forward, PassContext will be the unified way to configure passes in the TVM stack.

Changes

- Refactored TVM_PASS_REGISTER_CONFIG_OPTION to take in the reference type.
- Removed BuildConfig.
- Migrated the passes to use PassContext.

* Update include/tvm/ir/attrs.h

Co-authored-by: Zhi <5145158+zhiics@users.noreply.github.com>

Co-authored-by: Zhi <5145158+zhiics@users.noreply.github.com>
2020-05-25 20:50:00 -07:00
Tianqi Chen e180b6614a [NODE][PASS] Introduce config to PassContext. (#5631)
This PR introduces a new config field to the PassContext
to allow it store arbitary config values.

To make sure that the config is validated, we allow each pass
to register the config key they would expect and the corresponding types.

We also introduce a CreateObject from Map<str, Object> to allow config creation
from a json-nest(like in vscode) in python.

We added an example of UnrollLoopConfig.

Followup PR should migrate the passes to use the new config field.
2020-05-20 14:54:11 -07:00
Tianqi Chen c3511c5e2c [TIR][REFACTOR] Remove te::Tensor dependencies from TIR passes. (#5372)
* [TIR][REFACTOR] Remove te::Tensor dependencies from TIR passes.

te::Tensor is an useful object for tensor expression, but brings
un-necessary reverse dependency in TIR nodes such as Provide and Realize.

This PR is a first step to remove this dependency. We will use Buffer in all the places
where the te::Tensor was used. The rough correspondence are:

- Provide -> BufferStore
- Realize -> BufferRealize
- HalideCall -> BufferLoad.

After this change, we can not use IRModule of PrimFuncs cleanly to represent TIR
at any point of the optimizations. Buffer will serve as the abstraction for the TIR data
models to represent the intermediate storages and their constraints.

We still keep Realize/HalideCall and Provide as TIR nodes for now to make the change minimum.
Right after ScheduleOps, we call SchedulePostProcToPrimFunc to canonicalize the temporary IR
generated by TE(which contains these nodes) to the TIR.

The TIR optimizations are now mostly migrated to to the pass manager.
Followup PRs are needed to migrate the remaining few passes.

* Fix dev tutorial
2020-04-19 15:26:51 -07:00
Tianqi Chen 275e317c56 [RELAY] Remove re-exports of tvm.transform (#5337) 2020-04-14 17:03:15 -07:00
Tianqi Chen f08d5d78ee [TIR] Refactor MakePackedAPI to target dependent stage. (#5326)
Previously MakePackedAPI was in the target independent stage,
but never the less requires the device_type information that will be
binded at a later target dependent stage.

The previous implementation was due to the limitation of LoweredFunc
which can not carry buffer_map info(so they have to be lowered right away).
This is no longer the case after the unified IR refactor.

This PR migrates MakePackedAPI to a target dependent stage
and removes the un-necessary BindDevice pass.
2020-04-14 07:48:14 -07:00
Tianqi Chen 6027412bcb [IR] Update the type_keys to reflect the code-org (#5074) 2020-03-15 15:39:47 -07:00
zhengdi 8c6a772365 [RELAY] fix error message (#4945) 2020-02-27 08:43:10 -08:00
Cody Yu fd6d7837ed [DOCS] Fix sphinx warnings (#4917)
* Fix Python docstrings

* More fixes

* Fix lint
2020-02-20 09:24:37 -08:00
Tianqi Chen a566161147 [REFACTOR][PY][API-CHANGE] establish tvm.ir, migrate corresponding files (#4862)
* [REFACTOR][PY][API-CHANGE] establish tvm.ir, migrate corresponding relay files.

This PR establishes tvm.ir and migrates the corresponding relay
files into the new folder.

API Change:
- relay.Module -> tvm.IRModule

* Update with ADT

* Migrate transform

* address comments

* Migrate module

* Migrate json_compact

* Migrate attrs

* Move LoweredFunc to stmt temporarily

* temp migrate container

* Finish migrate container
2020-02-11 20:01:36 -08:00