You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@tvm.apache.org by tq...@apache.org on 2026/09/23 12:56:21 UTC
(tvm) 03/03: [REFACTOR][Script] Type parser contracts and unify argument policies
This is an automated email from the ASF dual-hosted git repository.
tqchen pushed a commit to branch script/canonical-parser-df
in repository https://gitbox.apache.org/repos/asf/tvm.git
commit 36d5fe1903cea90c72f4d3f4525de7a130de28d2
Author: Tianqi Chen <tq...@users.noreply.github.com>
AuthorDate: Wed Sep 23 12:55:11 2026 +0000
[REFACTOR][Script] Type parser contracts and unify argument policies
Annotate parser inputs, callbacks and retained state. Route expression-string
metadata through args_policy, including bound methods and dtype propagation.
Group shared recording tests under tests/python/script and native builder
contracts under their dialect script suites. Keep actual helper integrations in
their owning domains and update platform test discovery.
---
.github/workflows/main.yml | 4 +-
python/tvm/relax/script/builder/__init__.py | 50 ++-
python/tvm/script/parser/__init__.py | 16 +-
python/tvm/script/parser/call_args_policy.py | 29 +-
python/tvm/script/parser/diagnostics.py | 6 +-
python/tvm/script/parser/entry.py | 228 +++++++++---
python/tvm/script/parser/jit_support.py | 27 +-
python/tvm/script/parser/prescan.py | 108 +++---
python/tvm/script/parser/protocol.py | 228 ++++--------
python/tvm/script/parser/source.py | 14 +-
python/tvm/script/parser/transpile.py | 234 +++++++-----
python/tvm/tirx/script/builder/__init__.py | 58 ++-
.../test_capture_annotation_constructors.py} | 0
.../script/test_capture_annotation_identity.py | 87 +++++
.../test_frontend_relax_construction_validation.py | 77 ++++
.../relax/script/test_parser_captured_shapes.py} | 22 +-
.../script/test_parser_construction_regressions.py | 68 ++++
.../test_parser_distributed_aliases.py | 0
.../script/test_parser_distributed_range.py} | 40 +-
.../test_parser_local_function_types.py | 0
.../{ => script}/test_parser_local_functions.py | 0
.../script/test_parser_relax_emission.py} | 44 +--
.../script/test_parser_relax_frames.py} | 170 ++-------
.../script/test_parser_relax_resolvers.py} | 69 +---
.../test_relax_parser_comparison_integration.py | 90 +++++
.../test_frontend_nn_llm_script_helpers.py} | 98 +----
tests/python/relax/test_parser_scoped_symbols.py | 96 -----
.../s_tir/test_s_tir_axis_binding_validation.py} | 30 +-
.../test_s_tir_migrated_source_symbols.py} | 2 +-
.../script/conftest.py} | 25 +-
tests/{parser => python/script}/dummy_builder.py | 19 +-
.../python/script/test_capture_definition_scope.py | 402 +++++++++++++++++++++
tests/python/script/test_capture_frontend_scope.py | 232 ++++++++++++
.../test_capture_gallery_source.py} | 74 ++--
tests/python/script/test_capture_nonlocal.py | 66 ++++
tests/{parser => python/script}/test_parser.py | 33 +-
.../test_parser_bypass_source_attachment.py} | 22 +-
.../{tirx => script}/test_parser_call_scopes.py | 86 +++--
.../script/test_parser_comparison_semantics.py | 347 ++++++++++++++++++
tests/python/script/test_parser_host_selection.py | 263 ++++++++++++++
tests/python/script/test_parser_scoped_symbols.py | 104 ++++++
.../python/script/test_parser_shared_resolvers.py | 79 ++++
tests/python/script/test_parser_span_helpers.py | 72 ++++
.../tirx/script/test_capture_jit_execution.py | 51 +++
.../test_frontend_construction_validation.py | 96 +++++
.../{ => script}/test_parser_backend_namespaces.py | 0
.../script/test_parser_buffer_strides.py} | 81 +----
.../tirx/{ => script}/test_parser_buffer_views.py | 0
.../tirx/script/test_parser_constexpr_buffers.py | 50 +++
.../tirx/{ => script}/test_parser_emitted_spans.py | 42 +--
.../{ => script}/test_parser_helper_migrations.py | 83 +----
.../{ => script}/test_parser_jit_specialization.py | 0
.../{ => script}/test_parser_printer_type_vars.py | 0
.../{ => script}/test_parser_range_annotations.py | 11 +-
.../{ => script}/test_parser_scope_id_identity.py | 17 +-
.../{ => script}/test_parser_scope_id_names.py | 0
.../tirx/{ => script}/test_parser_self_bind.py | 4 +-
.../{ => script}/test_parser_tile_namespaces.py | 0
.../script/test_parser_tirx_emission.py} | 23 +-
.../script/test_parser_tirx_frames.py} | 187 +++-------
.../script/test_parser_tirx_resolvers.py} | 76 +---
.../test_tirx_parser_comparison_integration.py | 199 ++++++++++
tests/python/tirx/test_parser_constexpr.py | 264 --------------
.../test_parser_comparison_source_order.py | 298 ---------------
.../unittest/test_parser_comparison_values.py | 203 -----------
.../unittest/test_parser_definition_context.py | 391 --------------------
.../unittest/test_parser_frontend_regressions.py | 303 ----------------
tests/python/unittest/test_parser_nonlocal.py | 57 ---
tests/scripts/task_python_unittest.sh | 2 +-
69 files changed, 3207 insertions(+), 2950 deletions(-)
diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml
index 968a9ff52a..2827ed917a 100644
--- a/.github/workflows/main.yml
+++ b/.github/workflows/main.yml
@@ -76,7 +76,7 @@ jobs:
- name: Test
shell: bash -l {0}
run: >-
- python -m pytest -v tests/python/all-platform-minimal-test tests/parser
+ python -m pytest -v tests/python/all-platform-minimal-test tests/python/script
- name: Minimal Metal Compile-Only
shell: bash -l {0}
run: |
@@ -116,4 +116,4 @@ jobs:
- name: Test
shell: cmd /C call {0}
run: >-
- python -m pytest -v tests/python/all-platform-minimal-test tests/parser
+ python -m pytest -v tests/python/all-platform-minimal-test tests/python/script
diff --git a/python/tvm/relax/script/builder/__init__.py b/python/tvm/relax/script/builder/__init__.py
index a3ee4b15ac..546437fca2 100644
--- a/python/tvm/relax/script/builder/__init__.py
+++ b/python/tvm/relax/script/builder/__init__.py
@@ -38,7 +38,6 @@ from tvm.script.ir_builder.base import source_span as _source_span
from tvm.script.ir_builder.ir.protocol import resolve_global_info as _lookup_global_info
from tvm.script.parser.protocol import args_policy as _args_policy
from tvm.script.parser.protocol import constexpr as constexpr
-from tvm.script.parser.protocol import expr_str_args as _expr_str_args
from . import _ffi_api
from . import distributed as dist
@@ -100,7 +99,7 @@ Range = _ir.Range
__tvm_value_if__ = True
-@_expr_str_args("values", introduce=True, dtype="int64")
+@_args_policy({"values": "expr_str"}, dtype="int64")
def Shape(values=None, ndim=-1, *, span=None):
"""Construct a shape type from concrete dimensions."""
return _relax.ShapeType(values, ndim, _source_span(span))
@@ -234,7 +233,13 @@ def arg(name, ty, *, span=None):
def func_ret_type(ret_ty):
- """Set the active function signature return type."""
+ """Set the active function signature return type.
+
+ Parameters
+ ----------
+ ret_ty : Type
+ The function return type.
+ """
return _native.func_ret_type(_type(_return_annotation(ret_ty)))
@@ -242,7 +247,18 @@ func_ret_ty = func_ret_type
def dataflow(*, span=None):
- """Create a dataflow context with explicit finalized exports."""
+ """Create a dataflow context with explicit finalized exports.
+
+ Parameters
+ ----------
+ span : Span or source location, optional
+ Source location attached to the constructed IR.
+
+ Returns
+ -------
+ res : frame.BindingBlockFrame
+ The constructed frame, retaining source metadata.
+ """
return _at(span, _native.dataflow())
@@ -268,12 +284,34 @@ def If(condition, *, span=None):
def Then(*, span=None):
- """Create the true branch of the active conditional."""
+ """Create the true branch of the active conditional.
+
+ Parameters
+ ----------
+ span : Span or source location, optional
+ Source location attached to the constructed IR.
+
+ Returns
+ -------
+ res : frame.ThenFrame
+ The constructed frame, retaining source metadata.
+ """
return _at(span, _native.Then())
def Else(*, span=None):
- """Create the false branch of the active conditional."""
+ """Create the false branch of the active conditional.
+
+ Parameters
+ ----------
+ span : Span or source location, optional
+ Source location attached to the constructed IR.
+
+ Returns
+ -------
+ res : frame.ElseFrame
+ The constructed frame, retaining source metadata.
+ """
return _at(span, _native.Else())
diff --git a/python/tvm/script/parser/__init__.py b/python/tvm/script/parser/__init__.py
index 90e22e6b0a..06c8f97cae 100644
--- a/python/tvm/script/parser/__init__.py
+++ b/python/tvm/script/parser/__init__.py
@@ -16,11 +16,13 @@
# under the License.
"""Canonical TVMScript AST parser and public construction namespaces."""
+from __future__ import annotations
+
import importlib
import sys
-from typing import TypeVar
+from typing import Any, TypeVar
-_ENTRY_EXPORTS = (
+_ENTRY_EXPORTS: tuple[str, ...] = (
"_NAMESPACES",
"from_source",
"ir_module",
@@ -30,12 +32,12 @@ _ENTRY_EXPORTS = (
"pyfunc",
"register_namespace",
)
-__all__ = [name for name in _ENTRY_EXPORTS if not name.startswith("_")]
-_initialized = False
-_initializing = False
+__all__: list[str] = [name for name in _ENTRY_EXPORTS if not name.startswith("_")]
+_initialized: bool = False
+_initializing: bool = False
-def _initialize():
+def _initialize() -> None:
global _initialized, _initializing
if _initialized or _initializing:
return
@@ -104,7 +106,7 @@ def _initialize():
_initializing = False
-def __getattr__(name):
+def __getattr__(name: str) -> Any:
if name in _ENTRY_EXPORTS:
_initialize()
return getattr(importlib.import_module(f"{__name__}.entry"), name)
diff --git a/python/tvm/script/parser/call_args_policy.py b/python/tvm/script/parser/call_args_policy.py
index d7f40bab80..a4b299ac9b 100644
--- a/python/tvm/script/parser/call_args_policy.py
+++ b/python/tvm/script/parser/call_args_policy.py
@@ -23,20 +23,23 @@ AST or adjacent concatenated literals), ranges conservatively fall back to the
literal's complete original range. Rewriting never evaluates source expressions.
"""
+from __future__ import annotations
+
import ast
import inspect
import linecache
import re
+from collections.abc import Callable
from . import protocol
class _LiteralParser:
# filename is immutable for one expression rewrite and owns no source/IR cache.
- def __init__(self, filename):
- self.filename = filename
+ def __init__(self, filename: str) -> None:
+ self.filename: str = filename
- def _string_expression(self, node):
+ def _string_expression(self, node: ast.Constant) -> ast.expr:
try:
expression = ast.parse(node.value, mode="eval").body
except SyntaxError as error:
@@ -72,7 +75,7 @@ class _LiteralParser:
return expression
@staticmethod
- def _literal_positions(literal, node):
+ def _literal_positions(literal: str, node: ast.Constant) -> dict[int, tuple[int, int]] | None:
"""Map decoded expression byte offsets back through the literal's escapes."""
match = re.match("(?i:([rub]*))([\"'])", literal)
if match is None:
@@ -84,7 +87,7 @@ class _LiteralParser:
positions, decoded, offset = {}, "", 0
index = start
- def location(raw_index):
+ def location(raw_index: int) -> tuple[int, int]:
before = literal[:raw_index]
line = node.lineno + before.count("\n")
column = len(before.rsplit("\n", 1)[-1].encode("utf-8"))
@@ -113,14 +116,16 @@ class _LiteralParser:
return positions if decoded == node.value else None
-def parse_annotation(node, filename):
+def parse_annotation(node: ast.expr, filename: str) -> ast.expr:
"""Decode a quoted whole annotation without interpreting its Python names."""
if isinstance(node, ast.Constant) and isinstance(node.value, str):
return _LiteralParser(filename)._string_expression(node)
return node
-def handle_call_args_policy(node, resolve, infrastructure, filename):
+def handle_call_args_policy(
+ node: ast.Call, resolve: Callable[[ast.expr], object], infrastructure: str, filename: str
+) -> ast.Call:
"""Normalize this call's marked literal arguments before normal visitation.
This local preorder step neither visits ordinary arguments nor copies the
@@ -137,12 +142,12 @@ def handle_call_args_policy(node, resolve, infrastructure, filename):
class Symbols(ast.NodeTransformer):
# Only the newly parsed argument string is visited here. This is literal
# normalization, not a second pass over source expressions.
- def visit_Attribute(self, current):
+ def visit_Attribute(self, current: ast.Attribute) -> ast.Attribute:
if resolve(current.value) is not None:
return current
return self.generic_visit(current)
- def visit_Call(self, current):
+ def visit_Call(self, current: ast.Call) -> ast.Call:
if resolve(current.func) is None:
current.func = self.visit(current.func)
current.args = [self.visit(value) for value in current.args]
@@ -150,11 +155,11 @@ def handle_call_args_policy(node, resolve, infrastructure, filename):
keyword.value = self.visit(keyword.value)
return current
- def visit_Name(self, current):
+ def visit_Name(self, current: ast.Name) -> ast.Name:
current._tvm_quoted_symbol = policy.expression.dtype
return current
- def expression_field(current, nested=False):
+ def expression_field(current: ast.expr, nested: bool = False) -> ast.expr:
if isinstance(current, ast.Tuple | ast.List):
current.elts = [expression_field(value, True) for value in current.elts]
elif isinstance(current, ast.Constant) and isinstance(current.value, str):
@@ -162,7 +167,7 @@ def handle_call_args_policy(node, resolve, infrastructure, filename):
return Symbols().visit(literals._string_expression(current))
return current
- def argument(current, name):
+ def argument(current: ast.expr, name: str | None) -> ast.expr:
kind = policy.fields.get(name)
if kind == "expr_str":
return expression_field(current)
diff --git a/python/tvm/script/parser/diagnostics.py b/python/tvm/script/parser/diagnostics.py
index 42e8cd240e..5605011ee4 100644
--- a/python/tvm/script/parser/diagnostics.py
+++ b/python/tvm/script/parser/diagnostics.py
@@ -16,6 +16,8 @@
# under the License.
"""Source-located construction errors without replacing their original traceback."""
+from __future__ import annotations
+
import ast
import linecache
import traceback
@@ -23,7 +25,7 @@ import traceback
from tvm.error import DiagnosticError
-def diagnostic_error(error, filename, tree):
+def diagnostic_error(error: Exception, filename: str, tree: ast.Module) -> DiagnosticError:
"""Return a DiagnosticError highlighting the original source operation.
error is the caught Python/builder exception. filename and tree supply the source
@@ -85,7 +87,7 @@ def diagnostic_error(error, filename, tree):
def _format_source_snippet(
- source_lines: list,
+ source_lines: list[str],
lineno: int,
col_offset: int,
end_lineno: int,
diff --git a/python/tvm/script/parser/entry.py b/python/tvm/script/parser/entry.py
index ad8afc4dd2..a7e560dbe3 100644
--- a/python/tvm/script/parser/entry.py
+++ b/python/tvm/script/parser/entry.py
@@ -16,6 +16,7 @@
# under the License.
"""Source acquisition and declaration/body execution for registered builders."""
+from __future__ import annotations
import __future__
import ast
@@ -25,8 +26,10 @@ import inspect
import linecache
import sys
import textwrap
+from collections.abc import Callable, Mapping
from functools import wraps
-from typing import TypeVar
+from types import FrameType, FunctionType
+from typing import TYPE_CHECKING, Any, TypeVar
from tvm.error import DiagnosticError
from tvm.ir import SourceName
@@ -39,10 +42,21 @@ from .diagnostics import diagnostic_error
from .prescan import PrescanCollector
from .transpile import IRBuilderTranspiler
-_NAMESPACES = {}
+if TYPE_CHECKING:
+ from tvm.ir import IRModule, Span
+ from tvm.relax import ExternFunc
+ from tvm.relax.base_py_module import BasePyModule
+ from tvm.runtime import Device
+ from tvm.target import Target
-def register_namespace(alias, namespace):
+_Callable = TypeVar("_Callable", bound=Callable[..., Any])
+
+# Executed Python bodies and registered dialects may supply arbitrary host/IR values.
+_NAMESPACES: dict[str, object] = {}
+
+
+def register_namespace(alias: str, namespace: object) -> None:
"""Register a host namespace for source-text entry points.
Parameters
@@ -65,7 +79,7 @@ def register_namespace(alias, namespace):
_NAMESPACES[alias] = namespace
-def _closure_values(function):
+def _closure_values(function: FunctionType) -> dict[str, Any]:
values = {}
for name, cell in zip(function.__code__.co_freevars, function.__closure__ or ()):
try:
@@ -76,7 +90,7 @@ def _closure_values(function):
return values
-def _lexical_environment(obj):
+def _lexical_environment(obj: FunctionType | type) -> dict[str, Any]:
"""Retain Python globals and closure bindings without inspecting callers."""
if inspect.isfunction(obj):
return {**obj.__globals__, **_closure_values(obj)}
@@ -84,7 +98,7 @@ def _lexical_environment(obj):
return dict(vars(module)) if module is not None else {}
-def _definition_scope(frame):
+def _definition_scope(frame: FrameType) -> dict[str, Any]:
"""Snapshot immediate locals and active enclosing Python function scopes.
Postponed annotations do not necessarily create closure cells. Retain their
@@ -107,17 +121,17 @@ def _definition_scope(frame):
def recompose_builder(
- translated,
+ translated: ast.Module,
*,
- source_fn,
- definition_scope,
- filename,
- flags,
- name,
- environment,
- result=None,
- definition_scopes_name=None,
-):
+ source_fn: str | FunctionType | type,
+ definition_scope: Mapping[str, Any],
+ filename: str,
+ flags: int,
+ name: str,
+ environment: Mapping[str, Any],
+ result: str | None = None,
+ definition_scopes_name: str | None = None,
+) -> Callable[..., Any]:
"""Compile one builder callable with source lexical and annotation scopes.
Python code objects identify the source's globals and closure cells. The
@@ -189,7 +203,7 @@ def recompose_builder(
default = body.args.kw_defaults[index]
class LexicalDefault(ast.NodeTransformer):
- def visit_Name(self, node):
+ def visit_Name(self, node: ast.Name) -> ast.Name:
return (
ast.copy_location(ast.Name(alias, ast.Load()), node)
if node.id == captured
@@ -228,7 +242,7 @@ def recompose_builder(
return namespace[name]
-def _inside_class(function, frame):
+def _inside_class(function: FunctionType, frame: FrameType) -> bool:
"""Defer only in the exact class frame of a registered module decorator."""
local = frame.f_locals
if local.get("__module__") != function.__module__ or "__qualname__" not in local:
@@ -250,7 +264,7 @@ def _inside_class(function, frame):
if frame.f_back is not None:
environment.update(frame.f_back.f_locals)
- def resolve(expr):
+ def resolve(expr: ast.expr) -> object:
if isinstance(expr, ast.Name):
return environment.get(expr.id)
if isinstance(expr, ast.Attribute):
@@ -265,7 +279,12 @@ def _inside_class(function, frame):
)
-def make_decorator(builder, *, option_map=None, defaults=None):
+def make_decorator(
+ builder: object,
+ *,
+ option_map: Mapping[str, str] | None = None,
+ defaults: Mapping[str, Any] | None = None,
+) -> Callable[..., Any]:
"""Create and register a function decorator for a construction namespace.
Parameters
@@ -302,11 +321,36 @@ def make_decorator(builder, *, option_map=None, defaults=None):
"""
mapping, default_options = dict(option_map or {}), dict(defaults or {})
- def decorator(function=None, **options):
+ def decorator(function: FunctionType | None = None, **options: Any) -> Any:
+ """Parse a Python function into a function of the selected IR dialect.
+
+ Parameters
+ ----------
+ function : Callable, optional
+ The function to be parsed. May be omitted to use the decorator with
+ keyword options, such as ``@T.prim_func(private=True)``.
+ private : bool, optional
+ Whether the function should be treated as private. A private
+ function has no global symbol attribute; a public function has a
+ global symbol matching its name. Defaults to False.
+ check_well_formed : bool, optional
+ Whether to check that the constructed function is well formed.
+ Defaults to True.
+ **options
+ Additional dialect options. ``T.prim_func`` accepts ``s_tir`` and
+ ``persistent``; ``R.function`` accepts ``pure``.
+
+ Returns
+ -------
+ result : PrimFunc or relax.Function or Callable
+ The parsed function, or a decorator when ``function`` is omitted.
+ Class members retain their Python functions until the enclosing
+ module is constructed.
+ """
if function is not None and not inspect.isfunction(function):
raise ValueError("Construction decorators require a function or keyword options")
- def apply(function):
+ def apply(function: FunctionType) -> Any:
frame = inspect.currentframe().f_back
try:
if frame.f_code is decorator.__code__:
@@ -333,7 +377,9 @@ def make_decorator(builder, *, option_map=None, defaults=None):
)
-def make_macro_decorator(builder, *, preserve_return=True, late_binding=False):
+def make_macro_decorator(
+ builder: object, *, preserve_return: bool = True, late_binding: bool = False
+) -> Callable[..., Callable[..., Any]]:
"""Create a decorator for helpers executed in a caller's builder frames.
Parameters
@@ -368,11 +414,51 @@ def make_macro_decorator(builder, *, preserve_return=True, late_binding=False):
compilation, and builder exceptions propagate to the caller.
"""
- def decorator(function=None, **options):
+ def decorator(function: FunctionType | None = None, **options: Any) -> Callable[..., Any]:
+ """Decorate a helper that constructs IR in its caller's active frames.
+
+ Parameters
+ ----------
+ function : Callable, optional
+ The helper function. May be omitted to supply keyword options.
+ hygienic : bool, optional
+ Whether the helper resolves symbols in its definition environment
+ instead of its calling environment. Defaults to True. ``T.macro``
+ and ``R.macro`` capture values at definition time; ``T.inline``
+ refreshes captured closure cells when called.
+
+ Returns
+ -------
+ result : Callable
+ The construction helper, or a decorator when ``function`` is omitted.
+
+ Notes
+ -----
+ ``T.inline`` follows Python lexical scoping with late binding of captured
+ closure cells. Its return statements produce Python values, as do those
+ of ``R.macro``. ``T.macro`` emits returns in the active primitive function.
+
+ Examples
+ --------
+ An inline helper can read values from its enclosing scope::
+
+ import tvm
+ from tvm.script import tirx as T
+
+ x_value = 128
+
+ @T.inline
+ def capture(A, B):
+ B[()] = A[x_value] # x_value resolved from enclosing scope
+
+ @T.prim_func(s_tir=True)
+ def use(A: T.Buffer((1024,), "int32"), B: T.Buffer((), "int32")) -> None:
+ capture(A, B) # Produces B[()] = A[128]
+ """
if function is not None and not inspect.isfunction(function):
raise ValueError("Construction decorators require a function or keyword options")
- def apply(function):
+ def apply(function: FunctionType) -> Callable[..., Any]:
frame = inspect.currentframe().f_back
try:
if frame.f_code is decorator.__code__:
@@ -383,7 +469,7 @@ def make_macro_decorator(builder, *, preserve_return=True, late_binding=False):
definition_env = _lexical_environment(function)
@wraps(function)
- def invoke(*args, **kwargs):
+ def invoke(*args: Any, **kwargs: Any) -> Any:
bound = inspect.signature(function).bind(*args, **kwargs)
bound.apply_defaults()
environment = (
@@ -407,7 +493,7 @@ def make_macro_decorator(builder, *, preserve_return=True, late_binding=False):
return decorator
-def pyfunc(function):
+def pyfunc(function: _Callable) -> _Callable:
"""Mark a Python function for opaque registration in a module.
Parameters
@@ -438,7 +524,9 @@ def pyfunc(function):
syntax_protocol.register_function(pyfunc, None, python=True)
-def _source_lines(source, definition_source):
+def _source_lines(
+ source: FunctionType | type, definition_source: tuple[str, int] | None
+) -> tuple[list[str], int, str | None]:
"""Recover a class from its exact decoration site when module inspection fails."""
try:
lines, start = inspect.getsourcelines(source)
@@ -459,7 +547,12 @@ def _source_lines(source, definition_source):
raise
-def acquire_source(source, filename=None, *, definition_source=None):
+def acquire_source(
+ source: str | FunctionType | type,
+ filename: str | None = None,
+ *,
+ definition_source: tuple[str, int] | None = None,
+) -> tuple[ast.Module, str, int]:
"""Read source into a location-preserving AST, filename and compiler flags.
Text uses ``<str>`` unless a filename is supplied. Function/class source
@@ -496,8 +589,15 @@ def acquire_source(source, filename=None, *, definition_source=None):
def _prepare_transpiler(
- tree, source, environment, definition_scope, filename, *, track_span=True, **options
-):
+ tree: ast.Module,
+ source: str | FunctionType | type,
+ environment: Mapping[str, Any],
+ definition_scope: Mapping[str, Any],
+ filename: str,
+ *,
+ track_span: bool = True,
+ **options: Any,
+) -> tuple[IRBuilderTranspiler, dict[str, Any]]:
"""Prescan an owned tree and inject collision-free execution bindings.
The lexical environment is copied per invocation. Descriptor-safe metadata
@@ -514,7 +614,9 @@ def _prepare_transpiler(
}
# Imports establish source-text namespace metadata before prescan. Their
# original AST nodes remain owned here and execute only once.
- imports = [node for node in tree.body[:-1] if isinstance(node, ast.Import | ast.ImportFrom)]
+ imports: list[ast.stmt] = [
+ node for node in tree.body[:-1] if isinstance(node, ast.Import | ast.ImportFrom)
+ ]
if imports:
exec(compile(ast.Module(imports, []), filename, "exec", dont_inherit=True), namespace)
metadata_environment = {**namespace, **definition_scope}
@@ -531,7 +633,7 @@ def _prepare_transpiler(
prescan = PrescanCollector(metadata, filename=filename).collect(tree)
names = dict.fromkeys([*namespace, *prescan.reserved_names], 0)
- def fresh(prefix="_t"):
+ def fresh(prefix: str = "_t") -> str:
"""Allocate a name without changing any source identifier."""
counter = names.get(prefix, 0)
while f"{prefix}{counter}" in names:
@@ -562,7 +664,7 @@ def _prepare_transpiler(
# One shared SourceName is metadata, not an IR construction result.
namespace[source_name] = SourceName(filename)
- def span(node):
+ def span(node: ast.AST) -> ast.expr:
"""Retain source ranges for builders to materialize during execution."""
if not track_span:
return ast.copy_location(ast.Constant(None), node)
@@ -599,7 +701,14 @@ def _prepare_transpiler(
return transformer, namespace
-def _run_statements(source, builder, environment, bound_names, *, preserve_return=False):
+def _run_statements(
+ source: FunctionType,
+ builder: object,
+ environment: Mapping[str, Any],
+ bound_names: set[str],
+ *,
+ preserve_return: bool = False,
+) -> Any:
"""Execute a macro body in its caller's active builder frames.
Argument binding precedes this call. The helper owns one source AST copy,
@@ -654,7 +763,16 @@ def _run_statements(source, builder, environment, bound_names, *, preserve_retur
return runnable(*(namespace[name] for name in names))
-def _build(tree, source, environment, definition_scope, filename, flags, *, track_span):
+def _build(
+ tree: ast.Module,
+ source: str | FunctionType | type,
+ environment: Mapping[str, Any],
+ definition_scope: Mapping[str, Any],
+ filename: str,
+ flags: int,
+ *,
+ track_span: bool,
+) -> Any:
"""Translate an owned AST and execute its direct native builder program.
Source expressions and annotations execute only in the generated program.
@@ -680,7 +798,12 @@ def _build(tree, source, environment, definition_scope, filename, flags, *, trac
return runnable()
-def make_opaque_function(name, function, source, location=None):
+def make_opaque_function(
+ name: str,
+ function: Callable[..., Any],
+ source: str,
+ location: tuple[SourceName, int, int, int, int] | Span | None = None,
+) -> ExternFunc:
"""Represent a Python module member without executing its body."""
from tvm import relax
@@ -695,7 +818,14 @@ def make_opaque_function(name, function, source, location=None):
)
-def parse(source, extra_vars=None, *, filename=None, track_span: bool = True, **options):
+def parse(
+ source: str | FunctionType | type,
+ extra_vars: Mapping[str, Any] | None = None,
+ *,
+ filename: str | None = None,
+ track_span: bool = True,
+ **options: Any,
+) -> Any:
"""Transpile and execute a source string, Python function, or Python class.
Parameters
@@ -788,7 +918,7 @@ def parse(source, extra_vars=None, *, filename=None, track_span: bool = True, **
raise diagnostic_error(error, filename, tree) from error
-def _check_well_formed(result):
+def _check_well_formed(result: object) -> None:
"""Apply the public entry point's default validation to constructed IR."""
from tvm import ir, relax, s_tir, tirx
@@ -814,13 +944,13 @@ def _check_well_formed(result):
class _PyModuleFactory:
"""Keep executable Python attachments on each fresh module instance."""
- def __init__(self, module, original_class):
- self.ir_module = module
- self.original_class = original_class
- self.pyfunc_methods = list(getattr(module, "pyfuncs", {}))
- self.__name__ = original_class.__name__
+ def __init__(self, module: IRModule, original_class: type) -> None:
+ self.ir_module: IRModule = module
+ self.original_class: type = original_class
+ self.pyfunc_methods: list[str] = list(getattr(module, "pyfuncs", {}))
+ self.__name__: str = original_class.__name__
- def __call__(self, device=None, target=None):
+ def __call__(self, device: Device | None = None, target: Target | None = None) -> BasePyModule:
from tvm import cpu, ir
from tvm.relax.base_py_module import BasePyModule
@@ -833,11 +963,13 @@ class _PyModuleFactory:
instance.add_python_function(name, getattr(self.original_class, name))
return instance
- def __getattr__(self, name):
+ def __getattr__(self, name: str) -> Any:
return getattr(self.ir_module, name)
-def ir_module(module=None, **options):
+def ir_module(
+ module: type | None = None, **options: Any
+) -> IRModule | _PyModuleFactory | Callable[[type], IRModule | _PyModuleFactory]:
"""Decorate a Python class with two-phase module construction.
Parameters
@@ -866,7 +998,7 @@ def ir_module(module=None, **options):
acquisition errors and frame lifetime follow `parse`.
"""
- def apply(module):
+ def apply(module: type) -> IRModule | _PyModuleFactory:
if not inspect.isclass(module):
raise TypeError(f"Expect a class, but got: {module}")
frame = inspect.currentframe().f_back
diff --git a/python/tvm/script/parser/jit_support.py b/python/tvm/script/parser/jit_support.py
index 200bec2758..96609b72e0 100644
--- a/python/tvm/script/parser/jit_support.py
+++ b/python/tvm/script/parser/jit_support.py
@@ -22,16 +22,27 @@ values after nested parsing or an exception. Native builder frames own no JIT
state, and ordinary parsing does not import the TIRx JIT entry point.
"""
+from __future__ import annotations
+
+from collections.abc import Iterator, Mapping
from contextlib import contextmanager
from contextvars import ContextVar
+from typing import Any, TypeVar
# Per-execution inputs, never a second owner of native function or parameter state.
-_SPECIALIZATION = ContextVar("tvm_parser_specialization", default=None)
-_ABSENT_PARAMETERS = ContextVar("tvm_parser_absent_parameters", default=None)
+_Value = TypeVar("_Value")
+
+# Host/JIT values and callable annotation adapters have open-ended Python types.
+_SPECIALIZATION: ContextVar[tuple[str | None, dict[str, Any]] | None] = ContextVar(
+ "tvm_parser_specialization", default=None
+)
+_ABSENT_PARAMETERS: ContextVar[tuple[str | None, dict[str, None]] | None] = ContextVar(
+ "tvm_parser_absent_parameters", default=None
+)
@contextmanager
-def specialization_context(name, bindings):
+def specialization_context(name: str | None, bindings: Mapping[str, Any] | None) -> Iterator[None]:
"""Pass selected JIT bindings to one root builder execution.
``None`` denotes ordinary parsing; an empty mapping is a specialization
@@ -46,7 +57,7 @@ def specialization_context(name, bindings):
@contextmanager
-def absent_parameters(name, parameters):
+def absent_parameters(name: str | None, parameters: Mapping[str, None] | None) -> Iterator[None]:
"""Transport explicitly absent root parameters while preserving None.
The legacy entry input maps each selected parameter name to None. No
@@ -62,19 +73,19 @@ def absent_parameters(name, parameters):
_ABSENT_PARAMETERS.reset(token)
-def specialization_bindings(name):
+def specialization_bindings(name: str) -> dict[str, Any] | None:
"""Read the current root's bindings, or None outside specialization."""
context = _SPECIALIZATION.get()
return context[1] if context is not None and context[0] == name else None
-def absent_parameter_names(name):
+def absent_parameter_names(name: str) -> frozenset[str]:
"""Read explicit root absences without treating missing bindings as None."""
context = _ABSENT_PARAMETERS.get()
return frozenset(context[1]) if context is not None and context[0] == name else frozenset()
-def unwrap_annotation(annotation, specialization):
+def unwrap_annotation(annotation: Any, specialization: Mapping[str, Any] | None) -> Any:
"""Read an optional runtime annotation only within a JIT specialization.
Generated argument construction calls this after checking selected values
@@ -88,7 +99,7 @@ def unwrap_annotation(annotation, specialization):
return annotation
-def constexpr_binding(value, name):
+def constexpr_binding(value: _Value, name: str) -> _Value:
"""Require an explicit captured value for a constexpr parameter."""
from tvm.script.ir_builder.base import MISSING
diff --git a/python/tvm/script/parser/prescan.py b/python/tvm/script/parser/prescan.py
index 6d7238d9e5..07b909eddf 100644
--- a/python/tvm/script/parser/prescan.py
+++ b/python/tvm/script/parser/prescan.py
@@ -16,16 +16,20 @@
# under the License.
"""One syntax prescan for generated names, declarations and region outputs."""
+from __future__ import annotations
+
import ast
import builtins
import inspect
+from collections.abc import Mapping
from dataclasses import dataclass
from types import GetSetDescriptorType, MappingProxyType, MemberDescriptorType
+from typing import NoReturn
from . import protocol
-def resolve_syntax(node, environment):
+def resolve_syntax(node: ast.AST | None, environment: Mapping[str, object]) -> object:
"""Read fixed namespace metadata without executing source descriptors."""
if isinstance(node, ast.Name):
return environment.get(node.id, getattr(builtins, node.id, None))
@@ -55,11 +59,11 @@ class Binding:
name: str
node: ast.AST
kind: str
- annotation: ast.AST | None = None
+ annotation: ast.expr | None = None
dtype: object = None
direct: bool = False
# Original callee root; assignment dispatch checks completed lexical bindings.
- declaration_root: ast.Name | None = None
+ declaration_root: ast.expr | None = None
@dataclass(frozen=True)
@@ -73,45 +77,45 @@ class PrescanContext:
``conditional_outputs`` supplies the one explicit native-frame result name.
"""
- reserved_names: frozenset
- bindings: object
- sites: object
- mutable_names: object
- conditional_outputs: object
- namespaces: frozenset
+ reserved_names: frozenset[str]
+ bindings: Mapping[ast.AST | None, tuple[Binding, ...]]
+ sites: Mapping[ast.AST, Binding]
+ mutable_names: Mapping[ast.AST | None, frozenset[str]]
+ conditional_outputs: Mapping[ast.stmt, str]
+ namespaces: frozenset[str]
# Explicit source dataflow outputs preserve native export identity on exit.
- with_outputs: object
+ with_outputs: Mapping[ast.With, tuple[str, ...]]
# Only source functions referencing themselves need early standalone refs.
- recursive_functions: frozenset
+ recursive_functions: frozenset[ast.FunctionDef | ast.AsyncFunctionDef]
class PrescanCollector(ast.NodeVisitor):
"""Collect binding syntax once, then discard all traversal accumulators."""
- def __init__(self, environment, *, filename="<str>"):
+ def __init__(self, environment: Mapping[str, object], *, filename: str = "<str>") -> None:
# Fixed lookup inputs last for this scan; never updated by assignments.
- self.environment = environment
- self.filename = filename
+ self.environment: Mapping[str, object] = environment
+ self.filename: str = filename
# Accumulators are frozen by collect(); no native values are stored.
- self.names = set(environment)
- self.bindings = {}
- self.sites = {}
- self.outputs = {}
- self.namespaces = set()
- self.exports = {}
- self.recursive = set()
+ self.names: set[str] = set(environment)
+ self.bindings: dict[ast.AST | None, list[Binding]] = {}
+ self.sites: dict[ast.AST, Binding] = {}
+ self.outputs: dict[ast.stmt, str] = {}
+ self.namespaces: set[str] = set()
+ self.exports: dict[ast.With, list[str]] = {}
+ self.recursive: set[ast.FunctionDef | ast.AsyncFunctionDef] = set()
# Active source declarations, used only to recognize self references.
- self.functions = []
- self.module_name = None
+ self.functions: list[ast.FunctionDef | ast.AsyncFunctionDef] = []
+ self.module_name: str | None = None
# Temporary lexical with-stack routes explicit output calls, then resets.
- self.regions = []
+ self.regions: list[ast.With] = []
# Lexical scope and dialect restore on function/class exit. direct marks
# unconditional function-body declarations eligible before signatures.
- self.scope = None
- self.builder = None
- self.direct = False
+ self.scope: ast.Module | ast.ClassDef | ast.FunctionDef | ast.AsyncFunctionDef | None = None
+ self.builder: object = None
+ self.direct: bool = False
- def collect(self, tree):
+ def collect(self, tree: ast.Module) -> PrescanContext:
"""Scan the owned tree and return immutable facts for its rewrite."""
# Decorator roots establish namespace meaning for this translation.
for node in ast.walk(tree):
@@ -152,12 +156,19 @@ class PrescanCollector(ast.NodeVisitor):
frozenset(self.recursive),
)
- def _error(self, node, message):
+ def _error(self, node: ast.AST, message: str) -> NoReturn:
raise SyntaxError(message, (self.filename, node.lineno, node.col_offset + 1, None))
def _binding(
- self, name, node, kind="ordinary", annotation=None, dtype=None, *, declaration_root=None
- ):
+ self,
+ name: str,
+ node: ast.AST,
+ kind: str = "ordinary",
+ annotation: ast.expr | None = None,
+ dtype: object = None,
+ *,
+ declaration_root: ast.expr | None = None,
+ ) -> None:
if name in self.namespaces:
self._error(node, f"Script namespace {name!r} cannot be rebound or shadowed")
self.names.add(name)
@@ -165,7 +176,7 @@ class PrescanCollector(ast.NodeVisitor):
self.bindings[self.scope].append(item)
self.sites[node] = item
- def visit_Name(self, node):
+ def visit_Name(self, node: ast.Name) -> None:
if isinstance(node.ctx, ast.Store) and node.id in self.namespaces:
self._error(node, f"Script namespace {node.id!r} cannot be rebound or shadowed")
self.names.add(node.id)
@@ -175,19 +186,19 @@ class PrescanCollector(ast.NodeVisitor):
self.recursive.add(function)
break
- def visit_arg(self, node):
+ def visit_arg(self, node: ast.arg) -> None:
if node.arg in self.namespaces:
self._error(node, f"Script namespace {node.arg!r} cannot be rebound or shadowed")
self.names.add(node.arg)
self.generic_visit(node)
- def visit_alias(self, node):
+ def visit_alias(self, node: ast.alias) -> None:
name = node.asname or node.name.split(".")[0]
if isinstance(self.scope, ast.FunctionDef) and name in self.namespaces:
self._error(node, f"Script namespace {name!r} cannot be rebound or shadowed")
self.names.add(name)
- def visit_ClassDef(self, node):
+ def visit_ClassDef(self, node: ast.ClassDef) -> None:
self.names.add(node.name)
old, old_module = self.scope, self.module_name
self.scope, self.module_name = node, node.name
@@ -195,7 +206,7 @@ class PrescanCollector(ast.NodeVisitor):
self.generic_visit(node)
self.scope, self.module_name = old, old_module
- def visit_FunctionDef(self, node):
+ def visit_FunctionDef(self, node: ast.FunctionDef | ast.AsyncFunctionDef) -> None:
self._binding(node.name, node, "function")
old_scope, old_builder, old_direct = self.scope, self.builder, self.direct
self.scope, self.direct = node, True
@@ -245,7 +256,14 @@ class PrescanCollector(ast.NodeVisitor):
visit_AsyncFunctionDef = visit_FunctionDef
- def _target(self, target, value=None, annotation=None, *, binding_declaration=None):
+ def _target(
+ self,
+ target: ast.expr,
+ value: ast.expr | None = None,
+ annotation: ast.expr | None = None,
+ *,
+ binding_declaration: ast.expr | None = None,
+ ) -> None:
constructor = (
resolve_syntax(value.func, self.environment) if isinstance(value, ast.Call) else None
)
@@ -298,18 +316,18 @@ class PrescanCollector(ast.NodeVisitor):
self._target(target.value, binding_declaration=binding_declaration)
self.visit(target)
- def visit_Assign(self, node):
+ def visit_Assign(self, node: ast.Assign) -> None:
for target in node.targets:
self._target(target, node.value)
self.visit(node.value)
- def visit_AnnAssign(self, node):
+ def visit_AnnAssign(self, node: ast.AnnAssign) -> None:
self._target(node.target, node.value, node.annotation)
self.visit(node.annotation)
if node.value:
self.visit(node.value)
- def visit_If(self, node):
+ def visit_If(self, node: ast.If) -> None:
old_direct, self.direct = self.direct, False
self.generic_visit(node)
marker = (
@@ -319,7 +337,7 @@ class PrescanCollector(ast.NodeVisitor):
)
if not marker and getattr(self.builder, "__tvm_value_if__", False):
- def ending(body):
+ def ending(body: list[ast.stmt]) -> str | None:
last = body[-1] if body else None
if (
isinstance(last, ast.Assign)
@@ -349,7 +367,7 @@ class PrescanCollector(ast.NodeVisitor):
self.outputs[node] = then
self.direct = old_direct
- def visit_For(self, node):
+ def visit_For(self, node: ast.For) -> None:
old_direct, self.direct = self.direct, False
self._target(node.target)
self.visit(node.iter)
@@ -357,12 +375,12 @@ class PrescanCollector(ast.NodeVisitor):
self.visit(statement)
self.direct = old_direct
- def visit_While(self, node):
+ def visit_While(self, node: ast.While) -> None:
old_direct, self.direct = self.direct, False
self.generic_visit(node)
self.direct = old_direct
- def visit_With(self, node):
+ def visit_With(self, node: ast.With) -> None:
old_direct, self.direct = self.direct, False
self.regions.append(node)
for item in node.items:
@@ -374,7 +392,7 @@ class PrescanCollector(ast.NodeVisitor):
self.regions.pop()
self.direct = old_direct
- def visit_Call(self, node):
+ def visit_Call(self, node: ast.Call) -> None:
if self.regions and isinstance(node.func, ast.Attribute) and node.func.attr == "output":
output = getattr(self.builder, "output", None)
if output is not None and resolve_syntax(node.func, self.environment) is output:
diff --git a/python/tvm/script/parser/protocol.py b/python/tvm/script/parser/protocol.py
index 6213967141..5c2a281e37 100644
--- a/python/tvm/script/parser/protocol.py
+++ b/python/tvm/script/parser/protocol.py
@@ -21,13 +21,17 @@ Concrete eager annotation behavior is delegated to a builder-owned adapter;
no IR definition, concrete annotation result, symbol or frame is stored here.
"""
-from collections.abc import Mapping
+from __future__ import annotations
+
+from collections.abc import Callable, Mapping
from inspect import signature
-from types import MappingProxyType
-from typing import Any, NamedTuple
+from types import MappingProxyType, MethodType
+from typing import Any, NamedTuple, NoReturn, TypeVar
+
+_Callable = TypeVar("_Callable", bound=Callable[..., Any])
-def constexpr(value):
+def constexpr(value: object) -> NoReturn:
"""Mark a host control value in source syntax; consumed by the transpiler.
The same callable may annotate a JIT specialization parameter. Generated
@@ -36,7 +40,7 @@ def constexpr(value):
raise TypeError("constexpr is a parser syntax marker, not a runtime operation")
-def is_constexpr_marker(value):
+def is_constexpr_marker(value: object) -> bool:
"""Recognize the shared marker by identity without inspecting host values."""
return value is constexpr
@@ -48,15 +52,11 @@ class ExprStrPolicy(NamedTuple):
----------
fields : tuple of str
Parameter names whose string values represent expressions.
- introduce : bool, optional
- Legacy symbol-introduction metadata. Default is False.
dtype : object, optional
Dtype spelling passed to builder symbol resolution. Default is None.
scalar_strings : bool, optional
Interpret bare strings as expressions. Default is True. Nested
strings in marked fields are always treated as expressions.
- compound_declarations : bool, optional
- Legacy compound-expression metadata. Default is False.
Notes
-----
@@ -68,16 +68,14 @@ class ExprStrPolicy(NamedTuple):
"""
fields: tuple[str, ...]
- introduce: bool = False
- dtype: Any = None
+ dtype: object = None
scalar_strings: bool = True
- compound_declarations: bool = False
# Process-wide registry: callable identity -> immutable syntax policy. Dialect
# imports register once; aliases share identities. No per-function entries or
# evaluation results are cached, and transpilers only read this table.
-_ARGS_POLICIES = {}
+_ARGS_POLICIES: dict[object, ArgsPolicy] = {}
class ArgsPolicy(NamedTuple):
@@ -87,25 +85,26 @@ class ArgsPolicy(NamedTuple):
expression: ExprStrPolicy
-def get_args_policy(constructor):
- """Return registered argument policies without evaluating the constructor.
+def get_args_policy(constructor: object) -> ArgsPolicy | None:
+ """Read a registered policy without evaluating the constructor.
- Legacy attached expression metadata is read without changing its owner.
Unregistered and unhashable host values have no argument policy.
"""
+ if isinstance(constructor, MethodType):
+ constructor = constructor.__func__
try:
- policy = _ARGS_POLICIES.get(constructor)
+ return _ARGS_POLICIES.get(constructor)
except TypeError:
return None
- if policy is not None:
- return policy
- expression = getattr(constructor, "__tvm_expression_args__", None)
- if expression is None:
- return None
- return ArgsPolicy(MappingProxyType(dict.fromkeys(expression.fields, "expr_str")), expression)
-def args_policy(fields, *, scalar_strings=True, as_type=False):
+def args_policy(
+ fields: Mapping[str, str],
+ *,
+ scalar_strings: bool = True,
+ dtype: object = None,
+ as_type: bool = False,
+) -> Callable[[Callable[..., Any]], Callable[..., Any]]:
"""Register ``expr_str`` and ``global_info`` policies by parameter name.
Expression strings are rewritten as expressions; global-info arguments
@@ -118,7 +117,26 @@ def args_policy(fields, *, scalar_strings=True, as_type=False):
(such as ``Tensor("float32")``), while nested shape strings are expressions.
Builders own the eager expression adapter: unresolved annotations outside
builder scope return MissingType, and concrete arguments construct normally.
- ``as_type=True`` preserves the Python annotation-class surface.
+ ``dtype`` is opaque syntax metadata forwarded to builder symbol resolution;
+ its default of None leaves the dtype choice to the builder.
+ ``as_type=True`` preserves the Python annotation-class surface, including
+ Python type unions; construction still returns the wrapped callable's result.
+
+ Both original and wrapped callable identities share the registered policy,
+ including bound methods. Concrete arguments call the original constructor.
+ Outside a builder, marked strings and ``typing.TypeVar`` values return
+ MissingType. Inside a builder, TypeVar values resolve through the current
+ function frame and unresolved expression strings raise TypeError. Calls and
+ annotation results are never cached; annotations must be safe to re-evaluate.
+
+ Raises
+ ------
+ ValueError
+ If a policy kind or parameter name is unknown, or the constructor's
+ signature cannot be inspected.
+ TypeError
+ If the constructor cannot be inspected, a wrapped call cannot bind its
+ signature, or expression strings remain unresolved inside a builder.
Examples
--------
@@ -134,19 +152,22 @@ def args_policy(fields, *, scalar_strings=True, as_type=False):
if unsupported:
raise ValueError(f"Unknown argument policies: {sorted(unsupported)}")
- def decorate(constructor):
- unknown = set(fields).difference(signature(constructor).parameters)
+ def decorate(constructor: Callable[..., Any]) -> Callable[..., Any]:
+ call_signature = signature(constructor)
+ unknown = set(fields).difference(call_signature.parameters)
if unknown:
raise ValueError(f"Unknown argument policy fields: {sorted(unknown)}")
expression_fields = tuple(name for name, kind in fields.items() if kind == "expr_str")
+ expression = ExprStrPolicy(expression_fields, dtype, bool(scalar_strings))
if expression_fields or as_type:
- result = expr_str_args(
- *expression_fields, scalar_strings=scalar_strings, as_type=as_type
- )(constructor)
- expression = expr_str_policy(result)
+ # Builders own eager construction and active-frame/MissingType decisions.
+ from tvm.script.ir_builder.base import wrap_expression_constructor
+
+ result = wrap_expression_constructor(
+ constructor, call_signature, expression, as_type=as_type
+ )
else:
result = constructor
- expression = ExprStrPolicy((), scalar_strings=scalar_strings)
policy = ArgsPolicy(MappingProxyType(fields.copy()), expression)
_ARGS_POLICIES[constructor] = policy
_ARGS_POLICIES[result] = policy
@@ -155,118 +176,6 @@ def args_policy(fields, *, scalar_strings=True, as_type=False):
return decorate
-def expr_str_policy(constructor):
- """Look up the expression-string policy for a host value.
-
- Parameters
- ----------
- constructor : object
- Python value whose registration or attached policy is queried.
-
- Returns
- -------
- ExprStrPolicy or None
- Registered or attached policy, or None if unregistered or unhashable.
- Legacy attached policies may use the equivalent legacy record type.
-
- Notes
- -----
- This read-only lookup neither imports dialects nor calls the constructor.
- Returned policies are shared registration state; no builder frame is
- entered. Exceptions from custom attribute access propagate.
- """
- policy = get_args_policy(constructor)
- return policy.expression if policy is not None else None
-
-
-def expr_str_args(
- *fields,
- introduce=False,
- dtype=None,
- scalar_strings=True,
- compound_declarations=False,
- as_type=False,
-):
- """Register expression-string fields and wrap eager constructor calls.
-
- Parameters
- ----------
- *fields : str
- Parameter names whose string values denote source expressions.
- introduce : bool, optional
- Legacy syntax metadata. Default is False; builders own introduction.
- dtype : object, optional
- Dtype spelling passed to builder symbol resolution. Default is None.
- scalar_strings : bool, optional
- Interpret bare strings as expressions. Default is True. False
- preserves literal shorthand such as ``Tensor("float32")``; nested
- strings in tuples and lists remain expressions.
- compound_declarations : bool, optional
- Legacy compound-expression metadata. Default is False.
- as_type : bool, optional
- Preserve use as an annotation class, including Python type unions.
- Default is False. True returns a class invoking the wrapped callable;
- construction still returns that callable's result.
-
- Returns
- -------
- decorator : callable
- Registers the constructor's policy and returns its eager-call adapter.
-
- Raises
- ------
- ValueError
- When applying the decorator to a constructor whose signature cannot
- be inspected or does not contain a requested field.
- TypeError
- When the constructor cannot be inspected, or a wrapped call cannot
- bind its signature or has unresolved fields inside an active builder.
-
- Notes
- -----
- Both original and wrapped callable identities retain the policy in the
- process-wide registry. Builders own eager annotation behavior: unresolved
- strings or typing.TypeVar values in marked fields produce MissingType
- outside active builders. Concrete arguments call the original constructor.
- Handwritten builders require concrete expressions. Calls are never cached;
- annotations must be safe to re-evaluate.
-
- Examples
- --------
- Register a shape parameter while leaving the dtype string literal intact::
-
- @expr_str_args("shape", scalar_strings=False)
- def tensor_type(shape, dtype="float32"):
- return make_tensor_type(shape, dtype)
- """
-
- def decorate(constructor):
- call_signature = signature(constructor)
- unknown = set(fields).difference(call_signature.parameters)
- if unknown:
- raise ValueError(f"Unknown expression argument fields: {sorted(unknown)}")
- policy = ExprStrPolicy(
- tuple(fields),
- bool(introduce),
- dtype,
- bool(scalar_strings),
- bool(compound_declarations),
- )
-
- # Registration is syntax-only. Builders own eager construction and the
- # active-frame/MissingType decisions behind this generic wrapper factory.
- from tvm.script.ir_builder.base import wrap_expression_constructor
-
- result = wrap_expression_constructor(constructor, call_signature, policy, as_type=as_type)
- result.__tvm_expression_args__ = policy
- arguments = ArgsPolicy(MappingProxyType(dict.fromkeys(fields, "expr_str")), policy)
- _ARGS_POLICIES[result] = arguments
- _ARGS_POLICIES[constructor] = arguments
- return result
-
- return decorate
-
-
class DeclarationArguments(NamedTuple):
"""Immutable metadata for scalar-constructor predeclarations.
@@ -285,10 +194,12 @@ class DeclarationArguments(NamedTuple):
"""
value_parameter: str
- dtype: Any = None
+ dtype: object = None
-def register_type_var_decl(constructor, *, value_parameter="expr", dtype=None):
+def register_type_var_decl(
+ constructor: _Callable, *, value_parameter: str = "expr", dtype: object = None
+) -> _Callable:
"""Register a constructor that can declare a type variable.
Parameters
@@ -328,7 +239,7 @@ def register_type_var_decl(constructor, *, value_parameter="expr", dtype=None):
return constructor
-def register_binding_decl(constructor):
+def register_binding_decl(constructor: _Callable) -> _Callable:
"""Mark a call that explicitly introduces an ordinary source binding.
Its scalar or unpacked targets bind the returned values even when an outer
@@ -340,7 +251,7 @@ def register_binding_decl(constructor):
return constructor
-def register_mutable_var_decl(constructor, *, syntax="call"):
+def register_mutable_var_decl(constructor: _Callable, *, syntax: str = "call") -> _Callable:
"""Register mutable storage in call, annotation or parameter position.
The immutable syntax set belongs to the callable across translations. It
@@ -348,12 +259,12 @@ def register_mutable_var_decl(constructor, *, syntax="call"):
"""
if syntax not in ("call", "annotation", "parameter"):
raise ValueError("Mutable declaration syntax must be call, annotation or parameter")
- kinds = getattr(constructor, "__tvm_mutable_var_decl__", frozenset())
+ kinds: frozenset[str] = getattr(constructor, "__tvm_mutable_var_decl__", frozenset())
constructor.__tvm_mutable_var_decl__ = kinds | frozenset((syntax,))
return constructor
-def is_mutable_var_decl(constructor, *, syntax):
+def is_mutable_var_decl(constructor: object, *, syntax: str) -> bool:
"""Read a registered mutable declaration without evaluating source values."""
return syntax in getattr(constructor, "__tvm_mutable_var_decl__", ())
@@ -382,13 +293,20 @@ class FunctionDecoratorInfo(NamedTuple):
result, annotation result, or symbol state and enter no builder frames.
"""
- builder: Any
- option_map: dict | None = None
- defaults: dict | None = None
+ builder: object
+ option_map: dict[str, str] | None = None
+ defaults: dict[str, Any] | None = None
python: bool = False
-def register_function(decorator, builder, *, option_map=None, defaults=None, python=False):
+def register_function(
+ decorator: _Callable,
+ builder: object,
+ *,
+ option_map: Mapping[str, str] | None = None,
+ defaults: Mapping[str, Any] | None = None,
+ python: bool = False,
+) -> _Callable:
"""Register a decorator with explicit supported syntax options.
Parameters
@@ -430,7 +348,7 @@ def register_function(decorator, builder, *, option_map=None, defaults=None, pyt
return decorator
-def function_info(decorator):
+def function_info(decorator: object) -> FunctionDecoratorInfo | None:
"""Read registered construction metadata without calling the decorator.
The returned option mappings are shared registration state. This lookup
diff --git a/python/tvm/script/parser/source.py b/python/tvm/script/parser/source.py
index 730f52f5cf..b035a09851 100644
--- a/python/tvm/script/parser/source.py
+++ b/python/tvm/script/parser/source.py
@@ -15,11 +15,16 @@
# specific language governing permissions and limitations
# under the License.
"""Source text and canonical one-based IR coordinates."""
+
+from __future__ import annotations
+
import ast
import inspect
+from types import FunctionType
from tvm.ir import SourceName, Span
+
class Source:
"""Source code class for TVMScript.
@@ -43,13 +48,13 @@ class Source:
The complete source code of the file where the source code locates.
"""
- source_name: str
+ source_name: str | None
start_line: int
start_column: int
source: str
full_source: str
- def __init__(self, program: str | ast.AST):
+ def __init__(self, program: str | FunctionType | type) -> None:
if isinstance(program, str):
self.source_name = "<str>"
self.start_line = 1
@@ -65,7 +70,7 @@ class Source:
else:
self.start_column = 0
if self.start_column and lines:
- self.source = "\n".join([l[self.start_column :].rstrip() for l in lines])
+ self.source = "\n".join([line[self.start_column :].rstrip() for line in lines])
else:
self.source = "".join(lines)
try:
@@ -84,7 +89,7 @@ class Source:
src, _ = inspect.findsource(program) # type: ignore
self.full_source = "".join(src)
- def as_ast(self) -> ast.AST:
+ def as_ast(self) -> ast.Module:
"""Parse the source code into AST.
Returns
@@ -118,4 +123,3 @@ class Source:
col_offset,
end_col_offset,
)
-
diff --git a/python/tvm/script/parser/transpile.py b/python/tvm/script/parser/transpile.py
index cfd4733438..9ae715526b 100644
--- a/python/tvm/script/parser/transpile.py
+++ b/python/tvm/script/parser/transpile.py
@@ -21,13 +21,19 @@ inputs, generated-name allocation and a small lexical rewrite context. Native
frames own symbols, declarations, parameters, region results and final IR.
"""
+from __future__ import annotations
+
import ast
import builtins
+from collections.abc import Callable, Iterator, Mapping
from contextlib import contextmanager
+from typing import Any, NoReturn, TypeVar
from . import protocol
from .call_args_policy import handle_call_args_policy, parse_annotation
-from .prescan import resolve_syntax
+from .prescan import PrescanContext, resolve_syntax
+
+_Node = TypeVar("_Node", bound=ast.AST)
class IRBuilderTranspiler(ast.NodeTransformer):
@@ -43,51 +49,53 @@ class IRBuilderTranspiler(ast.NodeTransformer):
def __init__(
self,
- filename,
- environment,
- builder_name,
- infrastructure_name,
- span,
- fresh,
+ filename: str,
+ environment: Mapping[str, object],
+ builder_name: str,
+ infrastructure_name: str,
+ span: Callable[[ast.AST], ast.expr],
+ fresh: Callable[[str], str],
*,
- prescan=None,
- track_span=True,
- definition_scopes_name=None,
- current_scope=None,
- bindings=None,
- preserve_return=False,
- ):
+ prescan: PrescanContext | None = None,
+ track_span: bool = True,
+ definition_scopes_name: str | None = None,
+ current_scope: ast.AST | None = None,
+ bindings: dict[str, Any] | None = None,
+ preserve_return: bool = False,
+ ) -> None:
# Read-only translation inputs; namespace meanings never change in flow.
- self.filename = filename
- self.environment = environment
- self.prescan = prescan
- self.infrastructure_name = infrastructure_name
- self.span = span
- self.track_span = track_span
- self.definition_scopes_name = definition_scopes_name
+ self.filename: str = filename
+ self.environment: Mapping[str, object] = environment
+ self.prescan: PrescanContext | None = prescan
+ self.infrastructure_name: str = infrastructure_name
+ self.span: Callable[[ast.AST], ast.expr] = span
+ self.track_span: bool = track_span
+ self.definition_scopes_name: str | None = definition_scopes_name
# Allocation/injection last for this source unit, including nested code.
- self.fresh = fresh
- self.bindings = bindings if bindings is not None else {}
+ self.fresh: Callable[[str], str] = fresh
+ self.bindings: dict[str, Any] = bindings if bindings is not None else {}
# Lexical syntax context, restored on nested function/host/annotation exit.
- self.dialect_prefix = builder_name
- self.current_scope = current_scope
- self.host_expression = False
- self.preserve_return = preserve_return
- self.annotation_aliases = {}
+ self.dialect_prefix: str = builder_name
+ self.current_scope: ast.AST | None = current_scope
+ self.host_expression: bool = False
+ self.preserve_return: bool = preserve_return
+ self.annotation_aliases: dict[str, str] = {}
# Annotation-only aliases in the current body; reset at function exit.
- self.body_annotation_aliases = {}
- self.module_name = None
- self.module_functions = frozenset()
+ self.body_annotation_aliases: dict[str, str] = {}
+ self.module_name: str | None = None
+ self.module_functions: frozenset[str] = frozenset()
- def _inject(self, value, prefix="_host"):
+ def _inject(self, value: object, prefix: str = "_host") -> ast.Name:
name = self.fresh(prefix)
self.bindings[name] = value
return ast.Name(name, ast.Load())
- def _error(self, node, message):
+ def _error(self, node: ast.AST, message: str) -> NoReturn:
raise SyntaxError(message, (self.filename, node.lineno, node.col_offset + 1, None))
- def _call(self, namespace, member, args, node, **keywords):
+ def _call(
+ self, namespace: str, member: str, args: list[ast.expr], node: ast.AST, **keywords: ast.expr
+ ) -> ast.Call:
"""Build a generated operation with its source range and named arguments."""
if not self.track_span:
keywords.pop("span", None)
@@ -101,16 +109,18 @@ class IRBuilderTranspiler(ast.NodeTransformer):
node,
)
- def _operation(self, member, args, node, **keywords):
+ def _operation(
+ self, member: str, args: list[ast.expr], node: ast.AST, **keywords: ast.expr
+ ) -> ast.Call:
return self._call(self.dialect_prefix, member, args, node, span=self.span(node), **keywords)
- def _at(self, value, node):
+ def _at(self, value: ast.expr, node: ast.AST) -> ast.expr:
if not self.track_span:
return value
return self._call(self.infrastructure_name, "at_", [self.span(node), value], node)
@staticmethod
- def _lambda(names, value):
+ def _lambda(names: list[str], value: ast.expr) -> ast.Lambda:
return ast.Lambda(
ast.arguments(
posonlyargs=[],
@@ -123,7 +133,9 @@ class IRBuilderTranspiler(ast.NodeTransformer):
)
@staticmethod
- def _definition(name, parameters, body, node):
+ def _definition(
+ name: str, parameters: list[str], body: list[ast.stmt], node: ast.AST
+ ) -> ast.FunctionDef:
definition = ast.copy_location(
ast.FunctionDef(
name,
@@ -144,7 +156,7 @@ class IRBuilderTranspiler(ast.NodeTransformer):
definition.type_params = []
return definition
- def transform_statements(self, body):
+ def transform_statements(self, body: list[ast.stmt]) -> list[ast.stmt]:
"""Visit source statements once, flattening statement-list rewrites."""
result = []
for statement in body:
@@ -154,7 +166,7 @@ class IRBuilderTranspiler(ast.NodeTransformer):
return result
@contextmanager
- def _host(self):
+ def _host(self) -> Iterator[None]:
# Only constexpr operands and module host syntax keep Python operators.
# The same visitor still instruments their source calls and restores mode.
old = self.host_expression
@@ -164,7 +176,7 @@ class IRBuilderTranspiler(ast.NodeTransformer):
finally:
self.host_expression = old
- def _resolve(self, node):
+ def _resolve(self, node: ast.AST | None) -> object:
# Fixed namespace meanings coexist with Python lexical value bindings.
# A local ``range`` or callable hides the ambient binding for the whole
# source function, including reads before its assignment.
@@ -186,7 +198,7 @@ class IRBuilderTranspiler(ast.NodeTransformer):
)
return resolve_syntax(node, self.environment)
- def _constexpr_operand(self, node):
+ def _constexpr_operand(self, node: ast.expr) -> ast.expr | None:
# Source: I.constexpr(expr), X.constexpr(expr)
# Builder: expr under the visitor's host-expression context.
if not isinstance(node, ast.Call) or not isinstance(node.func, ast.Attribute):
@@ -199,7 +211,7 @@ class IRBuilderTranspiler(ast.NodeTransformer):
self._error(node, "constexpr expects exactly one controlling value")
return node.args[0]
- def visit_Name(self, node):
+ def visit_Name(self, node: ast.Name) -> ast.expr:
# Source: "n" in a marked expression argument
# Builder: X.resolve_type_var_("n") without a Python binding.
if hasattr(node, "_tvm_quoted_symbol"):
@@ -241,7 +253,7 @@ class IRBuilderTranspiler(ast.NodeTransformer):
else node
)
- def visit_Attribute(self, node):
+ def visit_Attribute(self, node: ast.Attribute) -> ast.expr:
# A normalized protocol callee is already builder syntax, with no source
# child expressions to transform or locations to invent.
if getattr(node, "_tvm_intrinsic", False):
@@ -255,7 +267,7 @@ class IRBuilderTranspiler(ast.NodeTransformer):
else result
)
- def visit_Lambda(self, node):
+ def visit_Lambda(self, node: ast.Lambda) -> ast.Lambda:
# Source: lambda n: n + outer; Builder: preserve the lambda's locals
# while real annotation-only outer reads use their definition aliases.
node.args.defaults = [self.visit(value) for value in node.args.defaults]
@@ -273,7 +285,9 @@ class IRBuilderTranspiler(ast.NodeTransformer):
self.annotation_aliases = old
return node
- def visit_ListComp(self, node):
+ def visit_ListComp(
+ self, node: ast.ListComp | ast.SetComp | ast.DictComp | ast.GeneratorExp
+ ) -> ast.ListComp | ast.SetComp | ast.DictComp | ast.GeneratorExp:
# Source: [f(n) for n in values]; Builder: preserve Python comprehension
# scope while translating its call/operand expressions exactly once.
old = self.annotation_aliases
@@ -295,11 +309,11 @@ class IRBuilderTranspiler(ast.NodeTransformer):
visit_DictComp = visit_ListComp
visit_GeneratorExp = visit_ListComp
- def visit_Constant(self, node):
+ def visit_Constant(self, node: ast.Constant) -> ast.expr:
# Source: literal; Builder: I.at_(literal_loc, literal).
return node if self.host_expression else self._at(node, node)
- def visit_List(self, node):
+ def visit_List(self, node: ast.List | ast.Tuple | ast.Set | ast.Dict) -> ast.expr:
# Source: [a,b] / (a,b) / {a,b}; Builder: preserve the Python container
# and source-location every original child through this same visitor.
result = self.generic_visit(node)
@@ -309,7 +323,7 @@ class IRBuilderTranspiler(ast.NodeTransformer):
visit_Set = visit_List
visit_Dict = visit_List
- def visit_JoinedStr(self, node):
+ def visit_JoinedStr(self, node: ast.JoinedStr) -> ast.JoinedStr:
# Source: f"value={expr}"; Builder: keep literal fragments, visit expr.
# Python requires these fragments to remain Constant/FormattedValue.
for child in node.values:
@@ -319,14 +333,14 @@ class IRBuilderTranspiler(ast.NodeTransformer):
child.format_spec = self.visit_JoinedStr(child.format_spec)
return node
- def visit_Subscript(self, node):
+ def visit_Subscript(self, node: ast.Subscript) -> ast.expr:
# Source: buffer[index]; Builder: I.at_(load_loc, buffer[index]).
result = self.generic_visit(node)
if not self.host_expression and isinstance(node.ctx, ast.Load):
return self._at(result, node)
return result
- def _module_owner(self, node):
+ def _module_owner(self, node: ast.expr) -> bool:
"""Recognize fixed source module aliases from existing binding records."""
if not isinstance(node, ast.Name):
return False
@@ -339,7 +353,7 @@ class IRBuilderTranspiler(ast.NodeTransformer):
]
return bool(records) and all(item.kind == "module_alias" for item in records)
- def visit_Call(self, node, *, callee=None):
+ def visit_Call(self, node: ast.Call, *, callee: ast.expr | None = None) -> ast.expr:
# Source: X.Tensor(("n",), vdevice="cuda:0")
# Builder: X.Tensor((X.resolve_type_var_("n"),),
# vdevice=I.resolve_global_info("cuda:0"))
@@ -388,14 +402,14 @@ class IRBuilderTranspiler(ast.NodeTransformer):
)
return node
- def visit_UnaryOp(self, node):
+ def visit_UnaryOp(self, node: ast.UnaryOp) -> ast.expr:
# Source: not x; Builder: X.not_(x). Host constexpr keeps Python not.
node = self.generic_visit(node)
if isinstance(node.op, ast.Not) and not self.host_expression:
return self._at(self._call(self.dialect_prefix, "not_", [node.operand], node), node)
return self._at(node, node) if not self.host_expression else node
- def visit_BinOp(self, node):
+ def visit_BinOp(self, node: ast.BinOp) -> ast.expr:
# Source: a + b; Builder: I.at_(loc, a + b), using native overloads.
return (
self._at(self.generic_visit(node), node)
@@ -403,13 +417,13 @@ class IRBuilderTranspiler(ast.NodeTransformer):
else self.generic_visit(node)
)
- def visit_BoolOp(self, node):
+ def visit_BoolOp(self, node: ast.BoolOp) -> ast.expr:
# Source: I.constexpr(enabled) and expr
# Builder: enabled and expr. Other operands use X.and_/X.or_.
if self.host_expression:
return self.generic_visit(node)
- def lower(position):
+ def lower(position: int) -> ast.expr:
value = node.values[position]
marker = self._constexpr_operand(value)
if marker is not None:
@@ -430,7 +444,7 @@ class IRBuilderTranspiler(ast.NodeTransformer):
return self._at(lower(0), node)
- def visit_IfExp(self, node):
+ def visit_IfExp(self, node: ast.IfExp) -> ast.expr:
# Source: yes if I.constexpr(test) else no
# Builder: yes if test else no. Unmarked tests use X.if_then_else_.
if self.host_expression:
@@ -452,7 +466,9 @@ class IRBuilderTranspiler(ast.NodeTransformer):
node,
)
- def _comparison(self, left, operation, right, node):
+ def _comparison(
+ self, left: ast.expr, operation: ast.cmpop, right: ast.expr, node: ast.AST
+ ) -> ast.expr:
operations = {
ast.Lt: "lt",
ast.LtE: "le",
@@ -465,7 +481,7 @@ class IRBuilderTranspiler(ast.NodeTransformer):
return self._call(self.dialect_prefix, operations[type(operation)], [left, right], node)
return ast.copy_location(ast.Compare(left, [operation], [right]), node)
- def visit_Compare(self, node):
+ def visit_Compare(self, node: ast.Compare) -> ast.expr:
# Source: a < b < c
# Builder: (lambda a,b,c: X.and_(X.lt(a,b), X.lt(b,c),
# chain=(a,b,c)))(a,b,c)
@@ -496,17 +512,17 @@ class IRBuilderTranspiler(ast.NodeTransformer):
)
return self._at(result, node)
- def visit_NamedExpr(self, node):
+ def visit_NamedExpr(self, node: ast.NamedExpr) -> NoReturn:
# Source assignment expressions have no builder declaration contract.
self._error(node, "Unsupported expression: NamedExpr")
- def visit_Await(self, node):
+ def visit_Await(self, node: ast.Await | ast.Yield | ast.YieldFrom) -> NoReturn:
self._error(node, f"Unsupported expression: {type(node).__name__}")
visit_Yield = visit_Await
visit_YieldFrom = visit_Await
- def _index(self, node):
+ def _index(self, node: ast.expr) -> ast.expr:
# Source: a[start:stop:step]; Builder: X.setitem(a, slice(...), value).
if isinstance(node, ast.Slice):
return ast.copy_location(
@@ -526,7 +542,15 @@ class IRBuilderTranspiler(ast.NodeTransformer):
)
return self.visit(node)
- def _bind(self, target, value, statement, *, ty=None, frame_value=False):
+ def _bind(
+ self,
+ target: ast.expr,
+ value: ast.expr,
+ statement: ast.stmt,
+ *,
+ ty: ast.expr | None = None,
+ frame_value: bool = False,
+ ) -> list[ast.stmt]:
# Declaration syntax has precedence; no previous/existence tracking.
if isinstance(target, ast.Name):
site = self.prescan.sites.get(target) if self.prescan else None
@@ -584,13 +608,13 @@ class IRBuilderTranspiler(ast.NodeTransformer):
if isinstance(target, ast.Tuple | ast.List):
# Source: a, (b,c) = rhs; Builder: unpack once at each reached level.
names = [self.fresh("_unpack") for _ in target.elts]
- pattern = [
+ pattern: list[ast.expr] = [
ast.Starred(ast.Name(name, ast.Store()), ast.Store())
if isinstance(item, ast.Starred)
else ast.Name(name, ast.Store())
for name, item in zip(names, target.elts)
]
- result = [
+ result: list[ast.stmt] = [
ast.copy_location(
ast.Assign(
[ast.Tuple(pattern, ast.Store())],
@@ -611,7 +635,8 @@ class IRBuilderTranspiler(ast.NodeTransformer):
return result
self._error(target, f"Unsupported assignment target: {type(target).__name__}")
- def visit_Assign(self, node):
+ def visit_Assign(self, node: ast.Assign) -> ast.Assign | list[ast.stmt]:
+ target: ast.expr
# Source: a = b = rhs; Builder: tmp = rhs; a = X.bind_(tmp); b = X.bind_(tmp).
if self.host_expression:
return self.generic_visit(node)
@@ -621,7 +646,7 @@ class IRBuilderTranspiler(ast.NodeTransformer):
value = ast.Constant(None) if site and site.kind == "symbol" else self.visit(node.value)
return self._bind(target, value, node)
temporary = self.fresh("_value")
- result = [
+ result: list[ast.stmt] = [
ast.copy_location(
ast.Assign([ast.Name(temporary, ast.Store())], self.visit(node.value)), node
)
@@ -630,7 +655,7 @@ class IRBuilderTranspiler(ast.NodeTransformer):
result.extend(self._bind(target, ast.Name(temporary, ast.Load()), node))
return result
- def visit_AnnAssign(self, node):
+ def visit_AnnAssign(self, node: ast.AnnAssign) -> ast.AnnAssign | list[ast.stmt]:
# Source: x: X.int32 = v; Builder: x = X.decl_mutable_var_(v, ty=X.int32).
if self.host_expression:
return self.generic_visit(node)
@@ -649,7 +674,10 @@ class IRBuilderTranspiler(ast.NodeTransformer):
self.annotation_aliases = old_aliases
return self._bind(node.target, value, node, ty=annotation)
- def visit_AugAssign(self, node):
+ def visit_AugAssign(self, node: ast.AugAssign) -> ast.AugAssign | list[ast.stmt]:
+ key: ast.expr
+ load: ast.expr
+ value: ast.expr
# Source: a[index] += value; Builder: evaluate base/index/load/RHS once,
# then X.setitem(base, index, old + value). Name stores use D27 dispatch.
if self.host_expression:
@@ -663,7 +691,7 @@ class IRBuilderTranspiler(ast.NodeTransformer):
if not isinstance(node.target, ast.Subscript | ast.Attribute):
self._error(node.target, "An augmented assignment requires a name, attribute, or index")
base = self.fresh("_base")
- statements = [
+ statements: list[ast.stmt] = [
ast.copy_location(
ast.Assign([ast.Name(base, ast.Store())], self.visit(node.target.value)), node
)
@@ -701,7 +729,7 @@ class IRBuilderTranspiler(ast.NodeTransformer):
)
return statements
- def visit_Expr(self, node):
+ def visit_Expr(self, node: ast.Expr) -> ast.Expr:
# Source: f(); Builder: X.emit_(I.with_at_group_(loc, lambda: f())).
if self.host_expression:
return self.generic_visit(node)
@@ -709,7 +737,7 @@ class IRBuilderTranspiler(ast.NodeTransformer):
ast.Expr(self._call(self.dialect_prefix, "emit_", [self.visit(node.value)], node)), node
)
- def visit_Return(self, node):
+ def visit_Return(self, node: ast.Return) -> ast.Return | ast.Expr:
# Source: return x; Builder: X.return_(x). Macros retain Python return.
value = self.visit(node.value) if node.value else None
if self.preserve_return or self.host_expression:
@@ -718,7 +746,7 @@ class IRBuilderTranspiler(ast.NodeTransformer):
ast.Expr(self._operation("return_", [] if value is None else [value], node)), node
)
- def visit_Break(self, node):
+ def visit_Break(self, node: ast.Break) -> ast.Break | ast.Expr:
# Source: break; Builder: X.break_().
return (
node
@@ -726,7 +754,7 @@ class IRBuilderTranspiler(ast.NodeTransformer):
else ast.copy_location(ast.Expr(self._operation("break_", [], node)), node)
)
- def visit_Continue(self, node):
+ def visit_Continue(self, node: ast.Continue) -> ast.Continue | ast.Expr:
# Source: continue; Builder: X.continue_().
return (
node
@@ -734,7 +762,7 @@ class IRBuilderTranspiler(ast.NodeTransformer):
else ast.copy_location(ast.Expr(self._operation("continue_", [], node)), node)
)
- def visit_Assert(self, node):
+ def visit_Assert(self, node: ast.Assert) -> ast.Assert | ast.Expr:
# Source: assert cond, msg; Builder: X.assert_(cond, msg).
if self.host_expression:
return self.generic_visit(node)
@@ -743,7 +771,7 @@ class IRBuilderTranspiler(ast.NodeTransformer):
ast.Expr(self._operation("assert_", [self.visit(node.test), message], node)), node
)
- def _branch(self, body, node, prefix):
+ def _branch(self, body: list[ast.stmt], node: ast.AST, prefix: str) -> list[ast.stmt]:
# Branch helper scoping keeps source names; mutable stores bind no locals.
name = self.fresh(prefix)
return [
@@ -751,7 +779,7 @@ class IRBuilderTranspiler(ast.NodeTransformer):
ast.copy_location(ast.Expr(ast.Call(ast.Name(name, ast.Load()), [], [])), node),
]
- def visit_If(self, node):
+ def visit_If(self, node: ast.If) -> ast.If | list[ast.stmt]:
# Source: if I.constexpr(flag): ...
# Builder: if flag: ... in the enclosing Python scope.
marker = self._constexpr_operand(node.test)
@@ -784,7 +812,7 @@ class IRBuilderTranspiler(ast.NodeTransformer):
if self.preserve_return
else self._branch(node.body, node, "_then")
)
- branches = [
+ branches: list[ast.stmt] = [
ast.copy_location(
ast.With([ast.withitem(self._operation("Then", [], node))], then or [ast.Pass()]),
node,
@@ -804,7 +832,7 @@ class IRBuilderTranspiler(ast.NodeTransformer):
node,
)
)
- result = [
+ result: list[ast.stmt] = [
ast.copy_location(
ast.With(
[
@@ -831,7 +859,7 @@ class IRBuilderTranspiler(ast.NodeTransformer):
)
return result
- def visit_For(self, node):
+ def visit_For(self, node: ast.For) -> ast.For | ast.With:
# Source:
# for i, *tail in X.grid(m,n,k): body
# Builder:
@@ -852,7 +880,7 @@ class IRBuilderTranspiler(ast.NodeTransformer):
else:
iterable = self.visit(node.iter)
if isinstance(node.target, ast.Name):
- names = ast.Constant(node.target.id)
+ names: ast.expr = ast.Constant(node.target.id)
elif isinstance(node.target, ast.Tuple | ast.List):
names = ast.Tuple(
[
@@ -869,7 +897,7 @@ class IRBuilderTranspiler(ast.NodeTransformer):
ast.With([ast.withitem(context, node.target)], body or [ast.Pass()]), node
)
- def visit_While(self, node):
+ def visit_While(self, node: ast.While) -> ast.While | ast.With:
# Source: while cond: body; Builder: with X.While(cond): body.
if self.host_expression:
return self.generic_visit(node)
@@ -881,14 +909,16 @@ class IRBuilderTranspiler(ast.NodeTransformer):
node,
)
- def visit_With(self, node):
+ def visit_With(self, node: ast.With) -> ast.With | list[ast.stmt]:
# Source: with X.block() as v: body
# Builder: with X.block() as entered: v = X.bind_(entered, frame_value=True); body
# Ordinary regions use Python locals; native dataflow outputs retain identity.
if self.host_expression:
return self.generic_visit(node)
item, rest = node.items[0], node.items[1:]
- body = [ast.copy_location(ast.With(rest, node.body), node)] if rest else node.body
+ body: list[ast.stmt] = (
+ [ast.copy_location(ast.With(rest, node.body), node)] if rest else node.body
+ )
if item.optional_vars is None:
target, initial = None, []
else:
@@ -908,7 +938,7 @@ class IRBuilderTranspiler(ast.NodeTransformer):
# Builder: with frame: ...; y = frame.output_vars[0]
# The native frame owns conversion to ordinary output variables.
frame = self.fresh("_dataflow")
- statements = [
+ statements: list[ast.stmt] = [
ast.copy_location(ast.Assign([ast.Name(frame, ast.Store())], context), node),
ast.copy_location(
ast.With([ast.withitem(ast.Name(frame, ast.Load()), target)], translated_body), node
@@ -925,7 +955,7 @@ class IRBuilderTranspiler(ast.NodeTransformer):
)
return statements
- def visit_FunctionDef(self, node):
+ def visit_FunctionDef(self, node: ast.FunctionDef) -> ast.FunctionDef | list[ast.stmt]:
# Source: nested @X.function def f(...): body
# Builder: declare fn; def build(fn): with fn: body; build(fn).
if self.host_expression:
@@ -942,27 +972,31 @@ class IRBuilderTranspiler(ast.NodeTransformer):
),
]
- def visit_Nonlocal(self, node):
+ def visit_Nonlocal(self, node: ast.Nonlocal) -> ast.Pass:
# Source closure declarations do not mutate the host closure during build.
return ast.copy_location(ast.Pass(), node)
- def visit_Pass(self, node):
+ def visit_Pass(self, node: ast.Pass) -> ast.Pass:
# Source: pass; Builder: pass.
return node
- def generic_visit(self, node):
+ def generic_visit(self, node: _Node) -> _Node:
if isinstance(node, ast.stmt) and not self.host_expression:
self._error(node, f"Unsupported statement: {type(node).__name__}")
return super().generic_visit(node)
- def function_metadata(self, node, *, allow_python=False):
+ def function_metadata(
+ self, node: ast.FunctionDef, *, allow_python: bool = False
+ ) -> tuple[protocol.FunctionDecoratorInfo, ast.Dict]:
"""Read registered decorator options without evaluating source values."""
for decorator in node.decorator_list:
target = decorator.func if isinstance(decorator, ast.Call) else decorator
kind = protocol.function_info(self._resolve(target))
if kind is None:
continue
- values = {key: ast.Constant(value) for key, value in (kind.defaults or {}).items()}
+ values: dict[str, ast.expr] = {
+ key: ast.Constant(value) for key, value in (kind.defaults or {}).items()
+ }
expansions = []
if isinstance(decorator, ast.Call):
if decorator.args:
@@ -985,7 +1019,9 @@ class IRBuilderTranspiler(ast.NodeTransformer):
return protocol.FunctionDecoratorInfo(None, python=True), ast.Dict([], [])
self._error(node, f"Function {node.name!r} has no registered construction kind")
- def function_program(self, node, *, local=False, declare=True):
+ def function_program(
+ self, node: ast.FunctionDef, *, local: bool = False, declare: bool = True
+ ) -> tuple[list[ast.stmt], str, str]:
"""Declare one native frame and emit one body function taking that frame.
Annotation aliases retain actual definition-local Python values; source
@@ -1054,9 +1090,11 @@ class IRBuilderTranspiler(ast.NodeTransformer):
ast.Call(self._inject(locals), [], []),
],
)
- statements = [
+ statements: list[ast.stmt] = [
ast.copy_location(ast.Assign([ast.Name(captures, ast.Store())], captures_expr), node)
]
+ fallback: ast.expr
+ value: ast.expr
for name, alias in aliases.items():
fallback = (
self._inject(getattr(builtins, name))
@@ -1070,6 +1108,8 @@ class IRBuilderTranspiler(ast.NodeTransformer):
ast.copy_location(ast.Assign([ast.Name(alias, ast.Store())], value), node)
)
special, absent = self.fresh("_specialization"), self.fresh("_absent")
+ special_expr: ast.expr
+ absent_expr: ast.expr
if local:
special_expr, absent_expr = ast.Constant(None), ast.Tuple([], ast.Load())
else:
@@ -1085,7 +1125,7 @@ class IRBuilderTranspiler(ast.NodeTransformer):
ast.copy_location(ast.Assign([ast.Name(absent, ast.Store())], absent_expr), node),
]
)
- declaration = [
+ declaration: list[ast.stmt] = [
ast.copy_location(
ast.Expr(self._call(builder, "func_name", [ast.Constant(node.name)], node)), node
)
@@ -1241,7 +1281,7 @@ class IRBuilderTranspiler(ast.NodeTransformer):
# The body re-enters the exact native frame. Runtime parameter storage
# stays native; the short iterator is consumed once by source parameters.
iterator = self.fresh("_arguments")
- body = [
+ body: list[ast.stmt] = [
ast.copy_location(
ast.Assign(
[ast.Name(iterator, ast.Store())],
@@ -1325,7 +1365,7 @@ class IRBuilderTranspiler(ast.NodeTransformer):
self.dialect_prefix, self.current_scope, self.annotation_aliases = old
return statements, frame, body_name
- def program(self, tree):
+ def program(self, tree: ast.Module) -> tuple[ast.Module, str]:
"""Emit direct native module construction, declarations, then bodies."""
from .entry import make_opaque_function
@@ -1341,7 +1381,7 @@ class IRBuilderTranspiler(ast.NodeTransformer):
self.module_functions = frozenset(item.name for item in functions)
declare = is_module or root in self.prescan.recursive_functions
builder, result = self.fresh("_builder"), self.fresh("_result")
- body = []
+ body: list[ast.stmt] = []
for function in functions if declare else ():
body.append(
ast.copy_location(
diff --git a/python/tvm/tirx/script/builder/__init__.py b/python/tvm/tirx/script/builder/__init__.py
index 5f00f6f767..96422108a7 100644
--- a/python/tvm/tirx/script/builder/__init__.py
+++ b/python/tvm/tirx/script/builder/__init__.py
@@ -30,8 +30,8 @@ from tvm.script.ir_builder.base import BypassBind as _BypassBind
from tvm.script.ir_builder.base import _construction_span, _return_annotation
from tvm.script.ir_builder.base import at as _at
from tvm.script.ir_builder.base import source_span as _source_span
+from tvm.script.parser.protocol import args_policy as _args_policy
from tvm.script.parser.protocol import constexpr as constexpr
-from tvm.script.parser.protocol import expr_str_args as _expression_args
from tvm.script.parser.protocol import register_type_var_decl as _register_type_var_decl
from tvm.tirx.lang.alloc_pool import SMEMPool as SMEMPool
from tvm.tirx.lang.alloc_pool import TMEMPool as TMEMPool
@@ -76,14 +76,14 @@ def type_var(name, *, dtype=None, span=None):
return _ir.Var(name, "int64" if dtype is None else dtype, _source_span(span))
-@_expression_args(
- "shape",
- "strides",
- "elem_offset",
- "byte_offset",
- "allocated_addr",
- introduce=True,
- compound_declarations=True,
+@_args_policy(
+ {
+ "shape": "expr_str",
+ "strides": "expr_str",
+ "elem_offset": "expr_str",
+ "byte_offset": "expr_str",
+ "allocated_addr": "expr_str",
+ },
as_type=True,
)
def Buffer(
@@ -405,13 +405,35 @@ def If(condition, *, span=None):
def Then(*, span=None):
- """Create a native then statement region."""
+ """Create a native then statement region.
+
+ Parameters
+ ----------
+ span : Span or source location, optional
+ Source location attached to the constructed IR.
+
+ Returns
+ -------
+ res : frame.ThenFrame
+ The constructed frame, retaining source metadata.
+ """
with _construction_span(span):
return _at(span, _native.Then())
def Else(*, span=None):
- """Create a native else statement region."""
+ """Create a native else statement region.
+
+ Parameters
+ ----------
+ span : Span or source location, optional
+ Source location attached to the constructed IR.
+
+ Returns
+ -------
+ res : frame.ElseFrame
+ The constructed frame, retaining source metadata.
+ """
with _construction_span(span):
return _at(span, _native.Else())
@@ -507,13 +529,13 @@ def shared_scalar(dtype="float32"):
return alloc_scalar(dtype, "shared")
-@_expression_args(
- "shape",
- "strides",
- "elem_offset",
- "allocated_addr",
- introduce=True,
- compound_declarations=True,
+@_args_policy(
+ {
+ "shape": "expr_str",
+ "strides": "expr_str",
+ "elem_offset": "expr_str",
+ "allocated_addr": "expr_str",
+ }
)
@_wraps(_native.match_buffer)
def match_buffer(*args, **kwargs):
diff --git a/tests/python/unittest/test_parser_captured_constructors.py b/tests/python/relax/script/test_capture_annotation_constructors.py
similarity index 100%
rename from tests/python/unittest/test_parser_captured_constructors.py
rename to tests/python/relax/script/test_capture_annotation_constructors.py
diff --git a/tests/python/relax/script/test_capture_annotation_identity.py b/tests/python/relax/script/test_capture_annotation_identity.py
new file mode 100644
index 0000000000..23465be972
--- /dev/null
+++ b/tests/python/relax/script/test_capture_annotation_identity.py
@@ -0,0 +1,87 @@
+# 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.
+
+"""Retained annotations construct complete Relax types, dataflow, and symbol identities."""
+
+from __future__ import annotations
+
+import tvm
+from tvm.script import ir as I
+from tvm.script import relax as R
+from tvm.script import tirx as T
+
+
+def test_local_annotation_retains_names_absent_from_signature():
+ def build(shape, dtype):
+ @R.function
+ def function(x: R.Tensor((2,), "float32")):
+ y: R.Tensor(shape, dtype) = R.add(x, x)
+ return y
+
+ return function
+
+ @R.function
+ def expected(x: R.Tensor((2,), "float32")):
+ y: R.Tensor((2,), "float32") = R.add(x, x)
+ return y
+
+ actual = build((2,), "float32")
+ tvm.ir.assert_structural_equal(
+ actual.with_attr("global_symbol", ""), expected.with_attr("global_symbol", "")
+ )
+
+
+def test_local_annotation_and_signature_share_retained_context():
+ def build(shape, dtype):
+ @I.ir_module
+ class Module:
+ @R.function
+ def main(x: R.Tensor(shape, dtype)):
+ with R.dataflow():
+ y: R.Tensor(shape, dtype) = R.add(x, x)
+ R.output(y)
+ return y
+
+ return Module
+
+ @I.ir_module
+ class Expected:
+ @R.function
+ def main(x: R.Tensor((2,), "float32")):
+ with R.dataflow():
+ y: R.Tensor((2,), "float32") = R.add(x, x)
+ R.output(y)
+ return y
+
+ tvm.ir.assert_structural_equal(build((2,), "float32"), Expected)
+
+
+def test_local_annotation_preserves_explicit_parameter_and_d3_symbols():
+ dtype = "float32"
+
+ @R.function
+ def function(n: R.Prim("int64"), x: R.Tensor((n, "m"), "float32")):
+ m = T.int64()
+ y: R.Tensor((n, m), dtype) = R.add(x, x)
+ return y
+
+ n, x = function.params
+ binding = function.body.blocks[0].bindings[0]
+ assert binding.var.ty.shape[0].same_as(n)
+ assert binding.var.ty.shape[1].same_as(x.ty.shape[1])
+ assert function.ret_ty.shape[0].same_as(n)
+ assert function.ret_ty.shape[1].same_as(x.ty.shape[1])
diff --git a/tests/python/relax/script/test_frontend_relax_construction_validation.py b/tests/python/relax/script/test_frontend_relax_construction_validation.py
new file mode 100644
index 0000000000..5953c1a3f3
--- /dev/null
+++ b/tests/python/relax/script/test_frontend_relax_construction_validation.py
@@ -0,0 +1,77 @@
+# 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.
+
+"""Public Relax construction retains validation controls and Python attachments."""
+
+import pytest
+
+import tvm
+from tvm import relax
+from tvm.error import DiagnosticError
+from tvm.relax import BasePyModule
+from tvm.script import ir as I
+from tvm.script import relax as R
+from tvm.script import tirx as T
+
+
+def _invalid_inplace_module(**options):
+ @I.ir_module(**options)
+ class Module:
+ @T.prim_func
+ def kernel(A: T.Buffer((2,), "int32")):
+ T.evaluate(0)
+
+ @R.function
+ def main(x: R.Tensor((2,), "int32")):
+ R.func_attr({"relax.force_pure": True})
+ result = R.call_tir_inplace(
+ Module.kernel,
+ (x,),
+ [0, 0],
+ [R.Tensor((2,), "int32"), R.Tensor((2,), "int32")],
+ )
+ return result
+
+ return Module
+
+
+def test_default_relax_validation_rejects_repeated_inplace_input():
+ with pytest.raises(DiagnosticError):
+ _invalid_inplace_module()
+
+
+def test_relax_validation_can_be_explicitly_disabled():
+ module = _invalid_inplace_module(check_well_formed=False)
+ assert isinstance(module["main"], relax.Function)
+ call = module["main"].body.blocks[0].bindings[0].value
+ assert list(call.attrs.inplace_indices) == [0, 0]
+ assert not relax.analysis.check_well_formed(module)
+
+
+def test_python_module_factory_and_attached_function_execute():
+ @I.ir_module
+ class Module(BasePyModule):
+ @I.pyfunc
+ def twice(value):
+ return value * 2
+
+ assert callable(Module)
+ assert Module.pyfuncs["twice"](3) == 6
+ instance = Module(tvm.cpu())
+ assert isinstance(instance, BasePyModule)
+ assert instance.twice(4) == 8
+ assert instance.pyfuncs["twice"](5) == 10
diff --git a/tests/scripts/task_python_unittest.sh b/tests/python/relax/script/test_parser_captured_shapes.py
old mode 100755
new mode 100644
similarity index 61%
copy from tests/scripts/task_python_unittest.sh
copy to tests/python/relax/script/test_parser_captured_shapes.py
index 6b9e7ae4d1..53a2366791
--- a/tests/scripts/task_python_unittest.sh
+++ b/tests/python/relax/script/test_parser_captured_shapes.py
@@ -1,4 +1,3 @@
-#!/usr/bin/env bash
# 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
@@ -15,13 +14,22 @@
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
+"""Captured Relax tensor shapes need concrete symbols."""
-set -euxo pipefail
+import pytest
-export PYTHONPATH="$(pwd)/python"
-export PYTEST_ADDOPTS="${CI_PYTEST_ADD_OPTIONS:-} ${PYTEST_ADDOPTS:-}"
+from tvm import ir
+from tvm.script import parser
-# setup tvm-ffi into python folder
-uv pip install -v --target=python ./3rdparty/tvm-ffi/
-python3 -m pytest -vvs -n auto -m "${TVM_TEST_MARKER:-not gpu}" tests/python tests/parser
+def test_captured_shapes_require_explicit_symbols():
+ n = ir.Var("n", "int64")
+ source = """
+@R.function
+def main(x: R.Tensor(shape, "float32")):
+ return x
+"""
+ result = parser.parse(source, extra_vars={"shape": (n, 16)})
+ assert result.params[0].ty.shape[0].same_as(n)
+ with pytest.raises(Exception):
+ parser.parse(source, extra_vars={"shape": ("n", 16)})
diff --git a/tests/python/relax/script/test_parser_construction_regressions.py b/tests/python/relax/script/test_parser_construction_regressions.py
new file mode 100644
index 0000000000..f107b4fb65
--- /dev/null
+++ b/tests/python/relax/script/test_parser_construction_regressions.py
@@ -0,0 +1,68 @@
+# 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.
+"""Construction regressions exercised by ordinary TVMScript entry points."""
+
+import tvm
+from tvm.script import ir as I
+from tvm.script import parser
+from tvm.script import relax as R
+
+
+def test_eager_module_annotations_resolve_global_info_in_module_scope():
+ @I.ir_module
+ class Module:
+ I.module_global_infos(
+ {
+ "mesh": [R.device_mesh((2,), I.Range(0, 2))],
+ "vdevice": [I.vdevice("llvm")],
+ }
+ )
+
+ @R.function
+ def distributed(x: R.DTensor((4,), "float32", "mesh[0]", "R")):
+ return x
+
+ @R.function
+ def tensor(x: R.Tensor((4,), "float32", vdevice="llvm:0:global")):
+ return x
+
+ assert (
+ Module["distributed"].params[0].ty.device_mesh.__chandle__()
+ == Module.global_infos["mesh"][0].__chandle__()
+ )
+ assert (
+ Module["tensor"].params[0].ty.vdevice.__chandle__()
+ == Module.global_infos["vdevice"][0].__chandle__()
+ )
+
+
+def test_scoped_vdevice_selects_target_ordinal_and_roundtrips():
+ module = parser.parse("""
+@I.ir_module
+class Module:
+ I.module_global_infos({"vdevice": [
+ I.vdevice("llvm"), I.vdevice("cuda"), I.vdevice("metal"), I.vdevice("cuda", 1),
+ ]})
+ @R.function
+ def main(x: R.Tensor((4,), "float32", vdevice="cuda:1:global")):
+ return x
+""")
+ assert (
+ module["main"].params[0].ty.vdevice.__chandle__()
+ == module.global_infos["vdevice"][3].__chandle__()
+ )
+ tvm.ir.assert_structural_equal(module, tvm.script.from_source(module.script()))
diff --git a/tests/python/relax/test_parser_distributed_aliases.py b/tests/python/relax/script/test_parser_distributed_aliases.py
similarity index 100%
rename from tests/python/relax/test_parser_distributed_aliases.py
rename to tests/python/relax/script/test_parser_distributed_aliases.py
diff --git a/tests/python/unittest/test_parser_ir_namespace.py b/tests/python/relax/script/test_parser_distributed_range.py
similarity index 58%
rename from tests/python/unittest/test_parser_ir_namespace.py
rename to tests/python/relax/script/test_parser_distributed_range.py
index 1aa99d620e..4243e5e73a 100644
--- a/tests/python/unittest/test_parser_ir_namespace.py
+++ b/tests/python/relax/script/test_parser_distributed_range.py
@@ -14,9 +14,7 @@
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
-"""Foundational IR constructors keep their identity in public script namespaces."""
-
-import pytest
+"""Distributed annotations retain common Range construction."""
import tvm
from tvm.relax.script import builder as R
@@ -25,15 +23,6 @@ from tvm.script.ir_builder import IRBuilder
from tvm.script.ir_builder import ir as I
-@pytest.mark.parametrize("name", ["Range", "StringType", "StringImm", "GenericConst"])
-def test_shared_ir_constructor_identity(name):
- # Initialize the source namespace before inspecting its shared constructors.
- parse = parser.parse
- assert callable(parse)
- assert getattr(I, name) is getattr(tvm.ir, name)
- assert getattr(parser.I, name) is getattr(tvm.ir, name)
-
-
def test_distributed_module_range():
source = """
@I.ir_module
@@ -59,30 +48,3 @@ class Module:
expected = builder.get()
actual = parser.parse(source)
tvm.ir.assert_structural_equal(expected, actual)
-
-
-def test_module_string_constants():
- source = """
-@I.ir_module
-class Module:
- I.module_attrs({
- "tag": I.StringImm("label"),
- "type": I.StringType(),
- })
-
- @R.function
- def main(x: R.Tensor((16,), "float32")):
- return x
-"""
- with IRBuilder() as builder:
- with I.ir_module():
- I.module_attrs({"tag": tvm.ir.StringImm("label"), "type": tvm.ir.StringType()})
- with R.function():
- R.func_name("main")
- x = R.arg("x", R.Tensor((16,), "float32"))
- R.func_ret_value(x)
- expected = builder.get()
- actual = parser.parse(source)
- tvm.ir.assert_structural_equal(expected, actual)
- assert actual.attrs["tag"].value == "label"
- assert isinstance(actual.attrs["type"], tvm.ir.StringType)
diff --git a/tests/python/relax/test_parser_local_function_types.py b/tests/python/relax/script/test_parser_local_function_types.py
similarity index 100%
rename from tests/python/relax/test_parser_local_function_types.py
rename to tests/python/relax/script/test_parser_local_function_types.py
diff --git a/tests/python/relax/test_parser_local_functions.py b/tests/python/relax/script/test_parser_local_functions.py
similarity index 100%
rename from tests/python/relax/test_parser_local_functions.py
rename to tests/python/relax/script/test_parser_local_functions.py
diff --git a/tests/python/unittest/test_parser_emission_contract.py b/tests/python/relax/script/test_parser_relax_emission.py
similarity index 62%
copy from tests/python/unittest/test_parser_emission_contract.py
copy to tests/python/relax/script/test_parser_relax_emission.py
index cb6d8259df..4958472597 100644
--- a/tests/python/unittest/test_parser_emission_contract.py
+++ b/tests/python/relax/script/test_parser_relax_emission.py
@@ -14,46 +14,18 @@
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
-"""Explicit source emission and generated statement consumption agree."""
+"""Source emission uses the dialect public builder contract."""
import pytest
-import tvm
from tvm import ir, tirx
from tvm.relax.script import builder as R
from tvm.relax.script.builder import ir as native_R
from tvm.script import parser
-from tvm.script import tirx as T
from tvm.script.ir_builder import IRBuilder
-from tvm.script.ir_builder import ir as I
from tvm.tirx.script import builder as tir_builder
-@pytest.mark.parametrize("error_type", [TypeError, ValueError])
-@pytest.mark.parametrize(
- "body",
- [
- "v: T.int32 = 1",
- "v: T.int32\n v = v + 1",
- 'A = T.alloc_buffer((4,), "int32")\n A[0] = 1',
- ],
-)
-def test_source_store_uses_public_builder_and_propagates_errors(monkeypatch, error_type, body):
- error = error_type("store rejected")
- calls = []
-
- def reject_store(*args):
- calls.append(args)
- raise error
-
- monkeypatch.setattr(tir_builder, "buffer_store", reject_store)
- source = f"@T.prim_func\ndef main():\n {body}\n"
- with pytest.raises(tvm.error.DiagnosticError, match="store rejected") as raised:
- parser.parse(source)
- assert raised.value.__cause__ is error
- assert len(calls) == 1
-
-
def test_explicit_relax_emit_retains_source_binding_api():
source = """
@R.function
@@ -70,19 +42,7 @@ def main():
ir.assert_structural_equal(context.get(), parser.parse(source))
-def test_emit_keeps_existing_buffer_store_identity_and_span():
- with IRBuilder() as builder:
- with T.function():
- T.func_name("store")
- buffer = tirx.decl_buffer((4,), "int32")
- statement = I.at_(("store.py", 3, 3, 1, 12), tirx.BufferStore(buffer, 1, [0]))
- T.emit(statement)
- stored = builder.get().body
- assert stored.same_as(statement)
- assert stored.span.line == 3
-
-
-@pytest.mark.parametrize("dialect", ["tirx", "relax"])
+@pytest.mark.parametrize("dialect", ["relax"])
def test_generated_statements_use_dialect_emit_protocol(monkeypatch, dialect):
builder = tir_builder if dialect == "tirx" else R
original = builder.emit_
diff --git a/tests/python/unittest/test_parser_native_frames.py b/tests/python/relax/script/test_parser_relax_frames.py
similarity index 59%
copy from tests/python/unittest/test_parser_native_frames.py
copy to tests/python/relax/script/test_parser_relax_frames.py
index cc92e890b5..3f37462d61 100644
--- a/tests/python/unittest/test_parser_native_frames.py
+++ b/tests/python/relax/script/test_parser_relax_frames.py
@@ -14,20 +14,19 @@
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
-"""Native declaration frames retain identity across generated body execution."""
+"""Native function frames preserve their declared objects."""
import pytest
-from tvm import ir, tirx
+from tvm import ir
from tvm.relax.script import builder as R
from tvm.script import parser
from tvm.script.ir_builder import IRBuilder
from tvm.script.ir_builder import ir as I
from tvm.tirx.script import builder as T
-from tvm.tirx.script.builder.frame import ForFrame
-@pytest.mark.parametrize("dialect", [T, R])
+@pytest.mark.parametrize("dialect", [R])
def test_function_declaration_reentry_reuses_parameters_symbols_and_reference(dialect):
# Before: @X.function def identity(x: ...): return x
# Expected builder program:
@@ -55,116 +54,7 @@ def test_function_declaration_reentry_reuses_parameters_symbols_and_reference(di
assert module["identity"].params[0].same_as(parameter)
-@pytest.mark.parametrize(
- "names, expected",
- [
- ("ids", ["ids_0", "ids_1", "ids_2"]),
- (("i", "*tail"), ["i", "tail_0", "tail_1"]),
- (("*head", "last"), ["head_0", "head_1", "last"]),
- ],
-)
-def test_native_grid_names_and_unpacking_preserve_entered_variables(names, expected):
- # Before: for i, *tail in X.grid(2, 3, 4): X.evaluate(i)
- # Expected builder program:
- # with X.for_(X.grid(2, 3, 4), names=("i", "*tail")) as (i, *tail): ...
- with IRBuilder() as builder:
- frame = T.grid(2, 3, 4)
- assert isinstance(frame, ForFrame)
- assert T.for_(frame, names=names) is frame
- with frame as variables:
- assert [variable.name for variable in variables] == expected
- for variable in variables:
- T.evaluate(variable)
- loop = builder.get()
- actual = []
- while isinstance(loop, tirx.For):
- actual.append(loop.loop_var)
- loop = loop.body
- assert len(actual) == 3
- assert all(a.same_as(b) for a, b in zip(actual, variables))
- assert all(
- statement.value.same_as(variable) for statement, variable in zip(loop.seq, variables)
- )
-
-
-def test_singleton_tuple_loop_target_keeps_sequence_shape():
- # Before: for (i,) in X.grid(4): X.evaluate(i)
- # Expected builder program: with X.for_(X.grid(4), names=("i",)) as (i,): ...
- with IRBuilder() as builder:
- frame = T.for_(T.grid(4), names=("i",))
- with frame as variables:
- assert len(variables) == 1
- T.evaluate(variables[0])
- assert builder.get().loop_var.same_as(variables[0])
-
-
-def test_conditional_output_uses_same_name_and_native_frame_result():
- # Before: if condition: y = X.add(x, x); else: y = X.multiply(x, x); return y
- # Expected builder program:
- # with X.If(condition) as frame:
- # with X.Then():
- # def then(): y = X.bind_(X.add(x, x), name="y")
- # then()
- # with X.Else():
- # def otherwise(): y = X.bind_(X.multiply(x, x), name="y")
- # otherwise()
- # y = frame.var; X.return_(y)
- actual = parser.parse("""
-@R.function
-def main(condition: R.Tensor((), "bool"), x: R.Tensor((4,), "float32")):
- if condition:
- y = R.add(x, x)
- else:
- y = R.multiply(x, x)
- return y
-""")
- with IRBuilder() as builder, R.function():
- R.func_name("main")
- condition = R.arg("condition", R.Tensor((), "bool"))
- x = R.arg("x", R.Tensor((4,), "float32"))
- with R.If(condition) as frame:
- with R.Then():
- R.bind_(R.add(x, x), name="y")
- with R.Else():
- R.bind_(R.multiply(x, x), name="y")
- R.func_ret_value(frame.var)
- ir.assert_structural_equal(actual, builder.get())
-
-
-def test_ir_branch_incoming_read_and_rebinding_obeys_python_scope():
- # Before: y = x; if condition: y = X.add(y, x); else: y = x
- # Expected builder program: a local branch helper reads y before assignment;
- # report Python's unbound-name error, without synthetic y=y capture parameters.
- with pytest.raises(Exception) as error:
- parser.parse("""
-@R.function
-def main(condition: R.Tensor((), "bool"), x: R.Tensor((4,), "float32")):
- y = x
- if condition:
- y = R.add(y, x)
- else:
- y = x
- return y
-""")
- assert isinstance(error.value.__cause__, NameError)
- assert "y" in str(error.value.__cause__)
-
-
-def test_body_attribute_overrides_default_after_declaration():
- # Before: @X.prim_func def main(): X.func_attr({"global_symbol": "custom"})
- # Expected builder program:
- # with X.function(decl=True) as fn: X.func_name("main")
- # with fn: X.func_attr({"global_symbol": "custom"}); X.emit_(X.evaluate(0))
- with IRBuilder() as builder, I.ir_module():
- with T.function(decl=True) as frame:
- T.func_name("main")
- with frame:
- T.func_attr({"global_symbol": "custom"})
- T.evaluate(0)
- assert builder.get()["main"].attrs["global_symbol"] == "custom"
-
-
-@pytest.mark.parametrize("dialect", [T, R])
+@pytest.mark.parametrize("dialect", [R])
def test_module_alias_is_the_native_frame_and_lookup_keeps_reference(dialect):
# Before: cls = Module; cls.callee
# Expected builder program: cls = X.bind_(Module, name="cls")
@@ -194,7 +84,7 @@ def test_module_alias_is_the_native_frame_and_lookup_keeps_reference(dialect):
@pytest.mark.parametrize("parameter", ["x", "callee"])
@pytest.mark.parametrize(
"dialect, decorator, annotation",
- [(T, "T.prim_func", "T.int32"), (R, "R.function", 'R.Tensor((4,), "float32")')],
+ [(R, "R.function", 'R.Tensor((4,), "float32")')],
)
def test_module_member_calls_use_the_callers_native_dialect(
monkeypatch, dialect, decorator, annotation, alias, parameter
@@ -230,22 +120,34 @@ class Module:
assert arguments[0].same_as(module["caller"].params[0])
-def test_lexical_range_binding_preserves_custom_native_loop_extent():
- # Before: range = custom_range; for i in range(4): X.evaluate(i)
- # Expected builder program: range = X.bind_(custom_range, name="range")
- # with X.for_(range(4), names="i") as i: X.emit_(X.evaluate(i))
- calls = []
-
- def custom_range(extent):
- calls.append(extent)
- return T.serial(2)
-
- function = parser.parse(
- "@T.prim_func\ndef main():\n range = custom_range\n"
- " for i in range(4):\n T.evaluate(i)\n",
- extra_vars={"custom_range": custom_range},
- )
- assert calls == [4]
- assert isinstance(function.body, tirx.For)
- assert int(function.body.extent) == 2
- assert function.body.body.value.same_as(function.body.loop_var)
+def test_conditional_output_uses_same_name_and_native_frame_result():
+ # Before: if condition: y = X.add(x, x); else: y = X.multiply(x, x); return y
+ # Expected builder program:
+ # with X.If(condition) as frame:
+ # with X.Then():
+ # def then(): y = X.bind_(X.add(x, x), name="y")
+ # then()
+ # with X.Else():
+ # def otherwise(): y = X.bind_(X.multiply(x, x), name="y")
+ # otherwise()
+ # y = frame.var; X.return_(y)
+ actual = parser.parse("""
+@R.function
+def main(condition: R.Tensor((), "bool"), x: R.Tensor((4,), "float32")):
+ if condition:
+ y = R.add(x, x)
+ else:
+ y = R.multiply(x, x)
+ return y
+""")
+ with IRBuilder() as builder, R.function():
+ R.func_name("main")
+ condition = R.arg("condition", R.Tensor((), "bool"))
+ x = R.arg("x", R.Tensor((4,), "float32"))
+ with R.If(condition) as frame:
+ with R.Then():
+ R.bind_(R.add(x, x), name="y")
+ with R.Else():
+ R.bind_(R.multiply(x, x), name="y")
+ R.func_ret_value(frame.var)
+ ir.assert_structural_equal(actual, builder.get())
diff --git a/tests/python/unittest/test_parser_support.py b/tests/python/relax/script/test_parser_relax_resolvers.py
similarity index 55%
copy from tests/python/unittest/test_parser_support.py
copy to tests/python/relax/script/test_parser_relax_resolvers.py
index 3eef773a72..2d5c613773 100644
--- a/tests/python/unittest/test_parser_support.py
+++ b/tests/python/relax/script/test_parser_relax_resolvers.py
@@ -14,9 +14,7 @@
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
-"""Native resolver ownership and eager annotation contracts."""
-
-from typing import TypeVar
+"""Relax declaration and distributed annotation ownership."""
import pytest
@@ -24,41 +22,10 @@ from tvm import ir
from tvm.relax.script import builder as R
from tvm.script import parser
from tvm.script.ir_builder import IRBuilder
-from tvm.script.ir_builder import ir as I
-from tvm.script.parser import protocol
from tvm.tirx.script import builder as T
-def test_global_info_requires_module_and_keeps_objects():
- # Before: X.Tensor((4,), "float32", vdevice="cuda:1")
- # Expected builder program: X.Tensor((4,), "float32", I.resolve_global_info("cuda:1"))
- # Without an enclosing module, a string lookup reports a missing context.
- marker = object()
- assert I.resolve_global_info(marker) is marker
- for active_builder in (False, True):
- if active_builder:
- with IRBuilder(), T.function():
- with pytest.raises(ValueError, match="module"):
- I.resolve_global_info("mesh[0]")
- else:
- with pytest.raises(ValueError, match="module"):
- I.resolve_global_info("cuda:1")
-
-
-def test_global_info_selectors_use_module_map():
- # Before: X.Tensor((4,), "float32", vdevice="cuda:1")
- # Expected builder program: I.resolve_global_info("cuda:1") is mod.global_infos["vdevice"][2]
- with IRBuilder(), I.ir_module() as module:
- devices = [I.vdevice("llvm"), I.vdevice("cuda"), I.vdevice("cuda", 1)]
- I.module_global_infos({"vdevice": devices, "other": [I.dummy_global_info()]})
- for spelling, index in (("cuda:1", 2), ("vdevice[1]", 1), ("cuda", 1)):
- resolved = I.resolve_global_info(spelling)
- assert resolved.__chandle__() == devices[index].__chandle__()
- assert resolved.__chandle__() == module.global_infos["vdevice"][index].__chandle__()
- assert I.resolve_global_info("other[0]") is not None
-
-
-@pytest.mark.parametrize("dialect", [T, R])
+@pytest.mark.parametrize("dialect", [R])
def test_symbol_lookup_requires_function_and_reuses_native_identity(dialect):
# Before: n = X.int64(); X.Tensor(("n",), "float32")
# Expected builder program: n = X.resolve_type_var_("n", "int64")
@@ -97,38 +64,6 @@ def test_nested_functions_have_distinct_symbol_maps():
R.func_ret_value(R.const(0))
-def test_eager_annotations_preserve_missing_type_and_concrete_construction():
- # Before: X.Tensor(("n",)); captured_shape = (n,); X.Tensor(captured_shape)
- # Expected builder program: X.Tensor((X.resolve_type_var_("n"),)); X.Tensor(captured_shape)
- @protocol.args_policy({"shape": "expr_str"}, scalar_strings=False)
- def tensor(shape):
- return shape
-
- assert tensor(("n",)).is_missing()
- assert tensor((TypeVar("n"),)).is_missing()
- assert tensor((16,)) == (16,)
- with IRBuilder(), T.function() as function:
- n = function.resolve_type_var("n")
- assert tensor((TypeVar("n"),))[0].same_as(n)
- assert tensor((n,))[0].same_as(n)
- with pytest.raises(TypeError, match="concrete symbols"):
- tensor(("n",))
- T.evaluate(0)
-
-
-def test_annotation_class_supports_union_and_missing_type():
- # Before: X.Annotation("n") | None
- # Expected builder program: X.Annotation((X.resolve_type_var_("n"))) in a function frame.
- @protocol.args_policy({"shape": "expr_str"}, as_type=True)
- def annotation(shape):
- return shape
-
- assert isinstance(annotation, type)
- assert annotation | None
- assert annotation(16) == 16
- assert annotation("n").is_missing()
-
-
def test_generated_module_enters_global_info_scope_before_annotations():
# Before: I.module_global_infos(info); def f(x: X.Tensor(..., vdevice="cuda:1")): ...
# Expected builder program: with I.ir_module(): I.module_global_infos(info); X.arg(...)
diff --git a/tests/python/relax/script/test_relax_parser_comparison_integration.py b/tests/python/relax/script/test_relax_parser_comparison_integration.py
new file mode 100644
index 0000000000..34c6532bd1
--- /dev/null
+++ b/tests/python/relax/script/test_relax_parser_comparison_integration.py
@@ -0,0 +1,90 @@
+# 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.
+"""Relax comparisons select tensor operators or the primitive fallback explicitly."""
+
+import pytest
+
+from tvm import ir, tirx
+from tvm.script import parser
+
+OPERATORS = [("<", "LT"), ("<=", "LE"), (">", "GT"), (">=", "GE"), ("==", "EQ"), ("!=", "NE")]
+
+
+@pytest.mark.parametrize("operator,kind", OPERATORS)
+def test_unmarked_host_comparison_never_calls_python_overload(operator, kind):
+ from tvm.error import DiagnosticError
+
+ calls = []
+
+ class Host:
+ pass
+
+ def comparison(self, other):
+ calls.append(other)
+ return True
+
+ setattr(
+ Host,
+ {
+ "LT": "__lt__",
+ "LE": "__le__",
+ "GT": "__gt__",
+ "GE": "__ge__",
+ "EQ": "__eq__",
+ "NE": "__ne__",
+ }[kind],
+ comparison,
+ )
+ decorator = "R.function"
+ statement = "return left " + operator + " right"
+ with pytest.raises(DiagnosticError, match="(PrimExpr|primitive|convert|type)"):
+ parser.parse(
+ f"@{decorator}\ndef main():\n {statement}\n",
+ extra_vars={"left": Host(), "right": Host()},
+ )
+ assert calls == []
+
+
+@pytest.mark.parametrize("operator,kind", OPERATORS)
+def test_relax_tensor_comparison_constructs_written_operator(operator, kind):
+ from tvm import relax
+
+ operation = {
+ "LT": "less",
+ "LE": "less_equal",
+ "GT": "greater",
+ "GE": "greater_equal",
+ "EQ": "equal",
+ "NE": "not_equal",
+ }[kind]
+ actual = parser.parse(
+ '@R.function\ndef main(x: R.Tensor((2,), "float32"), y: R.Tensor((2,), "float32")):\n'
+ f" return x {operator} y\n",
+ track_span=True,
+ )
+ call = actual.body.blocks[0].bindings[0].value
+ expected = relax.BlockBuilder().normalize(getattr(relax.op, operation)(*actual.params))
+ ir.assert_structural_equal(call, expected)
+ assert call.span is not None
+
+
+@pytest.mark.parametrize("operator,kind", OPERATORS)
+def test_relax_primitive_comparison_is_concrete_ir(operator, kind):
+ actual = parser.parse(
+ f'@R.function\ndef main(x: R.Prim("int32")):\n return 0 {operator} x\n'
+ )
+ ir.assert_structural_equal(actual.body.body, getattr(tirx, kind)(0, actual.params[0]))
diff --git a/tests/python/tirx/test_parser_helper_migrations.py b/tests/python/relax/test_frontend_nn_llm_script_helpers.py
similarity index 51%
copy from tests/python/tirx/test_parser_helper_migrations.py
copy to tests/python/relax/test_frontend_nn_llm_script_helpers.py
index 2c21344d8c..3d8799c8aa 100644
--- a/tests/python/tirx/test_parser_helper_migrations.py
+++ b/tests/python/relax/test_frontend_nn_llm_script_helpers.py
@@ -14,111 +14,15 @@
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
-"""External helpers construct their IR directly in the new builder."""
+"""LLM allocation and prefill helpers construct their native scheduled IR."""
import pytest
import tvm
-from tvm.backend.cuda.iket import IketProfiler
-from tvm.backend.cuda.lang.warp_role import WarpgroupRole, WarpRole
from tvm.relax.frontend.nn.llm import _kernel_common as kernels
from tvm.script import parser
-def test_iket_annotations():
- source = """
-@T.prim_func
-def main(payload: T.int32):
- iket = IketProfiler()
- iket.range_push("outer")
- iket.range_push("inner", payload)
- iket.mark("point")
- iket.mark("point_payload", payload)
- token = iket.range_start("range")
- token_with_payload = iket.range_start("range_payload", payload)
- sentinel = iket.sentinel_token("sentinel")
- iket.range_end(token)
- iket.range_end(token_with_payload, payload)
- iket.range_end(sentinel)
- iket.range_pop()
- iket.range_pop()
-"""
- expected_source = """
-@T.prim_func
-def main(payload: T.int32):
- T.evaluate(T.cuda.iket.range_push("outer"))
- T.evaluate(T.cuda.iket.range_push("inner", payload))
- T.evaluate(T.cuda.iket.mark("point"))
- T.evaluate(T.cuda.iket.mark("point_payload", payload))
- token = T.cuda.iket.range_start("range")
- token_with_payload = T.cuda.iket.range_start("range_payload", payload)
- sentinel = T.cuda.iket.sentinel_token("sentinel")
- T.evaluate(T.cuda.iket.range_end(token))
- T.evaluate(T.cuda.iket.range_end(token_with_payload, payload))
- T.evaluate(T.cuda.iket.range_end(sentinel))
- T.evaluate(T.cuda.iket.range_pop())
- T.evaluate(T.cuda.iket.range_pop())
-"""
- actual = parser.parse(source, {"IketProfiler": IketProfiler})
- tvm.ir.assert_structural_equal(actual, parser.parse(expected_source))
-
-
-@pytest.mark.parametrize("role", [WarpRole, WarpgroupRole])
-@pytest.mark.parametrize("regs,increase", [(None, False), (48, False), (232, True)])
-def test_warp_role_guards_and_register_budgets(role, regs, increase):
- source = f"""
-@T.prim_func
-def main(role_id: T.int32):
- with role(role_id, 1, regs={regs}, increase={increase}):
- T.evaluate(T.cuda.warp_sync())
-"""
- budget = ""
- if regs is not None:
- direction = "inc" if increase else "dec"
- budget = f' T.evaluate(T.ptx["setmaxnreg.{direction}.sync.aligned.u32"]({regs}))\n'
- expected_source = f"""
-@T.prim_func
-def main(role_id: T.int32):
- if role_id == 1:
-{budget} T.evaluate(T.cuda.warp_sync())
-"""
- actual = parser.parse(source, {"role": role})
- tvm.ir.assert_structural_equal(actual, parser.parse(expected_source))
-
-
-def test_warpgroup_range_guard():
- source = """
-@T.prim_func
-def main(role_id: T.int32):
- with WarpgroupRole(role_id, (1, 3)):
- T.evaluate(T.cuda.warp_sync())
-"""
- expected_source = """
-@T.prim_func
-def main(role_id: T.int32):
- if 1 <= role_id and role_id < 3:
- T.evaluate(T.cuda.warp_sync())
-"""
- actual = parser.parse(source, {"WarpgroupRole": WarpgroupRole})
- tvm.ir.assert_structural_equal(actual, parser.parse(expected_source))
-
-
-@pytest.mark.parametrize("sliding", [False, True])
-def test_llm_length_info_buffer(sliding):
- source = f"""
-@T.prim_func(s_tir=True)
-def main(lengths: T.handle):
- length_info = declare(lengths, 4, {sliding}, 8)
- T.evaluate(length_info[{"0, 0" if sliding else "0"}])
-"""
- expected_source = source.replace(
- f"declare(lengths, 4, {sliding}, 8)",
- f'T.match_buffer(lengths, {"(3, 4)" if sliding else "(4,)"}, "int32", elem_offset=8)',
- )
- actual = parser.parse(source, {"declare": kernels._declare_length_info})
- tvm.ir.assert_structural_equal(actual, parser.parse(expected_source))
-
-
@pytest.mark.parametrize(
"helper,args,specs",
[
diff --git a/tests/python/relax/test_parser_scoped_symbols.py b/tests/python/relax/test_parser_scoped_symbols.py
deleted file mode 100644
index eff4b26e25..0000000000
--- a/tests/python/relax/test_parser_scoped_symbols.py
+++ /dev/null
@@ -1,96 +0,0 @@
-# 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.
-"""Quoted symbols remain frame-local without creating Python bindings."""
-
-import pytest
-
-from tvm.error import DiagnosticError
-from tvm.script import parser
-
-
-@pytest.mark.parametrize("track_span", [True, False])
-def test_signature_symbols_cross_nested_calls_parameters_return_and_body(track_span):
- function = parser.parse(
- """
-@R.function
-def main(
- x: R.Tuple(R.Tensor(("n",), "float32"), R.Tensor(("n",), "float32")),
- y: R.Tensor(("n",), "float32"),
-) -> R.Tensor(("n",), "float32"):
- n = T.int64()
- R.func_attr({"symbol": n})
- return y
-""",
- track_span=track_span,
- )
- n = function.params[0].ty.fields[0].shape[0]
- assert function.params[0].ty.fields[1].shape[0].same_as(n)
- assert function.params[1].ty.shape[0].same_as(n)
- assert function.ret_ty.shape[0].same_as(n)
- assert function.attrs["symbol"].same_as(n)
-
-
-def test_signature_strings_reuse_symbol_before_explicit_body_declaration():
- function = parser.parse(
- """
-@R.function
-def main(x: R.Tensor(("n + 1", "n"), "float32")):
- n = T.int64()
- R.func_attr({"symbol": n})
- return x
-"""
- )
- first, n = function.params[0].ty.shape
- assert first.a.same_as(n)
- assert first.b.value == 1
- assert function.attrs["symbol"].same_as(n)
-
-
-@pytest.mark.parametrize(
- "annotation",
- [
- 'R.Tensor((n, "n"), "float32")',
- 'R.Tuple(R.Tensor((n,), "float32"), R.Tensor(("n",), "float32"))',
- ],
-)
-def test_signature_read_before_introduction_remains_unbound(annotation):
- source = f"""
-@R.function
-def main(x: {annotation}):
- return x
-"""
- with pytest.raises(DiagnosticError) as error:
- parser.parse(source)
- assert isinstance(error.value.__cause__, NameError)
- assert "n" in str(error.value.__cause__)
-
-
-def test_signature_strings_do_not_replace_captured_python_names():
- function = parser.parse(
- """
-@R.function
-def main(x: R.Tensor((n, "n"), "float32"), y: R.Tensor((n,), "float32")):
- R.func_attr({"symbol": n})
- return y
-""",
- extra_vars={"n": 7},
- )
- first, n = function.params[0].ty.shape
- assert first.value == 7
- assert function.params[1].ty.shape[0].value == 7
- assert function.attrs["symbol"] == 7
- assert n.name == "n"
diff --git a/tests/scripts/task_python_unittest.sh b/tests/python/s_tir/test_s_tir_axis_binding_validation.py
old mode 100755
new mode 100644
similarity index 52%
copy from tests/scripts/task_python_unittest.sh
copy to tests/python/s_tir/test_s_tir_axis_binding_validation.py
index 6b9e7ae4d1..f82c77d040
--- a/tests/scripts/task_python_unittest.sh
+++ b/tests/python/s_tir/test_s_tir_axis_binding_validation.py
@@ -1,4 +1,3 @@
-#!/usr/bin/env bash
# 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
@@ -15,13 +14,30 @@
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
+"""Scheduled block axes reject duplicate source bindings in their native frame."""
-set -euxo pipefail
+import pytest
-export PYTHONPATH="$(pwd)/python"
-export PYTEST_ADDOPTS="${CI_PYTEST_ADD_OPTIONS:-} ${PYTEST_ADDOPTS:-}"
+import tvm
+from tvm.script import parser
-# setup tvm-ffi into python folder
-uv pip install -v --target=python ./3rdparty/tvm-ffi/
-python3 -m pytest -vvs -n auto -m "${TVM_TEST_MARKER:-not gpu}" tests/python tests/parser
+@pytest.mark.parametrize(
+ "axes",
+ [
+ "vi = T.axis.spatial(16, i)\n vi = T.axis.spatial(16, j)",
+ 'vi, vi = T.axis.remap("SS", [i, j])',
+ 'vi, vj = T.axis.remap("SS", [i, j])\n vi = T.axis.spatial(16, j)',
+ ],
+)
+def test_duplicate_block_axis_source_name_is_rejected(axes):
+ source = f"""
+@T.prim_func(s_tir=True)
+def main():
+ for i, j in T.grid(16, 16):
+ with T.sblock("block"):
+ {axes}
+ T.evaluate(vi)
+"""
+ with pytest.raises(tvm.error.DiagnosticError):
+ parser.parse(source)
diff --git a/tests/python/tirx/test_parser_dtype_migrations.py b/tests/python/s_tir/test_s_tir_migrated_source_symbols.py
similarity index 98%
rename from tests/python/tirx/test_parser_dtype_migrations.py
rename to tests/python/s_tir/test_s_tir_migrated_source_symbols.py
index 9461bf9785..6d7c5b4829 100644
--- a/tests/python/tirx/test_parser_dtype_migrations.py
+++ b/tests/python/s_tir/test_s_tir_migrated_source_symbols.py
@@ -14,7 +14,7 @@
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
-"""Scoped dtype migrations preserve symbols in the actual migrated sources."""
+"""Migrated scheduled kernels retain native symbols in their actual sources."""
import ast
import textwrap
diff --git a/tests/scripts/task_python_unittest.sh b/tests/python/script/conftest.py
old mode 100755
new mode 100644
similarity index 58%
copy from tests/scripts/task_python_unittest.sh
copy to tests/python/script/conftest.py
index 6b9e7ae4d1..51f523c17d
--- a/tests/scripts/task_python_unittest.sh
+++ b/tests/python/script/conftest.py
@@ -1,4 +1,3 @@
-#!/usr/bin/env bash
# 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
@@ -15,13 +14,25 @@
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
+"""Recording builder fixtures for the production source-to-builder parser."""
-set -euxo pipefail
+import pytest
+from dummy_builder import Language
-export PYTHONPATH="$(pwd)/python"
-export PYTEST_ADDOPTS="${CI_PYTEST_ADD_OPTIONS:-} ${PYTEST_ADDOPTS:-}"
+from tvm.script.ir_builder import base
+from tvm.script.parser import entry
-# setup tvm-ffi into python folder
-uv pip install -v --target=python ./3rdparty/tvm-ffi/
-python3 -m pytest -vvs -n auto -m "${TVM_TEST_MARKER:-not gpu}" tests/python tests/parser
+@pytest.fixture
+def language(monkeypatch):
+ language = Language()
+ monkeypatch.setattr(entry, "builder_ir", language.I)
+ return language
+
+
+@pytest.fixture
+def spanned_language(language):
+ language.I.at_ = base.at_
+ language.I.with_at_group_ = base.with_at_group_
+ language.X.inline = entry.make_macro_decorator(language.X)
+ return language
diff --git a/tests/parser/dummy_builder.py b/tests/python/script/dummy_builder.py
similarity index 93%
rename from tests/parser/dummy_builder.py
rename to tests/python/script/dummy_builder.py
index 87823e10ae..0f968b1975 100644
--- a/tests/parser/dummy_builder.py
+++ b/tests/python/script/dummy_builder.py
@@ -16,8 +16,11 @@
# under the License.
"""A recording mini-language for executing production-generated builder programs.
-Values carry only an operation and operands. Frames record entry, parameters,
-outputs and identity; they deliberately implement no TVM type system or parser.
+Values record which protocol hook the generated program called and its operands.
+Their addition records only operand order; no type inference, folding or runtime
+evaluation is implemented. Tests of expression semantics and span composition use
+real common IR/Prim nodes. Frames record entry, parameters, outputs and identity;
+they deliberately implement no TVM type system or parser.
Each test creates a fresh language so recorded effects cannot leak across cases.
"""
@@ -25,12 +28,13 @@ from contextlib import contextmanager
from dataclasses import dataclass, field
from types import SimpleNamespace
+from tvm.script.ir_builder import IRBuilder
from tvm.script.parser import entry, protocol
@dataclass(eq=False)
class Value:
- """An opaque expression with observable operands and source locations."""
+ """An opaque protocol-call record, with operands and instrumentation locations."""
op: str
args: tuple = ()
@@ -62,7 +66,7 @@ class Module(dict):
class Frame:
"""Native-style frame: declarations and body reuse the same params/result."""
- def __init__(self, language, kind, *, decl=False, values=(), span=None, local=False):
+ def __init__(self, language, kind, *, decl=False, values=(), span=None, local=False, **options):
self.language, self.kind, self.decl = language, kind, decl
self.values = values
self.function = Function() if kind == "function" else None
@@ -100,7 +104,7 @@ class Frame:
elif self.kind == "if":
self.var = Value("if", (*self.values, *self.branches))
elif self.kind == "module":
- self.language.result = self.language.functions
+ self.language.result = Module(self.language.functions)
return False
def resolve_type_var(self, name, dtype=None, *, value=None, **kwargs):
@@ -196,7 +200,8 @@ class Language:
@contextmanager
def context(self):
- yield self
+ with IRBuilder():
+ yield self
def get(self):
return self.result
@@ -226,7 +231,7 @@ class Language:
return value
def func_ret_type(self, annotation):
- self.frame().function.ret_type = annotation
+ self.frame().function.ret_type = annotation() if callable(annotation) else annotation
def func_ret_value(self, value):
self.events.append(("return", value))
diff --git a/tests/python/script/test_capture_definition_scope.py b/tests/python/script/test_capture_definition_scope.py
new file mode 100644
index 0000000000..4559794af9
--- /dev/null
+++ b/tests/python/script/test_capture_definition_scope.py
@@ -0,0 +1,402 @@
+# 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.
+
+"""Definition and body scope rules through production parser and recording frames."""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+import pytest
+
+from tvm.error import DiagnosticError
+from tvm.script import ir as I
+from tvm.script.ir_builder import IRBuilder
+from tvm.tirx.script.jit import make_jit
+
+EXTENT = 11
+VALUE = 1
+
+
+@pytest.fixture(autouse=True)
+def jit_namespace(language):
+ language.X.jit = make_jit(language.X)
+
+
+def _delayed(n, decorator, X):
+ @decorator
+ def function(output: X.tensor((n,), "int32")):
+ n = 2
+ X.record(n + VALUE)
+
+ return function
+
+
+@pytest.mark.parametrize("factory", [False, True])
+def test_reused_eager_decorator_captures_application_scope(factory, language):
+ # Before: a reused plain/factory decorator is applied where n=4, before body n=2.
+ # Expected builder: X.arg receives extent 4 from application scope.
+ X = language.X
+ decorator = X.script() if factory else X.script
+ function = _delayed(4, decorator, X)
+ assert [int(value) for value in function.params[0].args[0].args[0]] == [4]
+
+
+def test_ir_module_class_annotation_scope_does_not_replace_body_global(language):
+ # Before: class EXTENT=3 appears in an annotation and a body global read.
+ # Expected builder: X.arg receives 3; X.record receives global 11.
+ X = language.X
+
+ @I.ir_module
+ class Module:
+ EXTENT = 3
+
+ @X.script
+ def function(output: X.tensor((EXTENT,), "int32")):
+ X.record(EXTENT)
+
+ function = Module["function"]
+ assert [int(value) for value in function.params[0].args[0].args[0]] == [3]
+ assert function.body[0][1] == 11
+
+
+def test_ordinary_class_annotation_scope_does_not_replace_body_global(language):
+ # Before: an ordinary class shadows global EXTENT only for annotations.
+ # Expected builder: eager X.arg receives 3; X.record receives global 11.
+ X = language.X
+
+ class Holder:
+ EXTENT = 3
+
+ @X.script
+ def function(output: X.tensor((EXTENT,), "int32")):
+ X.record(EXTENT)
+
+ assert [int(value) for value in Holder.function.params[0].args[0].args[0]] == [3]
+ assert Holder.function.body[0][1] == 11
+
+
+def test_jit_annotation_snapshot_precedes_later_closure_mutation(language):
+ # Before: a delayed annotation/body capture n=4 before the closure changes to 9.
+ # Expected builder: specialization uses the retained 4 in both places.
+ X = language.X
+
+ def build():
+ n = 4
+
+ @X.jit
+ def function(output: X.tensor((n,), "int32")):
+ X.record(n)
+
+ n = 9
+ return function
+
+ function = build().specialize()
+ assert [int(value) for value in function.params[0].args[0].args[0]] == [4]
+ assert function.body[0][1] == 4
+
+
+def test_annotation_constructor_executes_in_required_builder_context(language):
+ # Before: a postponed annotation calls a context-sensitive constructor.
+ # Expected builder: constructor runs once at specialization inside the real IRBuilder.
+ X = language.X
+ calls = []
+
+ def annotation():
+ calls.append(IRBuilder.is_in_scope())
+ return X.tensor((5,), "int32")
+
+ @X.jit
+ def function(output: annotation()):
+ X.record(7)
+
+ assert calls == [] # postponed annotations are not evaluated at decoration
+ result = function.specialize()
+ assert calls == [True]
+ assert [int(value) for value in result.params[0].args[0].args[0]] == [5]
+
+
+def test_enclosing_namespace_used_only_by_annotation_is_retained(language):
+ # Before: an annotation-only namespace creates symbolic shape n after scope exit.
+ # Expected builder: resolve_type_var_("n") supplies the named annotation symbol.
+ X = language.X
+
+ def build():
+ dtype_namespace = X
+
+ @X.jit
+ def function(output: dtype_namespace.tensor(("n",), "int32")):
+ X.record(7)
+
+ return function
+
+ result = build().specialize()
+ assert result.params[0].args[0].args[0][0].op == "symbol"
+ assert result.params[0].args[0].args[0][0].name == "n"
+
+
+def test_attribute_name_does_not_turn_a_closure_binding_into_a_global(language):
+ # Before: closure dtype="int32" and descriptor.dtype="int64" share a spelling.
+ # Expected builder: X.record receives ("int32", 3), then ("int64", 4).
+ X = language.X
+ dtype = "int32"
+ descriptor = SimpleNamespace(dtype="int64")
+
+ @X.script
+ def function():
+ X.record((dtype, 3))
+ X.record((descriptor.dtype, 4))
+
+ first, second = function.body
+ assert first[1][0] == "int32"
+ assert first[1][1] == 3
+ assert second[1][0] == "int64"
+ assert second[1][1] == 4
+
+
+def test_active_lexical_ancestor_retains_annotation_only_names(language):
+ # Before: nested annotation-only extent/width come from two active ancestors.
+ # Expected builder: X.arg receives (extent, 3) for both extent=4 and extent=8.
+ X = language.X
+
+ def outer(extent):
+ def middle(width):
+ @X.script
+ def function(output: X.tensor((extent, width), "int32")):
+ X.record(VALUE)
+
+ return function
+
+ return middle(3)
+
+ for extent in (4, 8):
+ function = outer(extent)
+ assert [int(value) for value in function.params[0].args[0].args[0]] == [extent, 3]
+ assert function.body[0][1] == 1
+
+
+def test_active_lexical_ancestor_respects_nearest_annotation_binding(language):
+ # Before: inner extent=3 shadows outer extent=8 in a signature.
+ # Expected builder: X.arg receives nearest extent 3.
+ X = language.X
+
+ def outer(extent):
+ def middle():
+ extent = 3
+
+ @X.script
+ def function(output: X.tensor((extent,), "int32")):
+ X.record(VALUE)
+
+ return function
+
+ return middle()
+
+ function = outer(8)
+ assert [int(value) for value in function.params[0].args[0].args[0]] == [3]
+
+
+def test_unrelated_same_file_caller_does_not_supply_annotation_locals(language):
+ # Before: unrelated caller locals shadow both annotation and body global names.
+ # Expected builder: X.arg receives global 11; X.record receives global 1.
+ X = language.X
+
+ def build():
+ @X.script
+ def function(output: X.tensor((EXTENT,), "int32")):
+ X.record(VALUE)
+
+ return function
+
+ def caller():
+ EXTENT = 99 # noqa: F841
+ VALUE = 99 # noqa: F841
+ return build()
+
+ function = caller()
+ assert [int(value) for value in function.params[0].args[0].args[0]] == [11]
+ assert function.body[0][1] == 1
+
+
+def test_inactive_lexical_ancestor_is_not_replaced_by_unrelated_caller(language):
+ # Before: annotation-only extent has left scope while an unrelated caller has extent.
+ # Expected builder: raise DiagnosticError naming extent; do not capture the caller.
+ X = language.X
+
+ def outer(extent):
+ def middle():
+ @X.script
+ def function(output: X.tensor((extent,), "int32")):
+ X.record(VALUE)
+
+ return function
+
+ return middle
+
+ middle = outer(8)
+ extent = 99 # noqa: F841
+ with pytest.raises(DiagnosticError, match="extent"):
+ middle()
+
+
+def test_enclosing_class_locals_are_not_nested_annotation_scope(language):
+ # Before: outer class EXTENT=99 surrounds a nested class definition.
+ # Expected builder: nested annotation and body read global 11.
+ X = language.X
+
+ class Outer:
+ EXTENT = 99
+
+ class Inner:
+ @X.script
+ def function(output: X.tensor((EXTENT,), "int32")):
+ X.record(EXTENT)
+
+ function = Outer.Inner.function
+ assert [int(value) for value in function.params[0].args[0].args[0]] == [11]
+ assert function.body[0][1] == 11
+
+
+@pytest.mark.parametrize("factory", [False, True])
+def test_jit_retains_active_lexical_ancestor_snapshot(factory, language):
+ # Before: plain/factory JIT captures extent=8,width=3 before extent changes to 99.
+ # Expected builder: delayed X.arg receives (8, 3), X.record receives global 1.
+ X = language.X
+ decorator = X.jit() if factory else X.jit
+
+ def outer(extent):
+ def middle(width):
+ @decorator
+ def function(output: X.tensor((extent, width), "int32")):
+ X.record(VALUE)
+
+ return function
+
+ pending = middle(3)
+ extent = 99
+ return pending
+
+ function = outer(8).specialize()
+ assert [int(value) for value in function.params[0].args[0].args[0]] == [8, 3]
+ assert function.body[0][1] == 1
+
+
+def test_unrelated_intervening_call_ends_annotation_capture(language):
+ # Before: an unrelated invoke(callback) frame interrupts lexical ancestor capture.
+ # Expected builder: raise DiagnosticError naming unavailable extent.
+ X = language.X
+
+ def invoke(callback):
+ return callback()
+
+ def outer(extent):
+ def middle():
+ @X.script
+ def function(output: X.tensor((extent,), "int32")):
+ X.record(VALUE)
+
+ return function
+
+ return invoke(middle)
+
+ with pytest.raises(DiagnosticError, match="extent"):
+ outer(8)
+
+
+def _annotation_bindings(language):
+ bindings = []
+ original = language.X.bind_
+
+ def bind(value, *, name=None, ty=None, **kwargs):
+ bindings.append((name, value, ty))
+ return original(value, name=name, **kwargs)
+
+ language.X.bind_ = bind
+ return bindings
+
+
+def test_local_annotation_keeps_rhs_before_constructor_evaluation(language):
+ # Before: y: annotation() = value(x)
+ # Expected builder: X.bind_(value(x), name="y", ty=annotation()).
+ X = language.X
+ events = []
+ bindings = _annotation_bindings(language)
+
+ def annotation():
+ events.append("annotation")
+ assert IRBuilder.is_in_scope()
+ return X.tensor((2,), "float32")
+
+ def value(x):
+ events.append("rhs")
+ return X.value(x, x)
+
+ @X.script
+ def function(x: X.tensor((2,), "float32")):
+ y: annotation() = value(x)
+ return y
+
+ assert events == ["rhs", "annotation"]
+ name, rhs, ty = bindings[0]
+ assert name == "y" and ty.args[:2] == ((2,), "float32")
+ assert rhs.args == (function.params[0], function.params[0])
+ assert function.body[0] == ("return", rhs)
+
+
+def test_local_annotation_scope_does_not_overwrite_ordinary_body_global(language):
+ # Before: class EXTENT=3; body reads global EXTENT; y: tensor((EXTENT,), dtype).
+ # Expected builder: X.record(11); X.bind_(rhs, ty=X.tensor((3,), "float32")).
+ X = language.X
+ dtype = "float32"
+ bindings = _annotation_bindings(language)
+
+ @I.ir_module
+ class Module:
+ EXTENT = 3
+
+ @X.script
+ def main(x: X.tensor((3,), "float32")):
+ X.record(EXTENT)
+ y: X.tensor((EXTENT,), dtype) = X.value(x, x)
+ return y
+
+ function = Module["main"]
+ name, rhs, ty = next(binding for binding in bindings if binding[0] == "y")
+ assert function.body[0] == ("emit", 11)
+ assert name == "y" and ty.args[:2] == ((3,), "float32")
+ assert rhs.args == (function.params[0], function.params[0])
+ assert function.body[1] == ("return", rhs)
+
+
+def test_local_annotation_preserves_lambda_and_comprehension_bindings(language):
+ # Before: annotation's lambda dtype and comprehension size shadow captured names.
+ # Expected builder: X.bind_(rhs, ty=X.tensor((2,), "float32")).
+ X = language.X
+ dtype = "int64" # noqa: F841
+ size = 9 # noqa: F841
+ sizes = (2,)
+ bindings = _annotation_bindings(language)
+
+ @X.script
+ def function(x: X.tensor((2,), "float32")):
+ y: (lambda dtype: X.tensor(tuple(size for size in sizes), dtype))("float32") = X.value(x, x)
+ return y
+
+ name, rhs, ty = bindings[0]
+ assert name == "y" and ty.args[:2] == ((2,), "float32")
+ assert rhs.args == (function.params[0], function.params[0])
+ assert function.body[0] == ("return", rhs)
diff --git a/tests/python/script/test_capture_frontend_scope.py b/tests/python/script/test_capture_frontend_scope.py
new file mode 100644
index 0000000000..2f0d784332
--- /dev/null
+++ b/tests/python/script/test_capture_frontend_scope.py
@@ -0,0 +1,232 @@
+# 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.
+
+"""Frontend dispatch, lexical capture, and real shared IR source locations."""
+
+import pytest
+from dummy_builder import Function
+
+from tvm import ir
+from tvm.script import ir as I
+from tvm.script.parser import entry
+from tvm.script.parser.source import Source
+from tvm.tirx.script.jit import make_jit
+
+VALUE = 1
+MACRO_VALUE = 2
+
+
+def test_ordinary_class_member_constructs_function(language):
+ # Before: ordinary class with a decorated member.
+ # Expected builder: enter X.function immediately and emit the member body.
+ X = language.X
+
+ class Holder:
+ @X.script
+ def function():
+ X.record(7)
+
+ assert isinstance(Holder.function, Function)
+ assert Holder.function.body == [("emit", 7)]
+
+
+def test_ir_module_defers_members_until_forward_signatures_exist(language):
+ # Before: main calls Module.identity, declared later in the class.
+ # Expected builder: declare both signatures, then call the reserved identity global.
+ X = language.X
+
+ @I.ir_module
+ class Module:
+ @X.script
+ def main(x: X.tensor((2,), "float32")):
+ return Module.identity(x)
+
+ @X.script
+ def identity(x: X.tensor((2,), "float32")):
+ return x
+
+ call = Module["main"].body[0][1]
+ assert call.op == "call"
+ assert call.args[0] is language.references["identity"]
+ assert call.args[1] is Module["main"].params[0]
+ assert Module["identity"].body[0][1] is Module["identity"].params[0]
+ entries = [event[1:3] for event in language.events if event[0] == "enter"]
+ assert entries == [
+ ("module", False),
+ ("function", True),
+ ("function", True),
+ ("function", False),
+ ("function", False),
+ ]
+
+
+@pytest.fixture
+def spanned_language(spanned_language):
+ language = spanned_language
+ language.X.evaluate = lambda value: value
+ language.X.call_extern = lambda dtype, name: ir.Call(ir.GlobalVar(name), [], ret_ty=dtype)
+ return language
+
+
+def _position(span):
+ return span.line, span.column, span.end_line, span.end_column
+
+
+@pytest.mark.parametrize("entrypoint", ["source", "function"])
+def test_source_and_ir_call_spans_use_one_based_columns(spanned_language, entrypoint):
+ # Before: evaluate(call_extern(...)) through source and callable entry points.
+ # Expected builder: production I.at_ attaches Source.to_span(call), one based.
+ language = spanned_language
+ X = language.X
+
+ def direct():
+ X.evaluate(X.call_extern("int32", "direct"))
+
+ if entrypoint == "source":
+ program = '@X.script\ndef direct():\n X.evaluate(X.call_extern("int32", "direct"))\n'
+ source = Source(program)
+ function = entry.parse(program, extra_vars={"X": X})
+ else:
+ source = Source(direct)
+ function = X.script(direct)
+ call = source.as_ast().body[0].body[0].value.args[0]
+ expected = source.to_span(call)
+ assert expected.column == call.col_offset + source.start_column + 1
+ assert expected.end_column == call.end_col_offset + source.start_column + 1
+ assert _position(function.body[0][1].span) == _position(expected)
+ assert function.body[0][1].span.source_name.name == source.source_name
+
+
+def test_nested_helper_spans_preserve_caller_and_definition_columns(spanned_language):
+ # Before: main -> outer inline helper -> inner inline helper -> call.
+ # Expected builder: production span stack retains all three call coordinates in order.
+ X = spanned_language.X
+ text = """@X.inline
+def inner():
+ X.evaluate(X.call_extern("int32", "nested"))
+@X.inline
+def outer():
+ inner()
+@X.script
+def main():
+ outer()
+"""
+ source = Source(text)
+ inner, outer, main = source.as_ast().body
+ calls = [main.body[0].value, outer.body[0].value, inner.body[0].value.args[0]]
+ expected = [_position(source.to_span(call)) for call in calls]
+ assert [position[1] for position in expected] == [5, 5, 16]
+ function = entry.parse(text, extra_vars={"X": X})
+ span = function.body[0][1].span
+ assert isinstance(span, ir.SequentialSpan)
+ assert [_position(item) for item in span.spans] == expected
+ assert all(item.source_name.name == "<str>" for item in span.spans)
+
+
+def test_annotation_only_enclosing_binding_is_captured(language):
+ # Before: a quoted annotation uses an enclosing shape absent from body bytecode.
+ # Expected builder: X.arg sees (3,), never the unrelated caller's (7,).
+ X = language.X
+
+ def build():
+ shape = (3,)
+
+ @X.script
+ def function(A: "X.tensor(shape, 'int32')"):
+ X.record(1)
+
+ return function
+
+ shape = (7,) # noqa: F841
+ function = build()
+ assert function.params[0].args[0].args[:2] == ((3,), "int32")
+ assert function.body == [("emit", 1)]
+
+
+def _build_symbolic_functions(X):
+ @I.ir_module
+ class Module:
+ @X.script
+ def first(x: X.tensor(("n",), "float32")):
+ n = X.symbol() # noqa: F841
+ return x
+
+ @X.script
+ def second(x: X.tensor(("n",), "float32")):
+ n = X.symbol() # noqa: F841
+ return x
+
+ return Module
+
+
+def test_dynamic_caller_symbol_does_not_join_function_declarations(language):
+ # Before: two function signatures declare "n" while a caller has its own n.
+ # Expected builder: each function frame resolves its own n, independent of the caller.
+ n = ir.Var("n", "int64")
+ module = _build_symbolic_functions(language.X)
+ first = module["first"].params[0].args[0].args[0][0]
+ second = module["second"].params[0].args[0].args[0][0]
+ assert first is not second
+ assert first is not n
+ assert second is not n
+ declared = [event[2] for event in language.events if event[:2] == ("symbol", "n")]
+ assert all(symbol is first or symbol is second for symbol in declared)
+ assert sum(symbol is first for symbol in declared) >= 2
+ assert sum(symbol is second for symbol in declared) >= 2
+
+
+@pytest.mark.parametrize("hygienic,expected", [(True, 2), (False, 1)])
+def test_macro_capture_policy_remains_explicit(language, hygienic, expected, monkeypatch):
+ # Before: macro captures MACRO_VALUE=2; the global changes to 1 before invocation.
+ # Expected builder: hygienic macro records 2; caller-environment macro records 1.
+ X = language.X
+ X.macro = entry.make_macro_decorator(X)
+ monkeypatch.setitem(globals(), "X", X)
+ monkeypatch.setitem(globals(), "MACRO_VALUE", 2)
+
+ @X.macro(hygienic=hygienic)
+ def write():
+ X.record(MACRO_VALUE)
+
+ monkeypatch.setitem(globals(), "MACRO_VALUE", 1)
+
+ @X.script
+ def function():
+ write()
+
+ assert function.body[0] == ("emit", expected)
+ assert [event for event in language.events if event[0] == "record"] == [("record", expected)]
+
+
+def _define_delayed_annotation(shape, X):
+ @X.jit
+ def function(output: "X.tensor(shape, 'int32')"):
+ X.record(VALUE)
+
+ return function
+
+
+def test_delayed_jit_retains_annotation_only_definition_binding(language):
+ # Before: delayed signature captures shape=(3,), body reads lexical global VALUE.
+ # Expected builder: after scope exits X.arg sees (3,), X.record sees 1.
+ language.X.jit = make_jit(language.X)
+ pending = _define_delayed_annotation((3,), language.X)
+ shape = (7,) # noqa: F841
+ VALUE = 2 # noqa: F841
+ function = pending.specialize()
+ assert function.params[0].args[0].args[:2] == ((3,), "int32")
+ assert function.body == [("emit", 1)]
diff --git a/tests/python/unittest/test_parser_class_source.py b/tests/python/script/test_capture_gallery_source.py
similarity index 55%
rename from tests/python/unittest/test_parser_class_source.py
rename to tests/python/script/test_capture_gallery_source.py
index a00a0c4271..051f81a264 100644
--- a/tests/python/unittest/test_parser_class_source.py
+++ b/tests/python/script/test_capture_gallery_source.py
@@ -22,13 +22,14 @@ import sys
import pytest
+from tvm import ir
from tvm.script import ir as I
-from tvm.script import tirx as T
+from tvm.script.ir_builder import base
-def _execute(source, filename, monkeypatch):
+def _execute(source, filename, monkeypatch, X):
module = importlib.util.module_from_spec(importlib.util.spec_from_loader("__main__", None))
- module.__dict__.update(I=I, T=T)
+ module.__dict__.update(I=I, X=X)
with monkeypatch.context() as patch:
patch.setitem(sys.modules, "__main__", module)
exec(compile(source, filename, "exec"), module.__dict__)
@@ -36,20 +37,23 @@ def _execute(source, filename, monkeypatch):
@pytest.mark.parametrize("cached", [False, True])
-def test_gallery_classes_retain_distinct_source_locations(tmp_path, monkeypatch, cached):
+def test_gallery_classes_retain_distinct_source_locations(tmp_path, monkeypatch, cached, language):
+ # Before: repeated class names use plain/factory decorators and file/cache source.
+ # Expected builder: each class retains its own body value, filename, and line.
+ _native_locations(language)
source = """
@I.ir_module
class Repeated:
- @T.prim_func
- def main(A: T.Buffer((1,), "int32")):
- A[0] = 11
+ @X.script
+ def main(A: X.tensor((1,), "int32")):
+ X.store(11)
first = Repeated
@I.ir_module()
class Repeated:
- @T.prim_func
- def main(A: T.Buffer((1,), "int32")):
- A[0] = 22
+ @X.script
+ def main(A: X.tensor((1,), "int32")):
+ X.store(22)
second = Repeated
"""
filename = "<gallery-cached-classes>" if cached else str(tmp_path / "gallery.py")
@@ -59,24 +63,27 @@ second = Repeated
)
else:
(tmp_path / "gallery.py").write_text(source)
- module = _execute(source, filename, monkeypatch)
+ module = _execute(source, filename, monkeypatch, language.X)
for result, value, line in ((module.first, 11, 6), (module.second, 22, 13)):
- store = result["main"].body
- assert store.value.value == value
+ store = result["main"].body[0][1]
+ assert store.args[0].value == value
assert store.span.line == line
assert store.span.source_name.name == filename
-def test_gallery_nested_class_preserves_definition_scope(tmp_path, monkeypatch):
+def test_gallery_nested_class_preserves_definition_scope(tmp_path, monkeypatch, language):
+ # Before: nested class captures n; an unrelated caller shadows global VALUE.
+ # Expected builder: X.arg receives shape=(4,), body records lexical VALUE=7.
+ _native_locations(language)
source = """
VALUE = 7
def build(n):
@I.ir_module
class Module:
- @T.prim_func
- def main(A: T.Buffer((n,), "int32")):
- A[0] = VALUE
+ @X.script
+ def main(A: X.tensor((n,), "int32")):
+ X.store(VALUE)
return Module
def caller():
@@ -87,13 +94,15 @@ result = caller()
"""
path = tmp_path / "nested_gallery.py"
path.write_text(source)
- module = _execute(source, str(path), monkeypatch)
+ module = _execute(source, str(path), monkeypatch, language.X)
function = module.result["main"]
- assert function.params[0].ty.shape[0].value == 4
- assert function.body.value.value == 7
+ assert function.params[0].args[0].args[0][0] == 4
+ assert function.body[0][1].args[0].value == 7
-def test_gallery_empty_class_needs_no_member_source(tmp_path, monkeypatch):
+def test_gallery_empty_class_needs_no_member_source(tmp_path, monkeypatch, language):
+ # Before: module class contains only pass.
+ # Expected builder: an empty module frame still recovers the class source.
source = """
@I.ir_module
class Empty:
@@ -101,10 +110,25 @@ class Empty:
"""
path = tmp_path / "empty_gallery.py"
path.write_text(source)
- module = _execute(source, str(path), monkeypatch)
- assert len(module.Empty.functions) == 0
+ module = _execute(source, str(path), monkeypatch, language.X)
+ assert len(module.Empty) == 0
-def test_unavailable_class_source_still_raises(monkeypatch):
+def test_unavailable_class_source_still_raises(monkeypatch, language):
+ # Before: an uncached synthetic filename has no recoverable class source.
+ # Expected builder: source acquisition raises OSError before construction.
with pytest.raises(OSError, match="source code not available"):
- _execute("@I.ir_module\nclass Empty:\n pass\n", "<missing-gallery-source>", monkeypatch)
+ _execute(
+ "@I.ir_module\nclass Empty:\n pass\n",
+ "<missing-gallery-source>",
+ monkeypatch,
+ language.X,
+ )
+
+
+def _native_locations(language):
+ language.I.at_ = base.at_
+ language.I.with_at_group_ = base.with_at_group_
+ language.X.store = lambda value: ir.Call(
+ ir.GlobalVar("store"), [ir.prim.IntImm("int32", value)], ret_ty="int32"
+ )
diff --git a/tests/python/script/test_capture_nonlocal.py b/tests/python/script/test_capture_nonlocal.py
new file mode 100644
index 0000000000..eb9e51d024
--- /dev/null
+++ b/tests/python/script/test_capture_nonlocal.py
@@ -0,0 +1,66 @@
+# 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.
+"""Enclosing lexical declarations retain captured values during construction."""
+
+import pytest
+
+from tvm.script.parser import entry
+
+
+@pytest.mark.parametrize(
+ "source,captured,expected_source",
+ [
+ (
+ """
+@X.script
+def main(x: X.tensor((2,), dtype)):
+ nonlocal dtype
+ return x
+""",
+ {"dtype": "float32"},
+ '@X.script\ndef main(x: X.tensor((2,), "float32")):\n return x\n',
+ ),
+ (
+ """
+@X.script
+def main():
+ nonlocal value
+ X.record(value + 1)
+""",
+ {"value": 3},
+ "@X.script\ndef main():\n X.record(4)\n",
+ ),
+ ],
+)
+def test_nonlocal_declaration_preserves_captured_values(
+ language, source, captured, expected_source
+):
+ # Before: nonlocal appears in signature-only and body-arithmetic captures.
+ # Expected builder: preserve annotation/value, return identity, and caller captures.
+ captures = {"X": language.X, **captured}
+ original_captures = dict(captures)
+ expected = entry.parse(expected_source, extra_vars={"X": language.X})
+ actual = entry.parse(source, extra_vars=captures)
+ assert actual.name == expected.name
+ assert len(actual.params) == len(expected.params)
+ if actual.params:
+ assert actual.params[0].args[0].args == expected.params[0].args[0].args
+ assert actual.body[0] == ("return", actual.params[0])
+ assert expected.body[0] == ("return", expected.params[0])
+ else:
+ assert actual.body == expected.body == [("emit", 4)]
+ assert captures == original_captures
diff --git a/tests/parser/test_parser.py b/tests/python/script/test_parser.py
similarity index 97%
rename from tests/parser/test_parser.py
rename to tests/python/script/test_parser.py
index 56f8c26da9..1b0c540e0a 100644
--- a/tests/parser/test_parser.py
+++ b/tests/python/script/test_parser.py
@@ -22,18 +22,11 @@ import ast
from types import SimpleNamespace
import pytest
-from dummy_builder import Language, Value
+from dummy_builder import Value
from tvm.script.parser import entry, protocol
-@pytest.fixture
-def language(monkeypatch):
- language = Language()
- monkeypatch.setattr(entry, "builder_ir", language.I)
- return language
-
-
@pytest.mark.parametrize(
"arguments",
[
@@ -152,12 +145,12 @@ def test_policy_registration_is_immutable_and_aliases_keep_identity():
assert protocol.get_args_policy([]) is None
assert protocol.get_args_policy(None) is None
- @protocol.expr_str_args("values", scalar_strings=False)
+ @protocol.args_policy({"values": "expr_str"}, scalar_strings=False)
def shorthand(values):
return values
assert dict(protocol.get_args_policy(shorthand).fields) == {"values": "expr_str"}
- assert protocol.expr_str_policy(shorthand).fields == ("values",)
+ assert protocol.get_args_policy(shorthand).expression.scalar_strings is False
@pytest.mark.parametrize(
@@ -809,3 +802,23 @@ def test_non_call_expression_reads_keep_their_source_range(language, expression)
assert result.body[0][1] is expected
assert [(loc, result) for loc, result in located if loc == location] == [(location, expected)]
assert reads == {"holder.item": ["attribute"], "items[0]": [0]}.get(expression, [])
+
+
+@pytest.mark.parametrize("dtype", [None, "int32", "int64"])
+def test_argument_policy_preserves_expression_dtype(language, dtype):
+ @protocol.args_policy({"values": "expr_str"}, dtype=dtype)
+ def shape(values):
+ return values
+
+ language.X.shape = shape
+ function = language.parse("""
+@X.script
+def main():
+ X.shape(("n", "n + 1"))
+""")
+ n, increment = function.body[0][1]
+ assert n.args == (dtype,)
+ assert increment.op == "add"
+ assert increment.args[0] is n
+ assert increment.args[1] == 1
+ assert protocol.get_args_policy(shape).expression.dtype == dtype
diff --git a/tests/scripts/task_python_unittest.sh b/tests/python/script/test_parser_bypass_source_attachment.py
old mode 100755
new mode 100644
similarity index 53%
copy from tests/scripts/task_python_unittest.sh
copy to tests/python/script/test_parser_bypass_source_attachment.py
index 6b9e7ae4d1..c3b84d05f9
--- a/tests/scripts/task_python_unittest.sh
+++ b/tests/python/script/test_parser_bypass_source_attachment.py
@@ -1,4 +1,3 @@
-#!/usr/bin/env bash
# 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
@@ -15,13 +14,22 @@
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
+"""Source attachment preserves common IR identity through binding bypass."""
-set -euxo pipefail
+import pytest
-export PYTHONPATH="$(pwd)/python"
-export PYTEST_ADDOPTS="${CI_PYTEST_ADD_OPTIONS:-} ${PYTEST_ADDOPTS:-}"
+import tvm
+from tvm.script.ir_builder import IRBuilder
+from tvm.script.ir_builder import ir as I
+from tvm.script.ir_builder.base import BypassBind
-# setup tvm-ffi into python folder
-uv pip install -v --target=python ./3rdparty/tvm-ffi/
-python3 -m pytest -vvs -n auto -m "${TVM_TEST_MARKER:-not gpu}" tests/python tests/parser
+@pytest.mark.parametrize("count", [1, 2])
+def test_bypass_source_attachment_preserves_value_identity(count):
+ span = tvm.ir.Span(tvm.ir.SourceName("scope.py"), 3, 3, 4, 25)
+ with IRBuilder():
+ values = tuple(tvm.ir.Var("", "int32") for _ in range(count))
+ result = BypassBind(values[0] if count == 1 else values)
+ assert I.at_(span, result) is result
+ for value in values:
+ assert value.span.same_as(span)
diff --git a/tests/python/tirx/test_parser_call_scopes.py b/tests/python/script/test_parser_call_scopes.py
similarity index 58%
rename from tests/python/tirx/test_parser_call_scopes.py
rename to tests/python/script/test_parser_call_scopes.py
index f111a3af6c..b4ada811ee 100644
--- a/tests/python/tirx/test_parser_call_scopes.py
+++ b/tests/python/script/test_parser_call_scopes.py
@@ -14,15 +14,15 @@
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
-"""Uniform source-call evaluation and exception-safe caller locations."""
+"""Production call scopes preserve common node identity and definition locations."""
import pytest
-from tvm import ir, tirx
-from tvm.script import parser
-from tvm.script import tirx as T
+from tvm import ir
+from tvm.ir import prim
from tvm.script.ir_builder import IRBuilder
from tvm.script.ir_builder import ir as I
+from tvm.script.parser import entry
def loc(line, name="calls.py"):
@@ -34,37 +34,45 @@ def span_lines(value):
return [span.line for span in spans]
+@pytest.fixture
+def spanned(spanned_language):
+ language = spanned_language
+ language.X.node = lambda value: prim.IntImm("int32", value)
+ return language
+
+
def test_call_scope_keeps_result_identity_and_restores_after_exception():
seen = []
with IRBuilder():
- value = tirx.IntImm("int32", 1)
+ value = prim.IntImm("int32", 1)
assert I.with_at_group_(loc(1), lambda: (seen.append(1), value)[1]) is value
assert seen == [1]
with pytest.raises(ValueError, match="failure"):
I.with_at_group_(loc(2), lambda: (_ for _ in ()).throw(ValueError("failure")))
- other = I.at_(loc(3), tirx.IntImm("int32", 2))
+ other = I.at_(loc(3), prim.IntImm("int32", 2))
assert span_lines(other) == [3]
-def test_scoped_helper_multiple_emissions_and_normal_return():
+def test_scoped_helper_multiple_emissions_and_normal_return(spanned):
marker = object()
- with IRBuilder() as builder:
- with T.function():
- T.func_name("multiple")
+ with spanned.context(), spanned.X.function():
- def helper():
- I.with_at_group_(loc(8), lambda: T.evaluate(1))
- I.with_at_group_(loc(9), lambda: T.evaluate(2))
- return marker
+ def helper():
+ first = I.with_at_group_(loc(8), lambda: prim.IntImm("int32", 1))
+ second = I.with_at_group_(loc(9), lambda: prim.IntImm("int32", 2))
+ spanned.X.emit_(first)
+ spanned.X.emit_(second)
+ return marker
- assert I.with_at_group_(loc(4), helper) is marker
- statements = builder.get().body.seq
+ assert I.with_at_group_(loc(4), helper) is marker
+ statements = [value for _, value in spanned.result.body]
assert len(statements) == 2
+ assert [int(value) for value in statements] == [1, 2]
assert span_lines(statements[0]) == [4, 8]
assert span_lines(statements[1]) == [4, 9]
-def test_source_call_callee_arguments_and_keywords_evaluate_once_in_order():
+def test_source_call_callee_arguments_and_keywords_evaluate_once_in_order(language):
seen = []
def callee():
@@ -81,35 +89,36 @@ def test_source_call_callee_arguments_and_keywords_evaluate_once_in_order():
return value
source = """
-@T.prim_func
+@X.script
def main():
- T.evaluate(callee()(operand(1), b=operand(2)))
+ X.record(callee()(operand(1), b=operand(2)))
"""
- result = parser.parse(source, extra_vars={"callee": callee, "operand": operand})
+ result = language.parse(source, callee=callee, operand=operand)
assert seen == ["callee", 1, 2, (1, 2)]
- assert isinstance(result.body, tirx.Evaluate)
- assert result.body.value.value == 3
+ assert result.body == [("emit", 3)]
-def test_module_source_calls_have_context_before_annotations():
+def test_module_source_calls_have_context_before_annotations(spanned):
seen = []
def record():
- node = tirx.IntImm("int32", 3)
+ node = prim.IntImm("int32", 3)
IRBuilder.current()._set_current_source_span(node)
seen.append(node.span)
return {}
- module = parser.parse(
+ spanned.I.module_attrs = lambda attrs: None
+ module = spanned.parse(
"""
@I.ir_module
class Module:
I.module_attrs(record())
- @T.prim_func
+ @X.script
def main():
- T.evaluate(1)
+ X.record(1)
""",
- extra_vars={"record": record},
+ I=spanned.I,
+ record=record,
)
assert "main" in module
assert len(seen) == 1
@@ -117,20 +126,27 @@ class Module:
assert seen[0].line == 4
-def test_source_inline_keeps_caller_and_each_definition_location():
- function = parser.parse(
+def test_source_inline_keeps_caller_and_each_definition_location(spanned):
+ function = entry.parse(
"""
-@T.inline
+@X.inline
def inner(x):
- T.evaluate(x)
- T.evaluate(x + 1)
-@T.prim_func
+ X.record(X.node(x))
+ X.record(X.node(x + 1))
+@X.script
def main():
inner(1)
""",
+ extra_vars={"X": spanned.X},
filename="inline_scope.py",
)
- statements = function.body.seq
+ statements = [value for _, value in function.body if isinstance(value, prim.IntImm)]
assert len(statements) == 2
+ assert [int(value) for value in statements] == [1, 2]
assert span_lines(statements[0]) == [8, 4]
assert span_lines(statements[1]) == [8, 5]
+ assert all(
+ str(span.source_name.name) == "inline_scope.py"
+ for value in statements
+ for span in value.span.spans
+ )
diff --git a/tests/python/script/test_parser_comparison_semantics.py b/tests/python/script/test_parser_comparison_semantics.py
new file mode 100644
index 0000000000..bffd71b264
--- /dev/null
+++ b/tests/python/script/test_parser_comparison_semantics.py
@@ -0,0 +1,347 @@
+# 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.
+"""Source comparison semantics using recording frames and common primitive IR nodes."""
+
+from functools import reduce
+
+import pytest
+import tvm_ffi
+
+from tvm import ir
+from tvm.ir import prim
+from tvm.ir._overload_prim_expr import EqualOp
+from tvm.script.ir_builder import base
+from tvm.script.parser import entry
+
+OPERATORS = [("<", "LT"), ("<=", "LE"), (">", "GT"), (">=", "GE"), ("==", "EQ"), ("!=", "NE")]
+
+
+@pytest.fixture
+def language(language):
+ language.I.at_ = base.at
+ language.I.with_at_group_ = base.with_at_group_
+ for _, kind in OPERATORS:
+ constructor = getattr(prim._ffi_api, "_Op" + kind)
+ setattr(language.X, kind.lower(), lambda lhs, rhs, make=constructor: make(lhs, rhs, None))
+
+ def conjunction(*conditions, chain):
+ language.events.append(("chain", chain))
+ return reduce(lambda rhs, lhs: prim.And(lhs, rhs), reversed(conditions))
+
+ language.X.and_ = conjunction
+ return language
+
+
+def parse(language, source, *, track_span=True, **captures):
+ return entry.parse(
+ source,
+ extra_vars={"X": language.X, **captures},
+ filename="comparison.py",
+ track_span=track_span,
+ )
+
+
+@pytest.mark.parametrize("operator,kind", OPERATORS)
+@pytest.mark.parametrize("literal_left", [True, False])
+@pytest.mark.parametrize("track_span", [True, False])
+def test_written_comparison_order(language, operator, kind, literal_left, track_span):
+ x = ir.Var("x", "int32")
+ expression = f"0 {operator} x" if literal_left else f"x {operator} 0"
+ actual = parse(
+ language,
+ f"@X.script\ndef main():\n {expression}\n",
+ x=x,
+ track_span=track_span,
+ ).body[0][1]
+ operands = (0, x) if literal_left else (x, 0)
+ ir.assert_structural_equal(actual, getattr(prim, kind)(*operands))
+ if track_span:
+ assert actual.span is not None
+ else:
+ assert actual.span is None
+
+
+@pytest.mark.parametrize("dtype", ["int64", "uint32", "float32", "int32x4", "float32x4"])
+def test_literal_uses_ir_operand_type_and_lanes(language, dtype):
+ x = ir.Var("x", dtype)
+ value = parse(language, "@X.script\ndef main():\n 0 < x\n", x=x).body[0][1]
+ assert isinstance(value, prim.LT)
+ assert str(value.a.ty) == str(value.b.ty) == dtype
+ assert value.b.same_as(x)
+
+
+@pytest.mark.parametrize("operator,kind", OPERATORS)
+@pytest.mark.parametrize("other_kind", ["host", "primitive"])
+def test_custom_host_comparison_result_is_preserved(language, operator, kind, other_kind):
+ class Result:
+ def __bool__(self):
+ raise AssertionError("custom comparison result must not be truth-tested")
+
+ def asobject(self):
+ raise AssertionError("custom comparison result must not be converted")
+
+ result = Result()
+ calls = []
+
+ class Host:
+ pass
+
+ def compare(self, other):
+ calls.append(other)
+ return result
+
+ setattr(Host, "__" + kind.lower() + "__", compare)
+
+ def consume(value):
+ assert value is result
+ return 0
+
+ right = ir.Var("x", "int32") if other_kind == "primitive" else object()
+ parse(
+ language,
+ f"@X.script\ndef main():\n consume(X.constexpr(left {operator} right))\n",
+ left=Host(),
+ right=right,
+ consume=consume,
+ )
+ assert len(calls) == 1
+ if other_kind == "primitive":
+ assert calls[0].same_as(right)
+ else:
+ assert calls[0] is right
+
+
+def test_numeric_subclass_keeps_custom_comparison(language):
+ seen = []
+ result = object()
+
+ class HostInt(int):
+ def __lt__(self, other):
+ seen.append(other)
+ return result
+
+ def consume(value):
+ assert value is result
+ return 0
+
+ parse(
+ language,
+ "@X.script\ndef main():\n consume(X.constexpr(left < x))\n",
+ x=ir.Var("x", "int32"),
+ left=HostInt(0),
+ consume=consume,
+ )
+ assert len(seen) == 1
+
+
+def test_host_ordering_does_not_materialize_an_equality_result(language):
+ result = ir.Var("host_result", "int32") == 0
+
+ class Host:
+ def __lt__(self, other):
+ return result
+
+ def consume(value):
+ assert value is result
+ return 0
+
+ parse(
+ language,
+ "@X.script\ndef main():\n consume(X.constexpr(left < right))\n",
+ left=Host(),
+ right=Host(),
+ consume=consume,
+ )
+
+
+def test_chain_evaluates_source_operands_once_in_order(language):
+ seen = []
+
+ def operand(index, value):
+ seen.append(index)
+ return value
+
+ x, y = ir.Var("x", "int32"), ir.Var("y", "int32")
+ actual = parse(
+ language,
+ """
+@X.script
+def main():
+ operand(0, 0) < operand(1, x) <= operand(2, y) != operand(3, 3)
+""",
+ operand=operand,
+ x=x,
+ y=y,
+ ).body[0][1]
+ expected = prim.And(prim.LT(0, x), prim.And(prim.LE(x, y), prim.NE(y, 3)))
+ ir.assert_structural_equal(actual, expected)
+ assert seen == [0, 1, 2, 3]
+ chains = [event[1] for event in language.events if event[0] == "chain"]
+ assert len(chains) == 1
+ assert chains[0][0] == 0 and chains[0][3] == 3
+ assert chains[0][1] is x and chains[0][2] is y
+
+
+def test_constexpr_keeps_python_comparison_and_chain_short_circuit(language):
+ seen = []
+
+ def operand(index, value):
+ seen.append(index)
+ return value
+
+ def invalid():
+ raise AssertionError("constexpr comparison chain must short-circuit")
+
+ actual = parse(
+ language,
+ """
+@X.script
+def main():
+ if X.constexpr(operand(0, 2) < operand(1, 1) < invalid()):
+ 0
+ elif X.constexpr(x == x):
+ 1
+""",
+ operand=operand,
+ invalid=invalid,
+ x=ir.Var("x", "int32"),
+ )
+ assert seen == [0, 1]
+ assert actual.body == [("emit", 1)]
+
+
+@pytest.mark.parametrize("operator,kind", OPERATORS)
+@pytest.mark.parametrize("dtype", ["int64", "float32", "int64x4"])
+def test_comparisons_use_native_promotion_and_broadcast(language, operator, kind, dtype):
+ x, y = ir.Var("x", "int32"), ir.Var("y", dtype)
+ actual = parse(
+ language,
+ f"@X.script\ndef main():\n x {operator} y\n",
+ x=x,
+ y=y,
+ ).body[0][1]
+ lhs = prim.Broadcast(prim.Cast("int64", x), 4) if dtype.endswith("x4") else prim.Cast(dtype, x)
+ ir.assert_structural_equal(actual, getattr(prim, kind)(lhs, y))
+
+
+@pytest.mark.parametrize("operator,kind", [("==", prim.EQ), ("!=", prim.NE)])
+@pytest.mark.parametrize("track_span", [True, False])
+def test_symbolic_equality_reaches_typed_consumer(language, operator, kind, track_span):
+ seen = []
+
+ def consume(value):
+ assert isinstance(value, kind)
+ assert str(value.ty) == "bool"
+ seen.append(value)
+ return value
+
+ x = ir.Var("x", "int32")
+ parse(
+ language,
+ f"@X.script\ndef main():\n consume(x {operator} 0)\n",
+ consume=consume,
+ x=x,
+ track_span=track_span,
+ )
+ assert len(seen) == 1
+ assert seen[0].a.same_as(x)
+ if track_span:
+ assert seen[0].span is not None
+ else:
+ assert seen[0].span is None
+
+
+def test_python_comparisons_remain_python_booleans(language):
+ seen = []
+
+ def consume(value):
+ assert type(value) is bool
+ seen.append(value)
+ return int(value)
+
+ parse(
+ language,
+ """
+@X.script
+def main():
+ consume(X.constexpr([1, 2] == [1, 2]))
+ consume(X.constexpr("x" != "y"))
+""",
+ consume=consume,
+ )
+ assert seen == [True, True]
+
+
+def test_host_equality_result_is_not_arbitrarily_converted(language):
+ class HostResult(tvm_ffi.ObjectConvertible):
+ def asobject(self):
+ raise AssertionError("host comparison result must not be converted")
+
+ result = HostResult()
+
+ class Host:
+ def __eq__(self, other):
+ return result
+
+ seen = []
+
+ def consume(value):
+ assert value is result
+ seen.append(value)
+ return 0
+
+ source = "@X.script\ndef main():\n consume(X.constexpr(left == right))\n"
+ parse(language, source, left=Host(), right=Host(), consume=consume)
+ assert seen == [result]
+ assert seen[0] is result
+
+ class CustomEquality(EqualOp):
+ def asobject(self):
+ raise AssertionError("custom equality subclasses are host values")
+
+ custom = CustomEquality(ir.Var("x", "int32"), 0)
+ result = custom
+ parse(language, source, left=Host(), right=Host(), consume=consume)
+ assert seen[-1] is custom
+
+
+@pytest.mark.parametrize(
+ "expression", ["operand(0) == operand(1)", "operand(0) == operand(1) != operand(2)"]
+)
+def test_comparison_operands_evaluate_once_in_order(language, expression):
+ seen = []
+
+ def operand(index, value):
+ seen.append(index)
+ return value
+
+ def consume(value):
+ assert isinstance(value, ir.Expr)
+ assert str(value.ty) == "bool"
+ return value
+
+ expression = expression.replace("operand(0)", "operand(0, value0)")
+ expression = expression.replace("operand(1)", "operand(1, value1)")
+ expression = expression.replace("operand(2)", "operand(2, value2)")
+ parse(
+ language,
+ "@X.script\ndef main():\n" + f" consume({expression})\n",
+ operand=operand,
+ consume=consume,
+ **{f"value{i}": ir.Var(f"value{i}", "int32") for i in range(3)},
+ )
+ assert seen == ([0, 1, 2] if "!=" in expression else [0, 1])
diff --git a/tests/python/script/test_parser_host_selection.py b/tests/python/script/test_parser_host_selection.py
new file mode 100644
index 0000000000..d8ab5ce206
--- /dev/null
+++ b/tests/python/script/test_parser_host_selection.py
@@ -0,0 +1,263 @@
+# 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.
+"""Compile-time choices preserve source order, scope and missing-value errors."""
+
+import pytest
+
+from tvm.script.parser import entry
+
+
+def parse(language, source, *, extra_vars=None, **options):
+ return entry.parse(source, extra_vars={"X": language.X, **(extra_vars or {})}, **options)
+
+
+def test_marked_expressions_are_lazy_operand_valued_and_ordered(language):
+ seen = []
+
+ def operand(value):
+ seen.append(value)
+ return value
+
+ result = parse(
+ language,
+ """
+@X.script
+def main():
+ X.record(operand(1) if I.constexpr(operand(True)) else invalid())
+ X.record(I.constexpr(operand(0)) and invalid())
+ X.record(I.constexpr(operand(4)) or invalid())
+ X.record(I.constexpr(operand(2)) and operand(7))
+ X.record(I.constexpr(operand(0)) or operand(8))
+""",
+ extra_vars={"operand": operand},
+ )
+ assert seen == [True, 1, 0, 4, 2, 7, 0, 8]
+ assert [value for _, value in result.body] == [1, 0, 4, 7, 8]
+
+
+def test_unmarked_expression_eagerly_constructs_both_ir_arms(language):
+ seen = []
+
+ def operand(value):
+ seen.append(value)
+ return value
+
+ result = parse(
+ language,
+ """
+@X.script
+def main(condition: X.value):
+ X.record(operand(1) if condition else operand(2))
+ X.record(condition and operand(True))
+ X.record(condition or operand(False))
+""",
+ extra_vars={"operand": operand},
+ )
+ assert seen == [1, 2, True, False]
+ assert result.body[0][1].op == "select"
+ assert result.body[1][1].op == "and"
+ assert result.body[2][1].op == "or"
+
+
+def test_nested_unmarked_statement_retains_ir_frame(language):
+ result = parse(
+ language,
+ """
+@X.script
+def main(condition: X.value):
+ if I.constexpr(True):
+ if condition:
+ X.record(1)
+ else:
+ X.record(2)
+""",
+ )
+ assert result.body == [("emit", 1), ("emit", 2)]
+ assert [event[1] for event in language.events if event[0] == "enter"] == [
+ "function",
+ "if",
+ "then",
+ "else",
+ ]
+
+
+@pytest.mark.parametrize("condition", [True, False])
+def test_conditional_binding_can_be_assigned_after_skipped_branch(language, condition):
+ result = parse(
+ language,
+ f"""
+@X.script
+def main():
+ if I.constexpr({condition}):
+ x = 1
+ x = 2
+ X.record(x)
+""",
+ )
+ assert result.body[-1] == ("emit", 2)
+
+
+@pytest.mark.parametrize("track_span", [True, False])
+def test_constexpr_keeps_named_expression_unsupported(language, track_span):
+ with pytest.raises(Exception, match="Unsupported expression: NamedExpr"):
+ parse(
+ language,
+ """
+@X.script
+def main():
+ if I.constexpr(bool(x := 3)):
+ X.record(x)
+""",
+ track_span=track_span,
+ )
+
+
+def test_ir_optional_binding_survives_skipped_host_assignment(language):
+ result = parse(
+ language,
+ """
+@X.script
+def main(condition: X.value):
+ if condition:
+ x = X.value(1)
+ if I.constexpr(False):
+ x = X.value(2)
+ x = X.value(3)
+ X.record(x)
+""",
+ )
+ assert result.body[-1][1].args == (3,)
+
+
+@pytest.mark.parametrize(
+ "expression", ["1 if I.constexpr(x) else 0", "I.constexpr(x) and 1", "I.constexpr(x) or 1"]
+)
+def test_missing_host_binding_cannot_be_truth_tested(language, expression):
+ from tvm.error import DiagnosticError
+
+ with pytest.raises(DiagnosticError) as caught:
+ parse(
+ language,
+ f"""
+@X.script
+def main():
+ if I.constexpr(False):
+ x = 1
+ X.record({expression})
+""",
+ )
+ assert isinstance(caught.value.__cause__, NameError)
+
+
+def test_missing_host_if_binding_raises_before_branch_assignments(language):
+ from tvm.error import DiagnosticError
+
+ with pytest.raises(DiagnosticError) as caught:
+ parse(
+ language,
+ """
+@X.script
+def main():
+ if I.constexpr(False):
+ x = 1
+ if I.constexpr(x):
+ x = 2
+ else:
+ x = 3
+""",
+ )
+ assert isinstance(caught.value.__cause__, NameError)
+
+
+def test_host_lambda_local_does_not_capture_optional_binding(language):
+ result = parse(
+ language,
+ """
+@X.script
+def main():
+ if I.constexpr(False):
+ x = 1
+ if I.constexpr((lambda x: x)(True)):
+ X.record(222)
+""",
+ )
+ assert result.body[-1] == ("emit", 222)
+
+
+def test_parser_skips_invalid_ramp_and_preserves_support_name(language):
+ # Before: X.ramp(0, 1, _PS) if I.constexpr(_PS > 1) else 0
+ # Expected builder program: X.ramp(0, 1, _PS) if _PS > 1 else 0
+ # The captured _PS name remains an ordinary user binding.
+ source = """
+@X.script
+def main():
+ X.record(X.ramp(0, 1, _PS) if I.constexpr(_PS > 1) else 0)
+"""
+ function = parse(language, source, extra_vars={"_PS": 1})
+ assert function.body == [("emit", 0)]
+
+
+def test_source_logical_operands_skip_at_construction(language):
+ # Before: value if I.constexpr(False and fail()) else fallback
+ # Expected builder program: value if False and fail() else fallback
+ # Calls inside the constexpr operand retain Python short-circuit behavior.
+ def fail():
+ raise AssertionError("skipped source operand was evaluated")
+
+ function = parse(
+ language,
+ """
+@X.script
+def main():
+ X.record(1 if I.constexpr(False and fail()) else 2)
+ X.record(3 if I.constexpr(True or fail()) else 4)
+""",
+ extra_vars={"fail": fail},
+ )
+ assert [value for _, value in function.body] == [2, 3]
+
+
+@pytest.mark.parametrize("operator", ["and", "or"])
+def test_unmarked_logical_chain_preserves_left_association(language, operator):
+ result = language.parse(f"""
+@X.script
+def main(a: X.value(), b: X.value(), c: X.value()):
+ X.record(a {operator} b {operator} c)
+""")
+ expression = result.body[0][1]
+ assert expression.op == operator
+ assert expression.args[1] is result.params[2]
+ assert expression.args[0].op == operator
+ assert expression.args[0].args == tuple(result.params[:2])
+
+
+def test_ir_branch_incoming_read_and_rebinding_obeys_python_scope(language):
+ from tvm.error import DiagnosticError
+
+ with pytest.raises(DiagnosticError) as error:
+ language.parse("""
+@X.script
+def main(condition: X.value(), x: X.value()):
+ y = x
+ if condition:
+ y = y + x
+ else:
+ y = x
+ return y
+""")
+ assert isinstance(error.value.__cause__, NameError)
+ assert "y" in str(error.value.__cause__)
diff --git a/tests/python/script/test_parser_scoped_symbols.py b/tests/python/script/test_parser_scoped_symbols.py
new file mode 100644
index 0000000000..f7b7311e75
--- /dev/null
+++ b/tests/python/script/test_parser_scoped_symbols.py
@@ -0,0 +1,104 @@
+# 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.
+"""Quoted symbols share identity without adding Python bindings."""
+
+import pytest
+
+from tvm.error import DiagnosticError
+from tvm.script.parser import entry
+
+
+def parse(language, source, *, extra_vars=None, **options):
+ language.X.tuple = lambda *fields: fields
+ return entry.parse(source, extra_vars={"X": language.X, **(extra_vars or {})}, **options)
+
+
+@pytest.mark.parametrize("track_span", [True, False])
+def test_signature_symbols_cross_nested_calls_parameters_return_and_body(language, track_span):
+ function = parse(
+ language,
+ """
+@X.script
+def main(
+ x: X.tuple(X.tensor(("n",), "float32"), X.tensor(("n",), "float32")),
+ y: X.tensor(("n",), "float32"),
+) -> X.tensor(("n",), "float32"):
+ n = X.symbol()
+ X.record(n)
+ return y
+""",
+ track_span=track_span,
+ )
+ n = function.params[0].args[0][0].args[0][0]
+ assert function.params[0].args[0][1].args[0][0] is n
+ assert function.params[1].args[0].args[0][0] is n
+ assert function.ret_type.args[0][0] is n
+ assert function.body[0][1] is n
+
+
+def test_signature_strings_reuse_symbol_before_explicit_body_declaration(language):
+ function = parse(
+ language,
+ """
+@X.script
+def main(x: X.tensor(("n + 1", "n"), "float32")):
+ n = X.symbol()
+ X.record(n)
+ return x
+""",
+ )
+ first, n = function.params[0].args[0].args[0]
+ assert first.args[0] is n
+ assert first.args[1] == 1
+ assert function.body[0][1] is n
+
+
+@pytest.mark.parametrize(
+ "annotation",
+ [
+ 'X.tensor((n, "n"), "float32")',
+ 'X.tuple(X.tensor((n,), "float32"), X.tensor(("n",), "float32"))',
+ ],
+)
+def test_signature_read_before_introduction_remains_unbound(language, annotation):
+ source = f"""
+@X.script
+def main(x: {annotation}):
+ return x
+"""
+ with pytest.raises(DiagnosticError) as error:
+ parse(language, source)
+ assert isinstance(error.value.__cause__, NameError)
+ assert "n" in str(error.value.__cause__)
+
+
+def test_signature_strings_do_not_replace_captured_python_names(language):
+ function = parse(
+ language,
+ """
+@X.script
+def main(x: X.tensor((n, "n"), "float32"), y: X.tensor((n,), "float32")):
+ X.record(n)
+ return y
+""",
+ extra_vars={"n": 7},
+ )
+ first, n = function.params[0].args[0].args[0]
+ assert first == 7
+ assert function.params[1].args[0].args[0][0] == 7
+ assert function.body[0][1] == 7
+ assert n.name == "n"
diff --git a/tests/python/script/test_parser_shared_resolvers.py b/tests/python/script/test_parser_shared_resolvers.py
new file mode 100644
index 0000000000..9916ba8978
--- /dev/null
+++ b/tests/python/script/test_parser_shared_resolvers.py
@@ -0,0 +1,79 @@
+# 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.
+"""Common IR constructors and argument policy metadata."""
+
+import pytest
+
+import tvm
+from tvm import ir
+from tvm.script import parser
+from tvm.script import tirx as T
+from tvm.script.ir_builder import IRBuilder
+from tvm.script.ir_builder import ir as I
+from tvm.script.parser import protocol
+
+
+def test_global_info_selectors_use_module_map():
+ # Before: X.Tensor((4,), "float32", vdevice="cuda:1")
+ # Expected builder program: I.resolve_global_info("cuda:1") is mod.global_infos["vdevice"][2]
+ with IRBuilder(), I.ir_module() as module:
+ devices = [I.vdevice("llvm"), I.vdevice("cuda"), I.vdevice("cuda", 1)]
+ I.module_global_infos({"vdevice": devices, "other": [I.dummy_global_info()]})
+ for spelling, index in (("cuda:1", 2), ("vdevice[1]", 1), ("cuda", 1)):
+ resolved = I.resolve_global_info(spelling)
+ assert resolved.__chandle__() == devices[index].__chandle__()
+ assert resolved.__chandle__() == module.global_infos["vdevice"][index].__chandle__()
+ assert I.resolve_global_info("other[0]") is not None
+
+
+def test_annotation_class_supports_union_and_missing_type():
+ # Before: X.Annotation("n") | None
+ # Expected builder program: X.Annotation((X.resolve_type_var_("n"))) in a function frame.
+ @protocol.args_policy({"shape": "expr_str"}, as_type=True)
+ def annotation(shape):
+ return shape
+
+ assert isinstance(annotation, type)
+ assert annotation | None
+ assert annotation(16) == 16
+ assert annotation("n").is_missing()
+
+
+@pytest.mark.parametrize("name", ["Range", "StringType", "StringImm", "GenericConst"])
+def test_shared_ir_constructor_identity(name):
+ # Initialize the source namespace before inspecting its shared constructors.
+ parse = parser.parse
+ assert callable(parse)
+ assert getattr(I, name) is getattr(tvm.ir, name)
+ assert getattr(parser.I, name) is getattr(tvm.ir, name)
+
+
+def test_module_string_constants_keep_common_constructor_values():
+ actual = parser.parse("""
+@I.ir_module
+class Module:
+ I.module_attrs({"tag": I.StringImm("label"), "type": I.StringType()})
+""")
+ with IRBuilder() as builder, I.ir_module():
+ I.module_attrs({"tag": ir.StringImm("label"), "type": ir.StringType()})
+ ir.assert_structural_equal(builder.get(), actual)
+ assert actual.attrs["tag"].value == "label"
+ assert isinstance(actual.attrs["type"], ir.StringType)
+
+
+def test_dialect_marker_is_same_protocol_identity():
+ assert T.constexpr is I.constexpr
diff --git a/tests/python/script/test_parser_span_helpers.py b/tests/python/script/test_parser_span_helpers.py
new file mode 100644
index 0000000000..7d84365edc
--- /dev/null
+++ b/tests/python/script/test_parser_span_helpers.py
@@ -0,0 +1,72 @@
+# 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.
+"""Production source-span composition on common IR nodes."""
+
+import pytest
+
+from tvm import ir
+from tvm.ir import prim
+from tvm.script.ir_builder import IRBuilder
+from tvm.script.ir_builder import ir as I
+
+
+def loc(line, name="source.py", column=1, end_column=20):
+ return (name, line, line, column, end_column)
+
+
+def locations(value):
+ span = value.span
+ spans = span.spans if isinstance(span, ir.SequentialSpan) else [span]
+ return [(str(s.source_name.name), s.line, s.column, s.end_column) for s in spans]
+
+
+def test_at_preserves_native_expression_identity():
+ with IRBuilder():
+ value = prim.IntImm("int32", 2)
+ assert I.at_(loc(4), value) is value
+ assert locations(value) == [("source.py", 4, 1, 20)]
+
+
+@pytest.mark.parametrize("value", [None, 3, "python", object()])
+def test_at_preserves_python_values(value):
+ with IRBuilder():
+ assert I.at_(loc(5), value) is value
+
+
+def test_enclosing_locations_collapse_without_losing_definition():
+ with IRBuilder():
+ value = prim.IntImm("int32", 1)
+ I.at_(loc(10, column=5, end_column=10), value)
+ I.at_(loc(10), value)
+ assert locations(value) == [("source.py", 10, 5, 10)]
+ I.at_(loc(10, column=6, end_column=8), value)
+ assert locations(value) == [("source.py", 10, 6, 8)]
+
+
+def test_composition_merges_shared_prefix_of_distinct_definition_chains():
+ with IRBuilder():
+ caller = ir.Span(ir.SourceName("caller.py"), 1, 1, 1, 20)
+ original = ir.Span(ir.SourceName("definition.py"), 2, 2, 1, 20)
+ value = prim.IntImm("int32", 1)
+ I.at_(ir.SequentialSpan([caller, original]), value)
+ with IRBuilder.current().with_source_span(caller):
+ I.at_(loc(3, "definition.py"), value)
+ assert locations(value) == [
+ ("caller.py", 1, 1, 20),
+ ("definition.py", 3, 1, 20),
+ ("definition.py", 2, 1, 20),
+ ]
diff --git a/tests/python/tirx/script/test_capture_jit_execution.py b/tests/python/tirx/script/test_capture_jit_execution.py
new file mode 100644
index 0000000000..f222568082
--- /dev/null
+++ b/tests/python/tirx/script/test_capture_jit_execution.py
@@ -0,0 +1,51 @@
+# 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.
+
+"""Reused JIT decorators retain annotation shape and compiled lexical values."""
+
+from __future__ import annotations
+
+import numpy as np
+import pytest
+
+import tvm
+from tvm.script import tirx as T
+
+VALUE = 1
+
+
+def _delayed(n, decorator):
+ @decorator
+ def function(output: T.Buffer((n,), "int32")):
+ n = 2
+ output[0] = n + VALUE
+
+ return function
+
+
+@pytest.mark.parametrize("factory", [False, True])
+def test_reused_jit_decorator_captures_application_scope(factory):
+ decorator = T.jit() if factory else T.jit
+ pending = _delayed(8, decorator)
+ n = 99
+ VALUE = 20
+ function = pending.specialize()
+ assert [int(value) for value in function.params[0].ty.shape] == [8]
+ compiled = tvm.compile(function, target="llvm", tir_pipeline="tirx")
+ output = tvm.runtime.tensor(np.zeros(8, dtype="int32"))
+ compiled(output)
+ np.testing.assert_array_equal(output.numpy(), [3, 0, 0, 0, 0, 0, 0, 0])
diff --git a/tests/python/tirx/script/test_frontend_construction_validation.py b/tests/python/tirx/script/test_frontend_construction_validation.py
new file mode 100644
index 0000000000..a219763551
--- /dev/null
+++ b/tests/python/tirx/script/test_frontend_construction_validation.py
@@ -0,0 +1,96 @@
+# 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.
+
+"""Public TIRx construction validates native scopes and executable specialization."""
+
+import numpy as np
+import pytest
+
+import tvm
+from tvm import tirx
+from tvm.error import DiagnosticError
+from tvm.script import ir as I
+from tvm.script import tirx as T
+
+VALUE = 1
+
+
+def _build_lexical_global():
+ @T.prim_func
+ def write(A: T.Buffer((1,), "int32")):
+ A[0] = VALUE
+
+ return write
+
+
+def test_default_tirx_validation_rejects_non_divisible_scope_extents():
+ with pytest.raises(DiagnosticError):
+
+ @T.prim_func
+ def invalid():
+ T.device_entry()
+ block = T.cta_id([1])
+ warp = T.warp_id([3])
+ thread = T.thread_id([100])
+ T.evaluate(block + warp + thread)
+
+
+def test_tirx_validation_can_be_explicitly_disabled():
+ @T.prim_func(check_well_formed=False)
+ def invalid():
+ T.device_entry()
+ block = T.cta_id([1])
+ warp = T.warp_id([3])
+ thread = T.thread_id([100])
+ T.evaluate(block + warp + thread)
+
+ assert isinstance(invalid, tirx.PrimFunc)
+ definitions = invalid.body.body.seq[:3]
+ assert all(isinstance(statement, tirx.ScopeIdDefStmt) for statement in definitions)
+ with pytest.raises(tvm.error.InternalError, match="100 is not divisible by 3"):
+ tirx.analysis.verify_tirx_well_formed(invalid)
+
+
+def test_optional_annotation_is_restricted_to_jit():
+ with pytest.raises(DiagnosticError, match="only supported by @T.jit"):
+
+ @T.prim_func(private=True)
+ def invalid(value: T.Optional(T.handle)):
+ T.evaluate(0)
+
+ @T.jit(private=True)
+ def valid(value: T.Optional(T.handle)):
+ if I.constexpr(value is None):
+ T.evaluate(1)
+ else:
+ T.evaluate(2)
+
+ present, absent = valid.specialize(), valid.specialize(value=None)
+ assert len(present.params) == 1
+ assert len(absent.params) == 0
+ assert present.body.value.value == 2
+ assert absent.body.value.value == 1
+
+
+def test_lexical_global_is_not_replaced_by_dynamic_caller_local():
+ VALUE = 2
+ function = _build_lexical_global()
+ assert function.body.value.value == 1
+ compiled = tvm.compile(function, target="llvm", tir_pipeline="tirx")
+ output = tvm.runtime.tensor(np.zeros(1, dtype="int32"))
+ compiled(output)
+ np.testing.assert_array_equal(output.numpy(), np.array([1], dtype="int32"))
diff --git a/tests/python/tirx/test_parser_backend_namespaces.py b/tests/python/tirx/script/test_parser_backend_namespaces.py
similarity index 100%
rename from tests/python/tirx/test_parser_backend_namespaces.py
rename to tests/python/tirx/script/test_parser_backend_namespaces.py
diff --git a/tests/python/relax/test_parser_construction_regressions.py b/tests/python/tirx/script/test_parser_buffer_strides.py
similarity index 58%
rename from tests/python/relax/test_parser_construction_regressions.py
rename to tests/python/tirx/script/test_parser_buffer_strides.py
index 9dd490d279..a43e90ca1c 100644
--- a/tests/python/relax/test_parser_construction_regressions.py
+++ b/tests/python/tirx/script/test_parser_buffer_strides.py
@@ -14,60 +14,12 @@
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
-"""Construction regressions exercised by ordinary TVMScript entry points."""
+"""Native buffer stride declarations preserve dtype and symbol identity."""
import pytest
import tvm
-from tvm.script import ir as I
from tvm.script import parser
-from tvm.script import relax as R
-
-
-def test_eager_module_annotations_resolve_global_info_in_module_scope():
- @I.ir_module
- class Module:
- I.module_global_infos(
- {
- "mesh": [R.device_mesh((2,), I.Range(0, 2))],
- "vdevice": [I.vdevice("llvm")],
- }
- )
-
- @R.function
- def distributed(x: R.DTensor((4,), "float32", "mesh[0]", "R")):
- return x
-
- @R.function
- def tensor(x: R.Tensor((4,), "float32", vdevice="llvm:0:global")):
- return x
-
- assert (
- Module["distributed"].params[0].ty.device_mesh.__chandle__()
- == Module.global_infos["mesh"][0].__chandle__()
- )
- assert (
- Module["tensor"].params[0].ty.vdevice.__chandle__()
- == Module.global_infos["vdevice"][0].__chandle__()
- )
-
-
-def test_scoped_vdevice_selects_target_ordinal_and_roundtrips():
- module = parser.parse("""
-@I.ir_module
-class Module:
- I.module_global_infos({"vdevice": [
- I.vdevice("llvm"), I.vdevice("cuda"), I.vdevice("metal"), I.vdevice("cuda", 1),
- ]})
- @R.function
- def main(x: R.Tensor((4,), "float32", vdevice="cuda:1:global")):
- return x
-""")
- assert (
- module["main"].params[0].ty.vdevice.__chandle__()
- == module.global_infos["vdevice"][3].__chandle__()
- )
- tvm.ir.assert_structural_equal(module, tvm.script.from_source(module.script()))
@pytest.mark.parametrize("constructor", ["Buffer", "match_buffer"])
@@ -75,13 +27,13 @@ class Module:
def test_implicit_buffer_strides_use_symbolic_default(constructor, index_dtype):
if constructor == "Buffer":
source = """
-@T.prim_func(s_tir=True)
+@T.prim_func
def main(A: T.Buffer((16, 16), "float32", strides=("s0", "s1"))):
T.evaluate(A[0, 0])
"""
else:
source = """
-@T.prim_func(s_tir=True)
+@T.prim_func
def main(a: T.handle):
A = T.match_buffer(a, (16, 16), "float32", strides=("s0", "s1"))
T.evaluate(A[0, 0])
@@ -94,7 +46,7 @@ def main(a: T.handle):
@pytest.mark.parametrize("dtype", ["int32", "int64"])
def test_explicit_stride_declaration_keeps_its_dtype_and_identity(dtype):
function = parser.parse(f"""
-@T.prim_func(s_tir=True)
+@T.prim_func
def main(A: T.Buffer((16, 16), "float32", strides=("s0", "s1")), s0: T.{dtype}):
s1 = T.int64()
T.evaluate(A[0, 0] + s0 + s1)
@@ -107,7 +59,7 @@ def main(A: T.Buffer((16, 16), "float32", strides=("s0", "s1")), s0: T.{dtype}):
@pytest.mark.parametrize("dtype", ["int32", "int64"])
def test_match_buffer_reuses_prior_explicit_stride(dtype):
function = parser.parse(f"""
-@T.prim_func(s_tir=True)
+@T.prim_func
def main(a: T.handle):
s0 = T.{dtype}()
A = T.match_buffer(a, (16,), "float32", strides=("s0",))
@@ -124,7 +76,7 @@ def test_decl_buffer_stride_roundtrip_preserves_dtype(dtype):
# Standalone buffer declarations can contain free stride symbols.
function = parser.parse(
f"""
-@T.prim_func(s_tir=True)
+@T.prim_func
def main(data: T.handle("float32")):
s0 = T.{dtype}()
A = T.decl_buffer((1,), "float32", data=data, strides=(s0,))
@@ -140,24 +92,3 @@ def main(data: T.handle("float32")):
tvm.ir.assert_structural_equal(
function, parser.parse(printed, check_well_formed=False), map_free_vars=True
)
-
-
-@pytest.mark.parametrize(
- "axes",
- [
- "vi = T.axis.spatial(16, i)\n vi = T.axis.spatial(16, j)",
- 'vi, vi = T.axis.remap("SS", [i, j])',
- 'vi, vj = T.axis.remap("SS", [i, j])\n vi = T.axis.spatial(16, j)',
- ],
-)
-def test_duplicate_block_axis_source_name_is_rejected(axes):
- source = f"""
-@T.prim_func(s_tir=True)
-def main():
- for i, j in T.grid(16, 16):
- with T.sblock("block"):
- {axes}
- T.evaluate(vi)
-"""
- with pytest.raises(tvm.error.DiagnosticError):
- parser.parse(source)
diff --git a/tests/python/tirx/test_parser_buffer_views.py b/tests/python/tirx/script/test_parser_buffer_views.py
similarity index 100%
rename from tests/python/tirx/test_parser_buffer_views.py
rename to tests/python/tirx/script/test_parser_buffer_views.py
diff --git a/tests/python/tirx/script/test_parser_constexpr_buffers.py b/tests/python/tirx/script/test_parser_constexpr_buffers.py
new file mode 100644
index 0000000000..a91a1a4fa0
--- /dev/null
+++ b/tests/python/tirx/script/test_parser_constexpr_buffers.py
@@ -0,0 +1,50 @@
+# 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.
+"""Compile-time selection preserves native parameter buffer identity."""
+
+import pytest
+
+from tvm import tirx
+from tvm.script import parser
+
+
+@pytest.mark.parametrize("marker", ["I.constexpr", "T.constexpr"])
+@pytest.mark.parametrize("track_span", [True, False])
+def test_marked_if_shares_parent_scope(marker, track_span):
+ seen = []
+
+ def choose():
+ seen.append("condition")
+ return True
+
+ result = parser.parse(
+ f"""
+@T.prim_func
+def main(a: T.handle):
+ if {marker}(choose()):
+ A = T.match_buffer(a, (4,), "int32")
+ else:
+ invalid()
+ A[0] = 3
+""",
+ extra_vars={"choose": choose},
+ track_span=track_span,
+ )
+ assert seen == ["condition"]
+ assert len(result.params) == 1
+ assert isinstance(result.body, tirx.BufferStore)
+ assert result.body.buffer.same_as(result.params[0])
diff --git a/tests/python/tirx/test_parser_emitted_spans.py b/tests/python/tirx/script/test_parser_emitted_spans.py
similarity index 74%
rename from tests/python/tirx/test_parser_emitted_spans.py
rename to tests/python/tirx/script/test_parser_emitted_spans.py
index 9996a7256c..384ca2e3bf 100644
--- a/tests/python/tirx/test_parser_emitted_spans.py
+++ b/tests/python/tirx/script/test_parser_emitted_spans.py
@@ -14,9 +14,7 @@
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
-"""Source context belongs to the actual construction result."""
-
-import pytest
+"""Native emitted statements and frames preserve source locations."""
from tvm import ir, tirx
from tvm.script import tirx as T
@@ -57,19 +55,6 @@ def test_emit_ordinary_value_once():
assert isinstance(builder.get().body, tirx.Evaluate)
-def test_at_preserves_native_expression_identity():
- with IRBuilder():
- value = tirx.IntImm("int32", 2)
- assert I.at_(loc(4), value) is value
- assert locations(value) == [("source.py", 4, 1, 20)]
-
-
-@pytest.mark.parametrize("value", [None, 3, "python", object()])
-def test_at_preserves_python_values(value):
- with IRBuilder():
- assert I.at_(loc(5), value) is value
-
-
def test_native_frame_retains_span_until_exit():
with IRBuilder() as builder:
frame = native.serial(0, 4)
@@ -105,16 +90,6 @@ def test_at_retains_definition_after_caller_scope_returns():
assert locations(builder.get()) == [("caller.py", 9, 1, 20), ("definition.py", 2, 1, 20)]
-def test_enclosing_locations_collapse_without_losing_definition():
- with IRBuilder():
- value = tirx.IntImm("int32", 1)
- I.at_(loc(10, column=5, end_column=10), value)
- I.at_(loc(10), value)
- assert locations(value) == [("source.py", 10, 5, 10)]
- I.at_(loc(10, column=6, end_column=8), value)
- assert locations(value) == [("source.py", 10, 6, 8)]
-
-
def test_nested_frame_context_has_no_repeated_caller():
with IRBuilder() as builder:
with builder.with_source_span(ir.Span(ir.SourceName("caller.py"), 1, 1, 1, 20)):
@@ -124,21 +99,6 @@ def test_nested_frame_context_has_no_repeated_caller():
assert locations(builder.get()) == [("caller.py", 1, 1, 20), ("definition.py", 2, 1, 20)]
-def test_composition_merges_shared_prefix_of_distinct_definition_chains():
- with IRBuilder():
- caller = ir.Span(ir.SourceName("caller.py"), 1, 1, 1, 20)
- original = ir.Span(ir.SourceName("definition.py"), 2, 2, 1, 20)
- value = tirx.IntImm("int32", 1)
- I.at_(ir.SequentialSpan([caller, original]), value)
- with IRBuilder.current().with_source_span(caller):
- I.at_(loc(3, "definition.py"), value)
- assert locations(value) == [
- ("caller.py", 1, 1, 20),
- ("definition.py", 3, 1, 20),
- ("definition.py", 2, 1, 20),
- ]
-
-
def test_tile_insertion_composes_caller_on_existing_statement_span():
from tvm.tirx import operator as tile_operator
from tvm.tirx.script.builder import tirx as tile_builder
diff --git a/tests/python/tirx/test_parser_helper_migrations.py b/tests/python/tirx/script/test_parser_helper_migrations.py
similarity index 60%
rename from tests/python/tirx/test_parser_helper_migrations.py
rename to tests/python/tirx/script/test_parser_helper_migrations.py
index 2c21344d8c..9e7b205043 100644
--- a/tests/python/tirx/test_parser_helper_migrations.py
+++ b/tests/python/tirx/script/test_parser_helper_migrations.py
@@ -106,7 +106,7 @@ def main(role_id: T.int32):
@pytest.mark.parametrize("sliding", [False, True])
def test_llm_length_info_buffer(sliding):
source = f"""
-@T.prim_func(s_tir=True)
+@T.prim_func
def main(lengths: T.handle):
length_info = declare(lengths, 4, {sliding}, 8)
T.evaluate(length_info[{"0, 0" if sliding else "0"}])
@@ -117,84 +117,3 @@ def main(lengths: T.handle):
)
actual = parser.parse(source, {"declare": kernels._declare_length_info})
tvm.ir.assert_structural_equal(actual, parser.parse(expected_source))
-
-
-@pytest.mark.parametrize(
- "helper,args,specs",
- [
- (kernels._var, '("float32")', [((1,), "float32", "local")]),
- (kernels._var_cpu, '("float32")', [((1,), "float32", "global")]),
- (
- kernels._alloc_softmax_state_buffers,
- "(8, 16, 2, 2)",
- [((8, 16), "float32", "shared"), ((8, 16), "float32", "local")]
- + [((8,), "float32", "shared")] * 3
- + [((2,), "float32", "local")] * 3,
- ),
- (
- kernels._alloc_mha_qkvo_buffers,
- '(8, 16, 32, 64, "float16")',
- [
- ((8, 32), "float16", "shared"),
- ((16, 32), "float16", "shared"),
- ((16, 64), "float16", "shared"),
- ((8, 64), "float32", "local"),
- ],
- ),
- (
- kernels._alloc_mla_qkvo_buffers,
- '(8, 16, 32, 64, "float16")',
- [
- ((8, 32), "float16", "shared"),
- ((16, 32), "float16", "shared"),
- ((8, 64), "float32", "local"),
- ],
- ),
- (kernels._alloc_tile_walk_state, "()", [((1,), "int32", "local")] * 6),
- ],
-)
-def test_llm_buffer_allocations(helper, args, specs):
- names = [f"buffer_{index}" for index in range(len(specs))]
- uses = "".join(
- f" T.evaluate({name}[{', '.join('0' for _ in shape)}])\n"
- for name, (shape, _, _) in zip(names, specs)
- )
- prefix = "@T.prim_func(s_tir=True)\ndef main():\n"
- source = prefix + f" {', '.join(names)} = helper{args}\n" + uses
- expected_source = (
- prefix
- + "".join(
- f' {name} = T.sblock_alloc_buffer({shape}, "{dtype}", scope="{scope}")\n'
- for name, (shape, dtype, scope) in zip(names, specs)
- )
- + uses
- )
- actual = parser.parse(source, {"helper": helper})
- tvm.ir.assert_structural_equal(actual, parser.parse(expected_source))
-
-
-def test_llm_prefill_macro_uses_callers_builder():
- init_states = kernels._make_prefill_macros(4, 8, 16, 8, 2, 2, 1)[0]
- prefix = """
-@T.prim_func(s_tir=True)
-def main(m: T.Buffer((4,), "float32"), d: T.Buffer((4,), "float32"),
- out: T.Buffer((4, 8), "float32"), ty: T.int32, tx: T.int32):
-"""
- source = prefix + " init_states(m, d, out, ty, tx)\n"
- expected_source = (
- prefix
- + """
- for i in T.serial(T.ceildiv(4, 4)):
- row: T.let[T.int32] = i * 2 * 2 + ty * 2 + tx
- if row < 4:
- m[row] = -5e4
- d[row] = 1.0
- for li, lj in T.grid(4, 8):
- with T.sblock("O_init"):
- i, j = T.axis.remap("SS", [li, lj])
- out[i, j] = 0.0
- T.tvm_storage_sync("shared")
-"""
- )
- actual = parser.parse(source, {"init_states": init_states})
- tvm.ir.assert_structural_equal(actual, parser.parse(expected_source))
diff --git a/tests/python/tirx/test_parser_jit_specialization.py b/tests/python/tirx/script/test_parser_jit_specialization.py
similarity index 100%
rename from tests/python/tirx/test_parser_jit_specialization.py
rename to tests/python/tirx/script/test_parser_jit_specialization.py
diff --git a/tests/python/tirx/test_parser_printer_type_vars.py b/tests/python/tirx/script/test_parser_printer_type_vars.py
similarity index 100%
rename from tests/python/tirx/test_parser_printer_type_vars.py
rename to tests/python/tirx/script/test_parser_printer_type_vars.py
diff --git a/tests/python/tirx/test_parser_range_annotations.py b/tests/python/tirx/script/test_parser_range_annotations.py
similarity index 93%
rename from tests/python/tirx/test_parser_range_annotations.py
rename to tests/python/tirx/script/test_parser_range_annotations.py
index f864866ad3..5ced90685f 100644
--- a/tests/python/tirx/test_parser_range_annotations.py
+++ b/tests/python/tirx/script/test_parser_range_annotations.py
@@ -24,9 +24,9 @@ from tvm.script import tirx as T
from tvm.script.ir_builder import IRBuilder
-def annotated_source(bounds, s_tir):
+def annotated_source(bounds):
return f"""
-@T.prim_func(s_tir={s_tir})
+@T.prim_func
def main(A: T.Buffer((16,), "float32")):
for i in range(
{bounds}, annotations={{"pragma_1": "str_value", "pragma_2": 1, "pragma_3": 0.0}}
@@ -35,12 +35,11 @@ def main(A: T.Buffer((16,), "float32")):
"""
-@pytest.mark.parametrize("s_tir", [False, True])
@pytest.mark.parametrize("bounds", ["16", "0, 16", "0, 16, 2"])
-def test_range_annotations_match_direct_builder(bounds, s_tir):
- source = annotated_source(bounds, s_tir)
+def test_range_annotations_match_direct_builder(bounds):
+ source = annotated_source(bounds)
with IRBuilder() as builder:
- with T.function(s_tir=s_tir):
+ with T.function():
T.func_name("main")
buffer = T.arg("A", T.Buffer((16,), "float32"))
with T.for_(
diff --git a/tests/python/tirx/test_parser_scope_id_identity.py b/tests/python/tirx/script/test_parser_scope_id_identity.py
similarity index 93%
rename from tests/python/tirx/test_parser_scope_id_identity.py
rename to tests/python/tirx/script/test_parser_scope_id_identity.py
index d4815f18df..9b93d21ad6 100644
--- a/tests/python/tirx/test_parser_scope_id_identity.py
+++ b/tests/python/tirx/script/test_parser_scope_id_identity.py
@@ -22,7 +22,6 @@ import tvm
from tvm.script import parser
from tvm.script import tirx as T
from tvm.script.ir_builder import IRBuilder
-from tvm.script.ir_builder import ir as I
from tvm.script.ir_builder.base import BypassBind
@@ -101,10 +100,7 @@ def test_bypass_bind_returns_exact_value_before_any_binding_policy(dialect):
value = object()
# No builder or symbol frame is active. Neither an annotation nor a previous
# binding may cause ordinary binding logic to inspect the wrapped value.
- assert (
- builder.bind_(BypassBind(value), name="x", ty=object())
- is value
- )
+ assert builder.bind_(BypassBind(value), name="x", ty=object()) is value
def test_scope_tuple_assignment_returns_native_values():
@@ -122,17 +118,6 @@ def test_scope_tuple_assignment_returns_native_values():
T.evaluate(variable)
-@pytest.mark.parametrize("count", [1, 2])
-def test_bypass_source_attachment_preserves_value_identity(count):
- span = tvm.ir.Span(tvm.ir.SourceName("scope.py"), 3, 3, 4, 25)
- with IRBuilder():
- values = tuple(tvm.ir.Var("", "int32") for _ in range(count))
- result = BypassBind(values[0] if count == 1 else values)
- assert I.at_(span, result) is result
- for value in values:
- assert value.span.same_as(span)
-
-
@pytest.mark.parametrize("track_span", [True, False])
def test_scope_ids_in_single_tuple_target(track_span):
source = """
diff --git a/tests/python/tirx/test_parser_scope_id_names.py b/tests/python/tirx/script/test_parser_scope_id_names.py
similarity index 100%
rename from tests/python/tirx/test_parser_scope_id_names.py
rename to tests/python/tirx/script/test_parser_scope_id_names.py
diff --git a/tests/python/tirx/test_parser_self_bind.py b/tests/python/tirx/script/test_parser_self_bind.py
similarity index 97%
rename from tests/python/tirx/test_parser_self_bind.py
rename to tests/python/tirx/script/test_parser_self_bind.py
index c14c827de1..778c50c497 100644
--- a/tests/python/tirx/test_parser_self_bind.py
+++ b/tests/python/tirx/script/test_parser_self_bind.py
@@ -55,9 +55,7 @@ def test_self_bind_preserves_native_identity_and_name(constant, explicit_name):
assert isinstance(result, BypassBind)
original_name = result.value.name
# Bypass precedes annotation, rebinding, and symbol resolution policy.
- assigned = T.bind_(
- result, name="assigned", ty=object()
- )
+ assigned = T.bind_(result, name="assigned", ty=object())
assert assigned is result.value
assert assigned.name == original_name
if variable is not None:
diff --git a/tests/python/tirx/test_parser_tile_namespaces.py b/tests/python/tirx/script/test_parser_tile_namespaces.py
similarity index 100%
rename from tests/python/tirx/test_parser_tile_namespaces.py
rename to tests/python/tirx/script/test_parser_tile_namespaces.py
diff --git a/tests/python/unittest/test_parser_emission_contract.py b/tests/python/tirx/script/test_parser_tirx_emission.py
similarity index 83%
rename from tests/python/unittest/test_parser_emission_contract.py
rename to tests/python/tirx/script/test_parser_tirx_emission.py
index cb6d8259df..8bbd845a31 100644
--- a/tests/python/unittest/test_parser_emission_contract.py
+++ b/tests/python/tirx/script/test_parser_tirx_emission.py
@@ -14,14 +14,13 @@
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
-"""Explicit source emission and generated statement consumption agree."""
+"""Source emission uses the dialect public builder contract."""
import pytest
import tvm
-from tvm import ir, tirx
+from tvm import tirx
from tvm.relax.script import builder as R
-from tvm.relax.script.builder import ir as native_R
from tvm.script import parser
from tvm.script import tirx as T
from tvm.script.ir_builder import IRBuilder
@@ -54,22 +53,6 @@ def test_source_store_uses_public_builder_and_propagates_errors(monkeypatch, err
assert len(calls) == 1
-def test_explicit_relax_emit_retains_source_binding_api():
- source = """
-@R.function
-def main():
- x = R.emit(R.const(1))
- return x
-"""
- with IRBuilder() as context:
- with R.function():
- R.func_name("main")
- value = native_R.emit(R.const(1))
- bound = native_R.emit(value)
- R.func_ret_value(bound)
- ir.assert_structural_equal(context.get(), parser.parse(source))
-
-
def test_emit_keeps_existing_buffer_store_identity_and_span():
with IRBuilder() as builder:
with T.function():
@@ -82,7 +65,7 @@ def test_emit_keeps_existing_buffer_store_identity_and_span():
assert stored.span.line == 3
-@pytest.mark.parametrize("dialect", ["tirx", "relax"])
+@pytest.mark.parametrize("dialect", ["tirx"])
def test_generated_statements_use_dialect_emit_protocol(monkeypatch, dialect):
builder = tir_builder if dialect == "tirx" else R
original = builder.emit_
diff --git a/tests/python/unittest/test_parser_native_frames.py b/tests/python/tirx/script/test_parser_tirx_frames.py
similarity index 70%
rename from tests/python/unittest/test_parser_native_frames.py
rename to tests/python/tirx/script/test_parser_tirx_frames.py
index cc92e890b5..9bffaec442 100644
--- a/tests/python/unittest/test_parser_native_frames.py
+++ b/tests/python/tirx/script/test_parser_tirx_frames.py
@@ -14,7 +14,7 @@
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
-"""Native declaration frames retain identity across generated body execution."""
+"""Native function frames preserve their declared objects."""
import pytest
@@ -27,7 +27,7 @@ from tvm.tirx.script import builder as T
from tvm.tirx.script.builder.frame import ForFrame
-@pytest.mark.parametrize("dialect", [T, R])
+@pytest.mark.parametrize("dialect", [T])
def test_function_declaration_reentry_reuses_parameters_symbols_and_reference(dialect):
# Before: @X.function def identity(x: ...): return x
# Expected builder program:
@@ -55,116 +55,7 @@ def test_function_declaration_reentry_reuses_parameters_symbols_and_reference(di
assert module["identity"].params[0].same_as(parameter)
-@pytest.mark.parametrize(
- "names, expected",
- [
- ("ids", ["ids_0", "ids_1", "ids_2"]),
- (("i", "*tail"), ["i", "tail_0", "tail_1"]),
- (("*head", "last"), ["head_0", "head_1", "last"]),
- ],
-)
-def test_native_grid_names_and_unpacking_preserve_entered_variables(names, expected):
- # Before: for i, *tail in X.grid(2, 3, 4): X.evaluate(i)
- # Expected builder program:
- # with X.for_(X.grid(2, 3, 4), names=("i", "*tail")) as (i, *tail): ...
- with IRBuilder() as builder:
- frame = T.grid(2, 3, 4)
- assert isinstance(frame, ForFrame)
- assert T.for_(frame, names=names) is frame
- with frame as variables:
- assert [variable.name for variable in variables] == expected
- for variable in variables:
- T.evaluate(variable)
- loop = builder.get()
- actual = []
- while isinstance(loop, tirx.For):
- actual.append(loop.loop_var)
- loop = loop.body
- assert len(actual) == 3
- assert all(a.same_as(b) for a, b in zip(actual, variables))
- assert all(
- statement.value.same_as(variable) for statement, variable in zip(loop.seq, variables)
- )
-
-
-def test_singleton_tuple_loop_target_keeps_sequence_shape():
- # Before: for (i,) in X.grid(4): X.evaluate(i)
- # Expected builder program: with X.for_(X.grid(4), names=("i",)) as (i,): ...
- with IRBuilder() as builder:
- frame = T.for_(T.grid(4), names=("i",))
- with frame as variables:
- assert len(variables) == 1
- T.evaluate(variables[0])
- assert builder.get().loop_var.same_as(variables[0])
-
-
-def test_conditional_output_uses_same_name_and_native_frame_result():
- # Before: if condition: y = X.add(x, x); else: y = X.multiply(x, x); return y
- # Expected builder program:
- # with X.If(condition) as frame:
- # with X.Then():
- # def then(): y = X.bind_(X.add(x, x), name="y")
- # then()
- # with X.Else():
- # def otherwise(): y = X.bind_(X.multiply(x, x), name="y")
- # otherwise()
- # y = frame.var; X.return_(y)
- actual = parser.parse("""
-@R.function
-def main(condition: R.Tensor((), "bool"), x: R.Tensor((4,), "float32")):
- if condition:
- y = R.add(x, x)
- else:
- y = R.multiply(x, x)
- return y
-""")
- with IRBuilder() as builder, R.function():
- R.func_name("main")
- condition = R.arg("condition", R.Tensor((), "bool"))
- x = R.arg("x", R.Tensor((4,), "float32"))
- with R.If(condition) as frame:
- with R.Then():
- R.bind_(R.add(x, x), name="y")
- with R.Else():
- R.bind_(R.multiply(x, x), name="y")
- R.func_ret_value(frame.var)
- ir.assert_structural_equal(actual, builder.get())
-
-
-def test_ir_branch_incoming_read_and_rebinding_obeys_python_scope():
- # Before: y = x; if condition: y = X.add(y, x); else: y = x
- # Expected builder program: a local branch helper reads y before assignment;
- # report Python's unbound-name error, without synthetic y=y capture parameters.
- with pytest.raises(Exception) as error:
- parser.parse("""
-@R.function
-def main(condition: R.Tensor((), "bool"), x: R.Tensor((4,), "float32")):
- y = x
- if condition:
- y = R.add(y, x)
- else:
- y = x
- return y
-""")
- assert isinstance(error.value.__cause__, NameError)
- assert "y" in str(error.value.__cause__)
-
-
-def test_body_attribute_overrides_default_after_declaration():
- # Before: @X.prim_func def main(): X.func_attr({"global_symbol": "custom"})
- # Expected builder program:
- # with X.function(decl=True) as fn: X.func_name("main")
- # with fn: X.func_attr({"global_symbol": "custom"}); X.emit_(X.evaluate(0))
- with IRBuilder() as builder, I.ir_module():
- with T.function(decl=True) as frame:
- T.func_name("main")
- with frame:
- T.func_attr({"global_symbol": "custom"})
- T.evaluate(0)
- assert builder.get()["main"].attrs["global_symbol"] == "custom"
-
-
-@pytest.mark.parametrize("dialect", [T, R])
+@pytest.mark.parametrize("dialect", [T])
def test_module_alias_is_the_native_frame_and_lookup_keeps_reference(dialect):
# Before: cls = Module; cls.callee
# Expected builder program: cls = X.bind_(Module, name="cls")
@@ -194,7 +85,7 @@ def test_module_alias_is_the_native_frame_and_lookup_keeps_reference(dialect):
@pytest.mark.parametrize("parameter", ["x", "callee"])
@pytest.mark.parametrize(
"dialect, decorator, annotation",
- [(T, "T.prim_func", "T.int32"), (R, "R.function", 'R.Tensor((4,), "float32")')],
+ [(T, "T.prim_func", "T.int32")],
)
def test_module_member_calls_use_the_callers_native_dialect(
monkeypatch, dialect, decorator, annotation, alias, parameter
@@ -230,22 +121,58 @@ class Module:
assert arguments[0].same_as(module["caller"].params[0])
-def test_lexical_range_binding_preserves_custom_native_loop_extent():
- # Before: range = custom_range; for i in range(4): X.evaluate(i)
- # Expected builder program: range = X.bind_(custom_range, name="range")
- # with X.for_(range(4), names="i") as i: X.emit_(X.evaluate(i))
- calls = []
+@pytest.mark.parametrize(
+ "names, expected",
+ [
+ ("ids", ["ids_0", "ids_1", "ids_2"]),
+ (("i", "*tail"), ["i", "tail_0", "tail_1"]),
+ (("*head", "last"), ["head_0", "head_1", "last"]),
+ ],
+)
+def test_native_grid_names_and_unpacking_preserve_entered_variables(names, expected):
+ # Before: for i, *tail in X.grid(2, 3, 4): X.evaluate(i)
+ # Expected builder program:
+ # with X.for_(X.grid(2, 3, 4), names=("i", "*tail")) as (i, *tail): ...
+ with IRBuilder() as builder:
+ frame = T.grid(2, 3, 4)
+ assert isinstance(frame, ForFrame)
+ assert T.for_(frame, names=names) is frame
+ with frame as variables:
+ assert [variable.name for variable in variables] == expected
+ for variable in variables:
+ T.evaluate(variable)
+ loop = builder.get()
+ actual = []
+ while isinstance(loop, tirx.For):
+ actual.append(loop.loop_var)
+ loop = loop.body
+ assert len(actual) == 3
+ assert all(a.same_as(b) for a, b in zip(actual, variables))
+ assert all(
+ statement.value.same_as(variable) for statement, variable in zip(loop.seq, variables)
+ )
- def custom_range(extent):
- calls.append(extent)
- return T.serial(2)
- function = parser.parse(
- "@T.prim_func\ndef main():\n range = custom_range\n"
- " for i in range(4):\n T.evaluate(i)\n",
- extra_vars={"custom_range": custom_range},
- )
- assert calls == [4]
- assert isinstance(function.body, tirx.For)
- assert int(function.body.extent) == 2
- assert function.body.body.value.same_as(function.body.loop_var)
+def test_singleton_tuple_loop_target_keeps_sequence_shape():
+ # Before: for (i,) in X.grid(4): X.evaluate(i)
+ # Expected builder program: with X.for_(X.grid(4), names=("i",)) as (i,): ...
+ with IRBuilder() as builder:
+ frame = T.for_(T.grid(4), names=("i",))
+ with frame as variables:
+ assert len(variables) == 1
+ T.evaluate(variables[0])
+ assert builder.get().loop_var.same_as(variables[0])
+
+
+def test_body_attribute_overrides_default_after_declaration():
+ # Before: @X.prim_func def main(): X.func_attr({"global_symbol": "custom"})
+ # Expected builder program:
+ # with X.function(decl=True) as fn: X.func_name("main")
+ # with fn: X.func_attr({"global_symbol": "custom"}); X.emit_(X.evaluate(0))
+ with IRBuilder() as builder, I.ir_module():
+ with T.function(decl=True) as frame:
+ T.func_name("main")
+ with frame:
+ T.func_attr({"global_symbol": "custom"})
+ T.evaluate(0)
+ assert builder.get()["main"].attrs["global_symbol"] == "custom"
diff --git a/tests/python/unittest/test_parser_support.py b/tests/python/tirx/script/test_parser_tirx_resolvers.py
similarity index 52%
rename from tests/python/unittest/test_parser_support.py
rename to tests/python/tirx/script/test_parser_tirx_resolvers.py
index 3eef773a72..8d37ea039a 100644
--- a/tests/python/unittest/test_parser_support.py
+++ b/tests/python/tirx/script/test_parser_tirx_resolvers.py
@@ -14,7 +14,7 @@
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
-"""Native resolver ownership and eager annotation contracts."""
+"""Native function and module resolver ownership."""
from typing import TypeVar
@@ -22,7 +22,6 @@ import pytest
from tvm import ir
from tvm.relax.script import builder as R
-from tvm.script import parser
from tvm.script.ir_builder import IRBuilder
from tvm.script.ir_builder import ir as I
from tvm.script.parser import protocol
@@ -45,20 +44,7 @@ def test_global_info_requires_module_and_keeps_objects():
I.resolve_global_info("cuda:1")
-def test_global_info_selectors_use_module_map():
- # Before: X.Tensor((4,), "float32", vdevice="cuda:1")
- # Expected builder program: I.resolve_global_info("cuda:1") is mod.global_infos["vdevice"][2]
- with IRBuilder(), I.ir_module() as module:
- devices = [I.vdevice("llvm"), I.vdevice("cuda"), I.vdevice("cuda", 1)]
- I.module_global_infos({"vdevice": devices, "other": [I.dummy_global_info()]})
- for spelling, index in (("cuda:1", 2), ("vdevice[1]", 1), ("cuda", 1)):
- resolved = I.resolve_global_info(spelling)
- assert resolved.__chandle__() == devices[index].__chandle__()
- assert resolved.__chandle__() == module.global_infos["vdevice"][index].__chandle__()
- assert I.resolve_global_info("other[0]") is not None
-
-
-@pytest.mark.parametrize("dialect", [T, R])
+@pytest.mark.parametrize("dialect", [T])
def test_symbol_lookup_requires_function_and_reuses_native_identity(dialect):
# Before: n = X.int64(); X.Tensor(("n",), "float32")
# Expected builder program: n = X.resolve_type_var_("n", "int64")
@@ -79,24 +65,6 @@ def test_symbol_lookup_requires_function_and_reuses_native_identity(dialect):
R.func_ret_value(R.const(0))
-def test_nested_functions_have_distinct_symbol_maps():
- # Before: @X.function outer(..."n"...): @X.function inner(..."n"...): ...
- # Expected builder program: X.resolve_type_var_("n") selects the nearest entered fn.
- with IRBuilder(), R.function() as outer:
- outer_n = R.resolve_type_var_("n")
- with R.function(decl=True, local=True) as inner:
- R.func_name("inner")
- inner_n = R.resolve_type_var_("n")
- assert not inner_n.same_as(outer_n)
- assert inner.type_var_map["n"].same_as(inner_n)
- with inner:
- assert R.resolve_type_var_("n").same_as(inner_n)
- R.func_ret_value(R.const(0))
- assert R.resolve_type_var_("n").same_as(outer_n)
- assert outer.type_var_map["n"].same_as(outer_n)
- R.func_ret_value(R.const(0))
-
-
def test_eager_annotations_preserve_missing_type_and_concrete_construction():
# Before: X.Tensor(("n",)); captured_shape = (n,); X.Tensor(captured_shape)
# Expected builder program: X.Tensor((X.resolve_type_var_("n"),)); X.Tensor(captured_shape)
@@ -114,43 +82,3 @@ def test_eager_annotations_preserve_missing_type_and_concrete_construction():
with pytest.raises(TypeError, match="concrete symbols"):
tensor(("n",))
T.evaluate(0)
-
-
-def test_annotation_class_supports_union_and_missing_type():
- # Before: X.Annotation("n") | None
- # Expected builder program: X.Annotation((X.resolve_type_var_("n"))) in a function frame.
- @protocol.args_policy({"shape": "expr_str"}, as_type=True)
- def annotation(shape):
- return shape
-
- assert isinstance(annotation, type)
- assert annotation | None
- assert annotation(16) == 16
- assert annotation("n").is_missing()
-
-
-def test_generated_module_enters_global_info_scope_before_annotations():
- # Before: I.module_global_infos(info); def f(x: X.Tensor(..., vdevice="cuda:1")): ...
- # Expected builder program: with I.ir_module(): I.module_global_infos(info); X.arg(...)
- module = parser.parse("""
-@I.ir_module
-class Module:
- I.module_global_infos({
- "vdevice": [I.vdevice("llvm"), I.vdevice("cuda"), I.vdevice("cuda", 1)],
- "mesh": [R.device_mesh((2,), [0, 1])],
- })
- @R.function
- def tensor(x: R.Tensor((4,), "float32", vdevice="cuda:1")):
- return x
- @R.function
- def distributed(x: R.DTensor((4,), "float32", device_mesh="mesh[0]", placement="S[0]")):
- return x
-""")
- assert (
- module["tensor"].params[0].ty.vdevice.__chandle__()
- == module.global_infos["vdevice"][2].__chandle__()
- )
- assert (
- module["distributed"].params[0].ty.device_mesh.__chandle__()
- == module.global_infos["mesh"][0].__chandle__()
- )
diff --git a/tests/python/tirx/script/test_tirx_parser_comparison_integration.py b/tests/python/tirx/script/test_tirx_parser_comparison_integration.py
new file mode 100644
index 0000000000..9f853c2575
--- /dev/null
+++ b/tests/python/tirx/script/test_tirx_parser_comparison_integration.py
@@ -0,0 +1,199 @@
+# 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.
+"""TIRx comparison conversion, shared effectful operands, and typed PTX predicates."""
+
+import pytest
+
+import tvm
+from tvm import ir, tirx
+from tvm.script import parser
+from tvm.script import tirx as T
+from tvm.script.ir_builder import IRBuilder
+
+OPERATORS = [("<", "LT"), ("<=", "LE"), (">", "GT"), (">=", "GE"), ("==", "EQ"), ("!=", "NE")]
+
+
+@pytest.mark.parametrize("operator,kind", OPERATORS)
+def test_constexpr_preserves_host_comparison_with_iterator(operator, kind):
+ class Result:
+ def __bool__(self):
+ raise AssertionError("custom comparison result must not be truth-tested")
+
+ def asobject(self):
+ raise AssertionError("custom comparison result must not be converted")
+
+ result = Result()
+ calls = []
+
+ class Host:
+ pass
+
+ def compare(self, other):
+ calls.append(other)
+ return result
+
+ setattr(
+ Host,
+ {
+ "LT": "__lt__",
+ "LE": "__le__",
+ "GT": "__gt__",
+ "GE": "__ge__",
+ "EQ": "__eq__",
+ "NE": "__ne__",
+ }[kind],
+ compare,
+ )
+
+ def consume(value):
+ assert value is result
+ return 0
+
+ right = tirx.IterVar(None, "axis", tirx.IterVar.DataPar)
+ parser.parse(
+ "@T.prim_func\ndef main(x: T.int32):\n"
+ f" T.evaluate(consume(T.constexpr(left {operator} right)))\n",
+ extra_vars={"left": Host(), "right": right, "consume": consume},
+ )
+ assert len(calls) == 1
+ assert calls[0] is right
+
+
+def test_chain_binds_effectful_middle_operand_once():
+ actual = parser.parse("""
+@T.prim_func
+def main():
+ T.evaluate(0 < T.call_extern("int32", "middle") < 10)
+""")
+ value = actual.body.value
+ assert isinstance(value, tirx.Let)
+ assert isinstance(value.value, ir.Call)
+ expected = tirx.And(tirx.LT(0, value.var), tirx.LT(value.var, 10))
+ ir.assert_structural_equal(value.body, expected)
+
+
+@pytest.mark.parametrize("operator,kind", OPERATORS)
+def test_iterator_comparison_keeps_written_operand_order(operator, kind):
+ calls = []
+
+ def axis(value):
+ calls.append(value)
+ return tirx.IterVar(None, value, tirx.IterVar.DataPar)
+
+ actual = parser.parse(
+ f"@T.prim_func\ndef main(x: T.int32):\n T.evaluate(0 {operator} axis(x))\n",
+ extra_vars={"axis": axis},
+ )
+ assert len(calls) == 1
+ assert calls[0].same_as(actual.params[0])
+ ir.assert_structural_equal(actual.body.value, getattr(tirx, kind)(0, actual.params[0]))
+
+
+@pytest.mark.parametrize("operator,kind", OPERATORS)
+def test_unmarked_host_comparison_never_calls_python_overload(operator, kind):
+ from tvm.error import DiagnosticError
+
+ calls = []
+
+ class Host:
+ pass
+
+ def comparison(self, other):
+ calls.append(other)
+ return True
+
+ setattr(
+ Host,
+ {
+ "LT": "__lt__",
+ "LE": "__le__",
+ "GT": "__gt__",
+ "GE": "__ge__",
+ "EQ": "__eq__",
+ "NE": "__ne__",
+ }[kind],
+ comparison,
+ )
+ decorator = "T.prim_func"
+ statement = "T.evaluate(left " + operator + " right)"
+ with pytest.raises(DiagnosticError, match="(PrimExpr|primitive|convert|type)"):
+ parser.parse(
+ f"@{decorator}\ndef main():\n {statement}\n",
+ extra_vars={"left": Host(), "right": Host()},
+ )
+ assert calls == []
+
+
+@pytest.mark.parametrize(
+ "kind,source",
+ [
+ (
+ "store",
+ """
+@T.prim_func
+def main(dst: T.Buffer((2,), "uint32")):
+ T.device_entry()
+ tx = T.thread_id([32])
+ T.ptx.st.global_.v2.b32(
+ T.ptx.addr(dst.data, 0), T.uint32(1), T.uint32(2), pred=tx == 0
+ )
+""",
+ ),
+ (
+ "mma",
+ """
+@T.prim_func
+def main():
+ T.device_entry()
+ tx = T.thread_id([32])
+ tmem = T.local_scalar("uint32")
+ desc = T.local_scalar("uint64")
+ idesc = T.local_scalar("uint32")
+ T.ptx["tcgen05.mma.cta_group::1.kind::f16"](
+ tmem, desc, desc, idesc, 0, 0, 0, 0, tx == 0
+ )
+""",
+ ),
+ ],
+)
+def test_backend_predicate_materializes_equality(kind, source):
+ with IRBuilder() as builder:
+ with T.function():
+ T.func_name("main")
+ if kind == "store":
+ dst = T.arg("dst", T.Buffer((2,), "uint32"))
+ T.device_entry()
+ tx = T.thread_id([32]).value
+ predicate = tirx.EQ(tx, 0)
+ if kind == "store":
+ T.emit_(
+ T.ptx.st.global_.v2.b32(
+ T.ptx.addr(dst.data, 0), T.uint32(1), T.uint32(2), pred=predicate
+ )
+ )
+ else:
+ tmem = T.local_scalar("uint32")
+ desc = T.local_scalar("uint64")
+ idesc = T.local_scalar("uint32")
+ T.emit_(
+ T.ptx["tcgen05.mma.cta_group::1.kind::f16"](
+ tmem, desc, desc, idesc, 0, 0, 0, 0, predicate
+ )
+ )
+ expected = builder.get()
+ actual = parser.parse(source)
+ tvm.ir.assert_structural_equal(expected, actual)
diff --git a/tests/python/tirx/test_parser_constexpr.py b/tests/python/tirx/test_parser_constexpr.py
deleted file mode 100644
index 2d0ffc958e..0000000000
--- a/tests/python/tirx/test_parser_constexpr.py
+++ /dev/null
@@ -1,264 +0,0 @@
-# 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.
-"""Explicit host selection preserves builder scope and source evaluation."""
-
-import pytest
-
-from tvm import ir, tirx
-from tvm.script import parser
-from tvm.script import tirx as T
-from tvm.script.ir_builder import ir as I
-
-
-@pytest.mark.parametrize("marker", ["I.constexpr", "T.constexpr"])
-@pytest.mark.parametrize("track_span", [True, False])
-def test_marked_if_shares_parent_scope(marker, track_span):
- seen = []
-
- def choose():
- seen.append("condition")
- return True
-
- result = parser.parse(
- f"""
-@T.prim_func
-def main(a: T.handle):
- if {marker}(choose()):
- A = T.match_buffer(a, (4,), "int32")
- else:
- invalid()
- A[0] = 3
-""",
- extra_vars={"choose": choose},
- track_span=track_span,
- )
- assert seen == ["condition"]
- assert len(result.params) == 1
- assert isinstance(result.body, tirx.BufferStore)
- assert result.body.buffer.same_as(result.params[0])
-
-
-def test_marked_expressions_are_lazy_operand_valued_and_ordered():
- seen = []
-
- def operand(value):
- seen.append(value)
- return value
-
- result = parser.parse(
- """
-@T.prim_func
-def main():
- T.evaluate(operand(1) if I.constexpr(operand(True)) else invalid())
- T.evaluate(I.constexpr(operand(0)) and invalid())
- T.evaluate(I.constexpr(operand(4)) or invalid())
- T.evaluate(I.constexpr(operand(2)) and operand(7))
- T.evaluate(I.constexpr(operand(0)) or operand(8))
-""",
- extra_vars={"operand": operand},
- )
- assert seen == [True, 1, 0, 4, 2, 7, 0, 8]
- assert [node.value.value for node in result.body.seq] == [1, 4, 7, 8]
-
-
-def test_unmarked_expression_eagerly_constructs_both_ir_arms():
- seen = []
-
- def operand(value):
- seen.append(value)
- return value
-
- result = parser.parse(
- """
-@T.prim_func
-def main(condition: T.bool):
- T.evaluate(operand(1) if condition else operand(2))
- T.evaluate(condition and operand(True))
- T.evaluate(condition or operand(False))
-""",
- extra_vars={"operand": operand},
- )
- assert seen == [1, 2, True, False]
- assert isinstance(result.body.seq[0].value, ir.Call)
- assert isinstance(result.body.seq[1].value, tirx.And)
- assert isinstance(result.body.seq[2].value, tirx.Or)
-
-
-def test_nested_unmarked_statement_retains_ir_frame():
- result = parser.parse("""
-@T.prim_func
-def main(condition: T.bool):
- if I.constexpr(True):
- if condition:
- T.evaluate(1)
- else:
- T.evaluate(2)
-""")
- assert isinstance(result.body, tirx.IfThenElse)
-
-
-def test_captured_shapes_require_explicit_symbols():
- n = ir.Var("n", "int64")
- source = """
-@R.function
-def main(x: R.Tensor(shape, "float32")):
- return x
-"""
- result = parser.parse(source, extra_vars={"shape": (n, 16)})
- assert result.params[0].ty.shape[0].same_as(n)
- with pytest.raises(Exception):
- parser.parse(source, extra_vars={"shape": ("n", 16)})
-
-
-def test_dialect_marker_is_same_protocol_identity():
- assert T.constexpr is I.constexpr
-
-
-@pytest.mark.parametrize("condition", [True, False])
-def test_conditional_binding_can_be_assigned_after_skipped_branch(condition):
- result = parser.parse(f"""
-@T.prim_func
-def main():
- if I.constexpr({condition}):
- x = 1
- x = 2
- T.evaluate(x)
-""")
- assert isinstance(result.body, tirx.SeqStmt)
- assert isinstance(result.body.seq[-1], tirx.Evaluate)
-
-
-@pytest.mark.parametrize("operator", ["and", "or"])
-def test_unmarked_logical_chain_preserves_left_association(operator):
- source = f"""
-@T.prim_func
-def main(a: T.bool, b: T.bool, c: T.bool):
- T.evaluate(a {operator} b {operator} c)
-"""
- variables = [tirx.Var(name, "bool") for name in ("a", "b", "c")]
- constructor = tirx.And if operator == "and" else tirx.Or
- expected = tirx.PrimFunc(
- variables, tirx.Evaluate(constructor(constructor(*variables[:2]), variables[2]))
- ).with_attr("global_symbol", "main")
- ir.assert_structural_equal(expected, parser.parse(source))
-
-
-@pytest.mark.parametrize("track_span", [True, False])
-def test_constexpr_keeps_named_expression_unsupported(track_span):
- with pytest.raises(Exception, match="Unsupported expression: NamedExpr"):
- parser.parse(
- """
-@T.prim_func
-def main():
- if I.constexpr(bool(x := 3)):
- T.evaluate(x)
-""",
- track_span=track_span,
- )
-
-
-def test_ir_optional_binding_survives_skipped_host_assignment():
- result = parser.parse("""
-@T.prim_func
-def main(condition: T.bool):
- if condition:
- x = T.int32(1)
- if I.constexpr(False):
- x = T.int32(2)
- x = T.int32(3)
- T.evaluate(x)
-""")
- assert isinstance(result.body, tirx.SeqStmt)
-
-
-@pytest.mark.parametrize(
- "expression", ["1 if I.constexpr(x) else 0", "I.constexpr(x) and 1", "I.constexpr(x) or 1"]
-)
-def test_missing_host_binding_cannot_be_truth_tested(expression):
- from tvm.error import DiagnosticError
-
- with pytest.raises(DiagnosticError) as caught:
- parser.parse(f"""
-@T.prim_func
-def main():
- if I.constexpr(False):
- x = 1
- T.evaluate({expression})
-""")
- assert isinstance(caught.value.__cause__, NameError)
-
-
-def test_missing_host_if_binding_raises_before_branch_assignments():
- from tvm.error import DiagnosticError
-
- with pytest.raises(DiagnosticError) as caught:
- parser.parse("""
-@T.prim_func
-def main():
- if I.constexpr(False):
- x = 1
- if I.constexpr(x):
- x = 2
- else:
- x = 3
-""")
- assert isinstance(caught.value.__cause__, NameError)
-
-
-def test_host_lambda_local_does_not_capture_optional_binding():
- result = parser.parse("""
-@T.prim_func
-def main():
- if I.constexpr(False):
- x = 1
- if I.constexpr((lambda x: x)(True)):
- T.evaluate(222)
-""")
- assert result.body.value.value == 222
-
-
-def test_parser_skips_invalid_ramp_and_preserves_support_name():
- # Before: X.ramp(0, 1, _PS) if I.constexpr(_PS > 1) else 0
- # Expected builder program: X.ramp(0, 1, _PS) if _PS > 1 else 0
- # The captured _PS name remains an ordinary user binding.
- source = """
-@T.prim_func
-def main():
- T.evaluate(T.ramp(0, 1, _PS) if I.constexpr(_PS > 1) else 0)
-"""
- function = parser.parse(source, extra_vars={"_PS": 1})
- assert isinstance(function.body, tirx.Evaluate)
- assert function.body.value.value == 0
-
-
-def test_source_logical_operands_skip_at_construction():
- # Before: value if I.constexpr(False and fail()) else fallback
- # Expected builder program: value if False and fail() else fallback
- # Calls inside the constexpr operand retain Python short-circuit behavior.
- def fail():
- raise AssertionError("skipped source operand was evaluated")
-
- function = parser.parse(
- """
-@T.prim_func
-def main():
- T.evaluate(1 if I.constexpr(False and fail()) else 2)
- T.evaluate(3 if I.constexpr(True or fail()) else 4)
-""",
- extra_vars={"fail": fail},
- )
- assert [statement.value.value for statement in function.body.seq] == [2, 3]
diff --git a/tests/python/unittest/test_parser_comparison_source_order.py b/tests/python/unittest/test_parser_comparison_source_order.py
deleted file mode 100644
index 654fd4bf3f..0000000000
--- a/tests/python/unittest/test_parser_comparison_source_order.py
+++ /dev/null
@@ -1,298 +0,0 @@
-# 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.
-"""Comparisons preserve source orientation while explicit constexpr retains host overloads."""
-
-import pytest
-
-from tvm import ir, tirx
-from tvm.script import parser
-
-OPERATORS = [("<", "LT"), ("<=", "LE"), (">", "GT"), (">=", "GE"), ("==", "EQ"), ("!=", "NE")]
-
-
-@pytest.mark.parametrize("operator,kind", OPERATORS)
-@pytest.mark.parametrize("literal_left", [True, False])
-@pytest.mark.parametrize("track_span", [True, False])
-def test_written_comparison_order(operator, kind, literal_left, track_span):
- expression = f"0 {operator} x" if literal_left else f"x {operator} 0"
- actual = parser.parse(
- f"@T.prim_func\ndef main(x: T.int32):\n T.evaluate({expression})\n",
- track_span=track_span,
- )
- x = actual.params[0]
- operands = (0, x) if literal_left else (x, 0)
- ir.assert_structural_equal(actual.body.value, getattr(tirx, kind)(*operands))
- if track_span:
- assert actual.body.value.span is not None
-
-
-@pytest.mark.parametrize("dtype", ["int64", "uint32", "float32", "int32x4", "float32x4"])
-def test_literal_uses_ir_operand_type_and_lanes(dtype):
- actual = parser.parse(f"@T.prim_func\ndef main(x: T.{dtype}):\n T.evaluate(0 < x)\n")
- value = actual.body.value
- assert isinstance(value, tirx.LT)
- assert str(value.a.ty) == str(value.b.ty) == dtype
- assert value.b.same_as(actual.params[0])
-
-
-@pytest.mark.parametrize("operator,kind", OPERATORS)
-@pytest.mark.parametrize("other_kind", ["host", "primitive", "iterator"])
-def test_custom_host_comparison_result_is_preserved(operator, kind, other_kind):
- class Result:
- def __bool__(self):
- raise AssertionError("custom comparison result must not be truth-tested")
-
- def asobject(self):
- raise AssertionError("custom comparison result must not be converted")
-
- result = Result()
- calls = []
-
- class Host:
- pass
-
- def compare(self, other):
- calls.append(other)
- return result
-
- setattr(
- Host,
- {
- "LT": "__lt__",
- "LE": "__le__",
- "GT": "__gt__",
- "GE": "__ge__",
- "EQ": "__eq__",
- "NE": "__ne__",
- }[kind],
- compare,
- )
-
- def consume(value):
- assert value is result
- return 0
-
- other = "x" if other_kind == "primitive" else "right"
- right = (
- tirx.IterVar(None, "axis", tirx.IterVar.DataPar) if other_kind == "iterator" else object()
- )
- actual = parser.parse(
- "@T.prim_func\ndef main(x: T.int32):\n"
- f" T.evaluate(consume(T.constexpr(left {operator} {other})))\n",
- extra_vars={"left": Host(), "right": right, "consume": consume},
- )
- assert len(calls) == 1
- if other_kind == "primitive":
- assert calls[0].same_as(actual.params[0])
- else:
- assert calls[0] is right
-
-
-def test_numeric_subclass_keeps_custom_comparison():
- seen = []
- result = object()
-
- class HostInt(int):
- def __lt__(self, other):
- seen.append(other)
- return result
-
- def consume(value):
- assert value is result
- return 0
-
- parser.parse(
- "@T.prim_func\ndef main(x: T.int32):\n T.evaluate(consume(T.constexpr(left < x)))\n",
- extra_vars={"left": HostInt(0), "consume": consume},
- )
- assert len(seen) == 1
-
-
-def test_host_ordering_does_not_materialize_an_equality_result():
- result = tirx.Var("host_result", "int32") == 0
-
- class Host:
- def __lt__(self, other):
- return result
-
- def consume(value):
- assert value is result
- return 0
-
- parser.parse(
- "@T.prim_func\ndef main():\n T.evaluate(consume(T.constexpr(left < right)))\n",
- extra_vars={"left": Host(), "right": Host(), "consume": consume},
- )
-
-
-def test_chain_evaluates_source_operands_once_in_order():
- seen = []
-
- def operand(index, value):
- seen.append(index)
- return value
-
- actual = parser.parse(
- """
-@T.prim_func
-def main(x: T.int32, y: T.int32):
- T.evaluate(operand(0, 0) < operand(1, x) <= operand(2, y) != operand(3, 3))
-""",
- extra_vars={"operand": operand},
- )
- x, y = actual.params
- expected = tirx.And(tirx.LT(0, x), tirx.And(tirx.LE(x, y), tirx.NE(y, 3)))
- ir.assert_structural_equal(actual.body.value, expected)
- assert seen == [0, 1, 2, 3]
-
-
-def test_chain_binds_effectful_middle_operand_once():
- actual = parser.parse("""
-@T.prim_func
-def main():
- T.evaluate(0 < T.call_extern("int32", "middle") < 10)
-""")
- value = actual.body.value
- assert isinstance(value, tirx.Let)
- assert isinstance(value.value, ir.Call)
- expected = tirx.And(tirx.LT(0, value.var), tirx.LT(value.var, 10))
- ir.assert_structural_equal(value.body, expected)
-
-
-def test_constexpr_keeps_python_comparison_and_chain_short_circuit():
- seen = []
-
- def operand(index, value):
- seen.append(index)
- return value
-
- def invalid():
- raise AssertionError("constexpr comparison chain must short-circuit")
-
- actual = parser.parse(
- """
-@T.prim_func
-def main(x: T.int32):
- if T.constexpr(operand(0, 2) < operand(1, 1) < invalid()):
- T.evaluate(0)
- elif T.constexpr(x == x):
- T.evaluate(1)
-""",
- extra_vars={"operand": operand, "invalid": invalid},
- )
- assert seen == [0, 1]
- assert actual.body.value.value == 1
-
-
-@pytest.mark.parametrize("operator,kind", OPERATORS)
-@pytest.mark.parametrize("dtype", ["int64", "float32", "int64x4"])
-def test_comparisons_use_native_promotion_and_broadcast(operator, kind, dtype):
- actual = parser.parse(
- f"@T.prim_func\ndef main(x: T.int32, y: T.{dtype}):\n T.evaluate(x {operator} y)\n"
- )
- x, y = actual.params
- lhs = tirx.Broadcast(tirx.Cast("int64", x), 4) if dtype.endswith("x4") else tirx.Cast(dtype, x)
- expected = getattr(tirx, kind)(lhs, y)
- ir.assert_structural_equal(actual.body.value, expected)
-
-
-@pytest.mark.parametrize("operator,kind", OPERATORS)
-def test_iterator_comparison_keeps_written_operand_order(operator, kind):
- calls = []
-
- def axis(value):
- calls.append(value)
- return tirx.IterVar(None, value, tirx.IterVar.DataPar)
-
- actual = parser.parse(
- f"@T.prim_func\ndef main(x: T.int32):\n T.evaluate(0 {operator} axis(x))\n",
- extra_vars={"axis": axis},
- )
- assert len(calls) == 1
- assert calls[0].same_as(actual.params[0])
- ir.assert_structural_equal(actual.body.value, getattr(tirx, kind)(0, actual.params[0]))
-
-
-@pytest.mark.parametrize("operator,kind", OPERATORS)
-@pytest.mark.parametrize("dialect", ["T", "R"])
-def test_unmarked_host_comparison_never_calls_python_overload(operator, kind, dialect):
- from tvm.error import DiagnosticError
-
- calls = []
-
- class Host:
- pass
-
- def comparison(self, other):
- calls.append(other)
- return True
-
- setattr(
- Host,
- {
- "LT": "__lt__",
- "LE": "__le__",
- "GT": "__gt__",
- "GE": "__ge__",
- "EQ": "__eq__",
- "NE": "__ne__",
- }[kind],
- comparison,
- )
- decorator = "T.prim_func" if dialect == "T" else "R.function"
- statement = (
- "T.evaluate(left " + operator + " right)"
- if dialect == "T"
- else "return left " + operator + " right"
- )
- with pytest.raises(DiagnosticError, match="(PrimExpr|primitive|convert|type)"):
- parser.parse(
- f"@{decorator}\ndef main():\n {statement}\n",
- extra_vars={"left": Host(), "right": Host()},
- )
- assert calls == []
-
-
-@pytest.mark.parametrize("operator,kind", OPERATORS)
-def test_relax_tensor_comparison_constructs_written_operator(operator, kind):
- from tvm import relax
-
- operation = {
- "LT": "less",
- "LE": "less_equal",
- "GT": "greater",
- "GE": "greater_equal",
- "EQ": "equal",
- "NE": "not_equal",
- }[kind]
- actual = parser.parse(
- '@R.function\ndef main(x: R.Tensor((2,), "float32"), y: R.Tensor((2,), "float32")):\n'
- f" return x {operator} y\n",
- track_span=True,
- )
- call = actual.body.blocks[0].bindings[0].value
- expected = relax.BlockBuilder().normalize(getattr(relax.op, operation)(*actual.params))
- ir.assert_structural_equal(call, expected)
- assert call.span is not None
-
-
-@pytest.mark.parametrize("operator,kind", OPERATORS)
-def test_relax_primitive_comparison_is_concrete_ir(operator, kind):
- actual = parser.parse(
- f'@R.function\ndef main(x: R.Prim("int32")):\n return 0 {operator} x\n'
- )
- ir.assert_structural_equal(actual.body.body, getattr(tirx, kind)(0, actual.params[0]))
diff --git a/tests/python/unittest/test_parser_comparison_values.py b/tests/python/unittest/test_parser_comparison_values.py
deleted file mode 100644
index 905461ee0a..0000000000
--- a/tests/python/unittest/test_parser_comparison_values.py
+++ /dev/null
@@ -1,203 +0,0 @@
-# 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.
-"""Source equality reaches typed consumers as concrete boolean IR."""
-
-import pytest
-import tvm_ffi
-
-import tvm
-from tvm import ir, tirx
-from tvm.ir._overload_prim_expr import EqualOp
-from tvm.script import parser
-from tvm.script import tirx as T
-from tvm.script.ir_builder import IRBuilder
-
-
-@pytest.mark.parametrize("operator, kind", [("==", tirx.EQ), ("!=", tirx.NE)])
-@pytest.mark.parametrize("track_span", [True, False])
-def test_symbolic_equality_reaches_typed_consumer(operator, kind, track_span):
- seen = []
-
- def consume(value):
- assert isinstance(value, kind)
- assert str(value.ty) == "bool"
- seen.append(value)
- return value
-
- source = f"""
-@T.prim_func
-def main(x: T.int32):
- T.evaluate(consume(x {operator} 0))
-"""
- actual = parser.parse(source, extra_vars={"consume": consume}, track_span=track_span)
- assert len(seen) == 1
- assert seen[0].a.same_as(actual.params[0])
- if track_span:
- assert seen[0].span is not None
-
-
-def test_python_comparisons_remain_python_booleans():
- seen = []
-
- def consume(value):
- assert type(value) is bool
- seen.append(value)
- return int(value)
-
- parser.parse(
- """
-@T.prim_func
-def main():
- T.evaluate(consume(T.constexpr([1, 2] == [1, 2])))
- T.evaluate(consume(T.constexpr("x" != "y")))
-""",
- extra_vars={"consume": consume},
- )
- assert seen == [True, True]
-
-
-def test_host_equality_result_is_not_arbitrarily_converted():
- class HostResult(tvm_ffi.ObjectConvertible):
- def asobject(self):
- raise AssertionError("host comparison result must not be converted")
-
- result = HostResult()
-
- class Host:
- def __eq__(self, other):
- return result
-
- seen = []
-
- def consume(value):
- assert value is result
- seen.append(value)
- return 0
-
- parser.parse(
- """
-@T.prim_func
-def main():
- T.evaluate(consume(T.constexpr(left == right)))
-""",
- extra_vars={"left": Host(), "right": Host(), "consume": consume},
- )
- assert seen == [result]
- assert seen[0] is result
-
- class CustomEquality(EqualOp):
- def asobject(self):
- raise AssertionError("custom equality subclasses are host values")
-
- custom = CustomEquality(tirx.Var("x", "int32"), 0)
- result = custom
- parser.parse(
- """
-@T.prim_func
-def main():
- T.evaluate(consume(T.constexpr(left == right)))
-""",
- extra_vars={"left": Host(), "right": Host(), "consume": consume},
- )
- assert seen[-1] is custom
-
-
-@pytest.mark.parametrize(
- "expression", ["operand(0) == operand(1)", "operand(0) == operand(1) != operand(2)"]
-)
-def test_comparison_operands_evaluate_once_in_order(expression):
- seen = []
-
- def operand(index, value):
- seen.append(index)
- return value
-
- def consume(value):
- assert isinstance(value, ir.Expr)
- assert str(value.ty) == "bool"
- return value
-
- expression = expression.replace("operand(0)", "operand(0, value0)")
- expression = expression.replace("operand(1)", "operand(1, value1)")
- expression = expression.replace("operand(2)", "operand(2, value2)")
- parser.parse(
- "@T.prim_func\ndef main(value0: T.int32, value1: T.int32, value2: T.int32):\n"
- f" T.evaluate(consume({expression}))\n",
- extra_vars={"operand": operand, "consume": consume},
- )
- assert seen == ([0, 1, 2] if "!=" in expression else [0, 1])
-
-
-@pytest.mark.parametrize(
- "kind,source",
- [
- (
- "store",
- """
-@T.prim_func
-def main(dst: T.Buffer((2,), "uint32")):
- T.device_entry()
- tx = T.thread_id([32])
- T.ptx.st.global_.v2.b32(
- T.ptx.addr(dst.data, 0), T.uint32(1), T.uint32(2), pred=tx == 0
- )
-""",
- ),
- (
- "mma",
- """
-@T.prim_func
-def main():
- T.device_entry()
- tx = T.thread_id([32])
- tmem = T.local_scalar("uint32")
- desc = T.local_scalar("uint64")
- idesc = T.local_scalar("uint32")
- T.ptx["tcgen05.mma.cta_group::1.kind::f16"](
- tmem, desc, desc, idesc, 0, 0, 0, 0, tx == 0
- )
-""",
- ),
- ],
-)
-def test_backend_predicate_materializes_equality(kind, source):
- with IRBuilder() as builder:
- with T.function():
- T.func_name("main")
- if kind == "store":
- dst = T.arg("dst", T.Buffer((2,), "uint32"))
- T.device_entry()
- tx = T.thread_id([32]).value
- predicate = tirx.EQ(tx, 0)
- if kind == "store":
- T.emit_(
- T.ptx.st.global_.v2.b32(
- T.ptx.addr(dst.data, 0), T.uint32(1), T.uint32(2), pred=predicate
- )
- )
- else:
- tmem = T.local_scalar("uint32")
- desc = T.local_scalar("uint64")
- idesc = T.local_scalar("uint32")
- T.emit_(
- T.ptx["tcgen05.mma.cta_group::1.kind::f16"](
- tmem, desc, desc, idesc, 0, 0, 0, 0, predicate
- )
- )
- expected = builder.get()
- actual = parser.parse(source)
- tvm.ir.assert_structural_equal(expected, actual)
diff --git a/tests/python/unittest/test_parser_definition_context.py b/tests/python/unittest/test_parser_definition_context.py
deleted file mode 100644
index 7f3b3bcefe..0000000000
--- a/tests/python/unittest/test_parser_definition_context.py
+++ /dev/null
@@ -1,391 +0,0 @@
-# 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.
-"""Generated builders preserve definition annotations and Python lexical bodies."""
-
-from __future__ import annotations
-
-import numpy as np
-import pytest
-
-import tvm
-from tvm.script import ir as I
-from tvm.script import relax as R
-from tvm.script import tirx as T
-from tvm.script.ir_builder import IRBuilder
-
-EXTENT = 11
-VALUE = 1
-
-
-def _delayed(n, decorator):
- @decorator
- def function(output: T.Buffer((n,), "int32")):
- n = 2
- output[0] = n + VALUE
-
- return function
-
-
-@pytest.mark.parametrize("factory", [False, True])
-def test_reused_jit_decorator_captures_application_scope(factory):
- decorator = T.jit() if factory else T.jit
- pending = _delayed(8, decorator)
- n = 99 # noqa: F841
- VALUE = 20 # noqa: F841
- function = pending.specialize()
- assert [int(value) for value in function.params[0].ty.shape] == [8]
- compiled = tvm.compile(function, target="llvm", tir_pipeline="tirx")
- output = tvm.runtime.tensor(np.zeros(8, dtype="int32"))
- compiled(output)
- np.testing.assert_array_equal(output.numpy(), [3, 0, 0, 0, 0, 0, 0, 0])
-
-
-@pytest.mark.parametrize("factory", [False, True])
-def test_reused_eager_decorator_captures_application_scope(factory):
- decorator = T.prim_func() if factory else T.prim_func
- function = _delayed(4, decorator)
- assert [int(value) for value in function.params[0].ty.shape] == [4]
-
-
-def test_ir_module_class_annotation_scope_does_not_replace_body_global():
- @I.ir_module
- class Module:
- EXTENT = 3
-
- @T.prim_func
- def function(output: T.Buffer((EXTENT,), "int32")):
- output[0] = EXTENT
-
- function = Module["function"]
- assert [int(value) for value in function.params[0].ty.shape] == [3]
- assert function.body.value.value == 11
-
-
-def test_ordinary_class_annotation_scope_does_not_replace_body_global():
- class Holder:
- EXTENT = 3
-
- @T.prim_func
- def function(output: T.Buffer((EXTENT,), "int32")):
- output[0] = EXTENT
-
- assert [int(value) for value in Holder.function.params[0].ty.shape] == [3]
- assert Holder.function.body.value.value == 11
-
-
-def test_jit_annotation_snapshot_precedes_later_closure_mutation():
- def build():
- n = 4
-
- @T.jit
- def function(output: T.Buffer((n,), "int32")):
- output[0] = n
-
- n = 9
- return function
-
- function = build().specialize()
- assert [int(value) for value in function.params[0].ty.shape] == [4]
- assert function.body.value.value == 4
-
-
-def test_annotation_constructor_executes_in_required_builder_context():
- calls = []
-
- def annotation():
- calls.append(IRBuilder.is_in_scope())
- return T.Buffer((5,), "int32")
-
- @T.jit
- def function(output: annotation()):
- output[0] = 7
-
- assert calls == [] # postponed annotations are not evaluated at decoration
- result = function.specialize()
- assert calls == [True]
- assert [int(value) for value in result.params[0].ty.shape] == [5]
-
-
-def test_enclosing_namespace_used_only_by_annotation_is_retained():
- def build():
- dtype_namespace = T
-
- @T.jit
- def function(output: dtype_namespace.Buffer(("n",), "int32")):
- output[0] = 7
-
- return function
-
- result = build().specialize()
- assert isinstance(result.params[0].ty.shape[0], tvm.ir.Var)
- assert result.params[0].ty.shape[0].name == "n"
-
-
-def test_attribute_name_does_not_turn_a_closure_binding_into_a_global():
- from types import SimpleNamespace
-
- dtype = "int32"
- descriptor = SimpleNamespace(dtype="int64")
-
- @T.prim_func
- def function():
- T.evaluate(T.cast(3, dtype))
- T.evaluate(T.cast(4, descriptor.dtype))
-
- first, second = function.body.seq
- assert first.value.ty.dtype == "int32"
- assert first.value.value == 3
- assert second.value.ty.dtype == "int64"
- assert second.value.value == 4
-
-
-def test_local_annotation_retains_names_absent_from_signature():
- def build(shape, dtype):
- @R.function
- def function(x: R.Tensor((2,), "float32")):
- y: R.Tensor(shape, dtype) = R.add(x, x)
- return y
-
- return function
-
- @R.function
- def expected(x: R.Tensor((2,), "float32")):
- y: R.Tensor((2,), "float32") = R.add(x, x)
- return y
-
- actual = build((2,), "float32")
- tvm.ir.assert_structural_equal(
- actual.with_attr("global_symbol", ""), expected.with_attr("global_symbol", "")
- )
-
-
-def test_local_annotation_and_signature_share_retained_context():
- def build(shape, dtype):
- @I.ir_module
- class Module:
- @R.function
- def main(x: R.Tensor(shape, dtype)):
- with R.dataflow():
- y: R.Tensor(shape, dtype) = R.add(x, x)
- R.output(y)
- return y
-
- return Module
-
- @I.ir_module
- class Expected:
- @R.function
- def main(x: R.Tensor((2,), "float32")):
- with R.dataflow():
- y: R.Tensor((2,), "float32") = R.add(x, x)
- R.output(y)
- return y
-
- tvm.ir.assert_structural_equal(build((2,), "float32"), Expected)
-
-
-def test_local_annotation_preserves_explicit_parameter_and_d3_symbols():
- dtype = "float32"
-
- @R.function
- def function(n: R.Prim("int64"), x: R.Tensor((n, "m"), "float32")):
- m = T.int64()
- y: R.Tensor((n, m), dtype) = R.add(x, x)
- return y
-
- n, x = function.params
- binding = function.body.blocks[0].bindings[0]
- assert binding.var.ty.shape[0].same_as(n)
- assert binding.var.ty.shape[1].same_as(x.ty.shape[1])
- assert function.ret_ty.shape[0].same_as(n)
- assert function.ret_ty.shape[1].same_as(x.ty.shape[1])
-
-
-def test_local_annotation_keeps_rhs_before_constructor_evaluation():
- events = []
-
- def annotation():
- events.append("annotation")
- assert IRBuilder.is_in_scope()
- return R.Tensor((2,), "float32")
-
- def value(x):
- events.append("rhs")
- return R.add(x, x)
-
- @R.function
- def function(x: R.Tensor((2,), "float32")):
- y: annotation() = value(x)
- return y
-
- assert events == ["rhs", "annotation"]
- assert function.ret_ty == R.Tensor((2,), "float32")
-
-
-def test_local_annotation_scope_does_not_overwrite_ordinary_body_global():
- dtype = "float32"
-
- @I.ir_module
- class Module:
- EXTENT = 3
-
- @R.function
- def main(x: R.Tensor((3,), "float32")):
- R.func_attr({"body_extent": EXTENT})
- y: "R.Tensor((EXTENT,), dtype)" = R.add(x, x) # noqa: UP037
- return y
-
- function = Module["main"]
- assert function.attrs["body_extent"] == 11
- assert function.ret_ty.shape[0] == 3
- assert function.ret_ty.dtype == "float32"
-
-
-def test_local_annotation_preserves_lambda_and_comprehension_bindings():
- dtype = "int64" # noqa: F841
- size = 9 # noqa: F841
- sizes = (2,)
-
- @R.function
- def function(x: R.Tensor((2,), "float32")):
- y: (lambda dtype: R.Tensor(tuple(size for size in sizes), dtype))("float32") = R.add(x, x)
- return y
-
- assert function.ret_ty.shape[0] == 2
- assert function.ret_ty.dtype == "float32"
-
-
-def test_active_lexical_ancestor_retains_annotation_only_names():
- def outer(extent):
- def middle(width):
- @T.prim_func
- def function(output: T.Buffer((extent, width), "int32")):
- output[0, 0] = VALUE
-
- return function
-
- return middle(3)
-
- for extent in (4, 8):
- function = outer(extent)
- assert [int(value) for value in function.params[0].ty.shape] == [extent, 3]
- assert function.body.value.value == 1
-
-
-def test_active_lexical_ancestor_respects_nearest_annotation_binding():
- def outer(extent):
- def middle():
- extent = 3
-
- @T.prim_func
- def function(output: T.Buffer((extent,), "int32")):
- output[0] = VALUE
-
- return function
-
- return middle()
-
- function = outer(8)
- assert [int(value) for value in function.params[0].ty.shape] == [3]
-
-
-def test_unrelated_same_file_caller_does_not_supply_annotation_locals():
- def build():
- @T.prim_func
- def function(output: T.Buffer((EXTENT,), "int32")):
- output[0] = VALUE
-
- return function
-
- def caller():
- EXTENT = 99 # noqa: F841
- VALUE = 99 # noqa: F841
- return build()
-
- function = caller()
- assert [int(value) for value in function.params[0].ty.shape] == [11]
- assert function.body.value.value == 1
-
-
-def test_inactive_lexical_ancestor_is_not_replaced_by_unrelated_caller():
- def outer(extent):
- def middle():
- @T.prim_func
- def function(output: T.Buffer((extent,), "int32")):
- output[0] = VALUE
-
- return function
-
- return middle
-
- middle = outer(8)
- extent = 99 # noqa: F841
- with pytest.raises(tvm.error.DiagnosticError, match="extent"):
- middle()
-
-
-def test_enclosing_class_locals_are_not_nested_annotation_scope():
- class Outer:
- EXTENT = 99
-
- class Inner:
- @T.prim_func
- def function(output: T.Buffer((EXTENT,), "int32")):
- output[0] = EXTENT
-
- function = Outer.Inner.function
- assert [int(value) for value in function.params[0].ty.shape] == [11]
- assert function.body.value.value == 11
-
-
-@pytest.mark.parametrize("factory", [False, True])
-def test_jit_retains_active_lexical_ancestor_snapshot(factory):
- decorator = T.jit() if factory else T.jit
-
- def outer(extent):
- def middle(width):
- @decorator
- def function(output: T.Buffer((extent, width), "int32")):
- output[0, 0] = VALUE
-
- return function
-
- pending = middle(3)
- extent = 99
- return pending
-
- function = outer(8).specialize()
- assert [int(value) for value in function.params[0].ty.shape] == [8, 3]
- assert function.body.value.value == 1
-
-
-def test_unrelated_intervening_call_ends_annotation_capture():
- def invoke(callback):
- return callback()
-
- def outer(extent):
- def middle():
- @T.prim_func
- def function(output: T.Buffer((extent,), "int32")):
- output[0] = VALUE
-
- return function
-
- return invoke(middle)
-
- with pytest.raises(tvm.error.DiagnosticError, match="extent"):
- outer(8)
diff --git a/tests/python/unittest/test_parser_frontend_regressions.py b/tests/python/unittest/test_parser_frontend_regressions.py
deleted file mode 100644
index 74dc32e128..0000000000
--- a/tests/python/unittest/test_parser_frontend_regressions.py
+++ /dev/null
@@ -1,303 +0,0 @@
-# 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.
-"""Public construction preserves validation, source locations, and lexical bindings."""
-
-import numpy as np
-import pytest
-
-import tvm
-from tvm import ir, relax, tirx
-from tvm.error import DiagnosticError
-from tvm.relax import BasePyModule
-from tvm.script import ir as I
-from tvm.script import relax as R
-from tvm.script import tirx as T
-from tvm.script.parser.source import Source
-
-VALUE = 1
-MACRO_VALUE = 2
-
-
-def _build_lexical_global():
- @T.prim_func
- def write(A: T.Buffer((1,), "int32")):
- A[0] = VALUE
-
- return write
-
-
-def _build_symbolic_functions():
- @I.ir_module
- class Module:
- @R.function
- def first(x: R.Tensor(("n",), "float32")):
- n = T.int64() # noqa: F841
- return x
-
- @R.function
- def second(x: R.Tensor(("n",), "float32")):
- n = T.int64() # noqa: F841
- return x
-
- return Module
-
-
-def test_ordinary_class_member_constructs_prim_func():
- class Holder:
- @T.prim_func(s_tir=True)
- def function():
- T.evaluate(7)
-
- assert isinstance(Holder.function, tirx.PrimFunc)
- assert isinstance(Holder.function.body, tirx.Evaluate)
- assert Holder.function.body.value.value == 7
-
-
-def test_ir_module_defers_members_until_forward_signatures_exist():
- @I.ir_module
- class Module:
- @R.function
- def main(x: R.Tensor((2,), "float32")):
- return Module.identity(x)
-
- @R.function
- def identity(x: R.Tensor((2,), "float32")):
- return x
-
- assert isinstance(Module, ir.IRModule)
- call = Module["main"].body.blocks[0].bindings[0].value
- assert isinstance(call, ir.Call)
- assert call.op.same_as(Module.get_global_var("identity"))
- assert call.args[0].same_as(Module["main"].params[0])
- assert Module["identity"].body.body.same_as(Module["identity"].params[0])
-
-
-def _invalid_inplace_module(**options):
- @I.ir_module(**options)
- class Module:
- @T.prim_func(s_tir=True)
- def kernel(A: T.Buffer((2,), "int32")):
- T.evaluate(0)
-
- @R.function
- def main(x: R.Tensor((2,), "int32")):
- R.func_attr({"relax.force_pure": True})
- result = R.call_tir_inplace(
- Module.kernel,
- (x,),
- [0, 0],
- [R.Tensor((2,), "int32"), R.Tensor((2,), "int32")],
- )
- return result
-
- return Module
-
-
-def test_default_relax_validation_rejects_repeated_inplace_input():
- with pytest.raises(DiagnosticError):
- _invalid_inplace_module()
-
-
-def test_relax_validation_can_be_explicitly_disabled():
- module = _invalid_inplace_module(check_well_formed=False)
- assert isinstance(module["main"], relax.Function)
- call = module["main"].body.blocks[0].bindings[0].value
- assert list(call.attrs.inplace_indices) == [0, 0]
- assert not relax.analysis.check_well_formed(module)
-
-
-def test_default_tirx_validation_rejects_non_divisible_scope_extents():
- with pytest.raises(DiagnosticError):
-
- @T.prim_func
- def invalid():
- T.device_entry()
- block = T.cta_id([1])
- warp = T.warp_id([3])
- thread = T.thread_id([100])
- T.evaluate(block + warp + thread)
-
-
-def test_tirx_validation_can_be_explicitly_disabled():
- @T.prim_func(check_well_formed=False)
- def invalid():
- T.device_entry()
- block = T.cta_id([1])
- warp = T.warp_id([3])
- thread = T.thread_id([100])
- T.evaluate(block + warp + thread)
-
- assert isinstance(invalid, tirx.PrimFunc)
- definitions = invalid.body.body.seq[:3]
- assert all(isinstance(statement, tirx.ScopeIdDefStmt) for statement in definitions)
- with pytest.raises(tvm.error.InternalError, match="100 is not divisible by 3"):
- tirx.analysis.verify_tirx_well_formed(invalid)
-
-
-def test_python_module_factory_and_attached_function_execute():
- @I.ir_module
- class Module(BasePyModule):
- @I.pyfunc
- def twice(value):
- return value * 2
-
- assert callable(Module)
- assert Module.pyfuncs["twice"](3) == 6
- instance = Module(tvm.cpu())
- assert isinstance(instance, BasePyModule)
- assert instance.twice(4) == 8
- assert instance.pyfuncs["twice"](5) == 10
-
-
-def _position(span):
- return span.line, span.column, span.end_line, span.end_column
-
-
-@pytest.mark.parametrize("entrypoint", ["source", "function"])
-def test_source_and_ir_call_spans_use_one_based_columns(entrypoint):
- def direct():
- T.evaluate(T.call_extern("int32", "direct"))
-
- if entrypoint == "source":
- program = (
- "@T.prim_func(s_tir=True)\ndef direct():\n"
- ' T.evaluate(T.call_extern("int32", "direct"))\n'
- )
- source = Source(program)
- function = tvm.script.from_source(program)
- else:
- source = Source(direct)
- function = T.prim_func(direct, s_tir=True)
- call = source.as_ast().body[0].body[0].value.args[0]
- expected = source.to_span(call)
- assert expected.column == call.col_offset + source.start_column + 1
- assert expected.end_column == call.end_col_offset + source.start_column + 1
- assert _position(function.body.value.span) == _position(expected)
- assert function.body.value.span.source_name.name == source.source_name
-
-
-def test_nested_helper_spans_preserve_caller_and_definition_columns():
- text = """@T.inline
-def inner():
- T.evaluate(T.call_extern("int32", "nested"))
-@T.inline
-def outer():
- inner()
-@T.prim_func(s_tir=True)
-def main():
- outer()
-"""
- source = Source(text)
- inner, outer, main = source.as_ast().body
- calls = [main.body[0].value, outer.body[0].value, inner.body[0].value.args[0]]
- expected = [_position(source.to_span(call)) for call in calls]
- assert [position[1] for position in expected] == [5, 5, 16]
- function = tvm.script.from_source(text)
- span = function.body.value.span
- assert isinstance(span, ir.SequentialSpan)
- assert [_position(item) for item in span.spans] == expected
- assert all(item.source_name.name == "<str>" for item in span.spans)
-
-
-def test_optional_annotation_is_restricted_to_jit():
- with pytest.raises(DiagnosticError, match="only supported by @T.jit"):
-
- @T.prim_func(private=True)
- def invalid(value: T.Optional(T.handle)):
- T.evaluate(0)
-
- @T.jit(private=True)
- def valid(value: T.Optional(T.handle)):
- if I.constexpr(value is None):
- T.evaluate(1)
- else:
- T.evaluate(2)
-
- present, absent = valid.specialize(), valid.specialize(value=None)
- assert len(present.params) == 1
- assert len(absent.params) == 0
- assert present.body.value.value == 2
- assert absent.body.value.value == 1
-
-
-def test_lexical_global_is_not_replaced_by_dynamic_caller_local():
- VALUE = 2 # noqa: F841
- function = _build_lexical_global()
- assert function.body.value.value == 1
- compiled = tvm.compile(function, target="llvm", tir_pipeline="tirx")
- output = tvm.runtime.tensor(np.zeros(1, dtype="int32"))
- compiled(output)
- np.testing.assert_array_equal(output.numpy(), np.array([1], dtype="int32"))
-
-
-def test_annotation_only_enclosing_binding_is_captured():
- def build():
- shape = (3,)
-
- @T.prim_func
- def function(A: "T.Buffer(shape, 'int32')"):
- A[0] = 1
-
- return function
-
- shape = (7,) # noqa: F841
- function = build()
- assert [int(extent) for extent in function.params[0].ty.shape] == [3]
-
-
-def test_dynamic_caller_symbol_does_not_join_function_declarations():
- n = tirx.Var("n", "int64")
- module = _build_symbolic_functions()
- first = module["first"].params[0].ty.shape.ty.values[0]
- second = module["second"].params[0].ty.shape.ty.values[0]
- assert not first.same_as(second)
- assert not first.same_as(n)
- assert not second.same_as(n)
-
-
-@pytest.mark.parametrize("hygienic,expected", [(True, 2), (False, 1)])
-def test_macro_capture_policy_remains_explicit(hygienic, expected, monkeypatch):
- monkeypatch.setitem(globals(), "MACRO_VALUE", 2)
-
- @T.macro(hygienic=hygienic)
- def write(output):
- output[0] = MACRO_VALUE
-
- monkeypatch.setitem(globals(), "MACRO_VALUE", 1)
-
- @T.prim_func
- def function(output: T.Buffer((1,), "int32")):
- write(output)
-
- assert function.body.value.value == expected
-
-
-def _define_delayed_annotation(shape):
- @T.jit
- def function(output: "T.Buffer(shape, 'int32')"):
- output[0] = VALUE
-
- return function
-
-
-def test_delayed_jit_retains_annotation_only_definition_binding():
- pending = _define_delayed_annotation((3,))
- shape = (7,) # noqa: F841
- VALUE = 2 # noqa: F841
- function = pending.specialize()
- assert [int(extent) for extent in function.params[0].ty.shape] == [3]
- assert function.body.value.value == 1
diff --git a/tests/python/unittest/test_parser_nonlocal.py b/tests/python/unittest/test_parser_nonlocal.py
deleted file mode 100644
index c041a1cb36..0000000000
--- a/tests/python/unittest/test_parser_nonlocal.py
+++ /dev/null
@@ -1,57 +0,0 @@
-# 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.
-"""Enclosing lexical declarations retain captured values during construction."""
-
-import pytest
-
-from tvm import ir
-from tvm.script import parser
-from tvm.script import relax as R
-from tvm.script import tirx as T
-
-
-@pytest.mark.parametrize(
- "source,captures,expected_source",
- [
- (
- """
-@R.function
-def main(x: R.Tensor((2,), dtype)):
- nonlocal dtype
- return x
-""",
- {"R": R, "dtype": "float32"},
- '@R.function\ndef main(x: R.Tensor((2,), "float32")):\n return x\n',
- ),
- (
- """
-@T.prim_func
-def main():
- nonlocal value
- T.evaluate(value + 1)
-""",
- {"T": T, "value": 3},
- "@T.prim_func\ndef main():\n T.evaluate(4)\n",
- ),
- ],
-)
-def test_nonlocal_declaration_preserves_captured_values(source, captures, expected_source):
- original_captures = dict(captures)
- expected = parser.parse(expected_source)
- actual = parser.parse(source, extra_vars=captures)
- ir.assert_structural_equal(expected, actual)
- assert captures == original_captures
diff --git a/tests/scripts/task_python_unittest.sh b/tests/scripts/task_python_unittest.sh
index 6b9e7ae4d1..524a9f2a2e 100755
--- a/tests/scripts/task_python_unittest.sh
+++ b/tests/scripts/task_python_unittest.sh
@@ -24,4 +24,4 @@ export PYTEST_ADDOPTS="${CI_PYTEST_ADD_OPTIONS:-} ${PYTEST_ADDOPTS:-}"
# setup tvm-ffi into python folder
uv pip install -v --target=python ./3rdparty/tvm-ffi/
-python3 -m pytest -vvs -n auto -m "${TVM_TEST_MARKER:-not gpu}" tests/python tests/parser
+python3 -m pytest -vvs -n auto -m "${TVM_TEST_MARKER:-not gpu}" tests/python