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/10/16 20:26:02 UTC
(tvm) branch main updated: [TIRx] Simplify Python APIs and configuration discovery (#20766)
This is an automated email from the ASF dual-hosted git repository.
tqchen pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/tvm.git
The following commit(s) were added to refs/heads/main by this push:
new 7b759fb513 [TIRx] Simplify Python APIs and configuration discovery (#20766)
7b759fb513 is described below
commit 7b759fb5134328af600e1ea5a25e20afe6b30c2b
Author: Tianqi Chen <tq...@users.noreply.github.com>
AuthorDate: Fri Oct 16 16:25:56 2026 -0400
[TIRx] Simplify Python APIs and configuration discovery (#20766)
Organize TIRx's Python APIs by moving IndexMap into its own module and
LLVM helpers under `codegen.llvm`. Use the existing s_tir attribute
checks directly, remove the empty dialect backend package, and place
public operator declarations before private helpers.
Centralize configuration discovery in `libinfo.py` and share it with
package and native configuration commands. Replace legacy exception
classes with builtin exceptions while retaining FFI error messages and
subprocess cleanup. Remove the environment-probe test module and move
wheel library validation into the runtime suite with updated packaging
and CI selectors.
---
.github/actions/build-wheel-for-publish/action.yml | 2 +-
.github/workflows/main.yml | 4 +-
docs/contribute/error_handling.rst | 16 +-
docs/reference/api/python/error.rst | 23 -
docs/reference/api/python/index.rst | 1 -
python/tvm/relax/frontend/common.py | 2 +-
python/tvm/relax/frontend/onnx/onnx_frontend.py | 10 +-
.../tvm/relax/frontend/tflite/tflite_frontend.py | 546 +++++++++------------
python/tvm/relax/op/index.py | 3 +-
python/tvm/relax/op/manipulate.py | 5 +-
python/tvm/relax/op/nn/nn.py | 111 +++--
python/tvm/s_tir/__init__.py | 5 +-
python/tvm/s_tir/dlight/cpu/reduction.py | 4 +-
python/tvm/s_tir/pipeline.py | 6 +-
python/tvm/s_tir/schedule/analysis.py | 3 +-
python/tvm/s_tir/schedule/schedule.py | 4 +-
python/tvm/s_tir/schedule/trace.py | 2 +-
python/tvm/s_tir/tensor_intrin/arm_cpu.py | 4 +-
python/tvm/s_tir/tensor_intrin/riscv_cpu.py | 4 +-
.../script/test_relax_script_dynamic_shape.py | 4 +-
.../script/test_relax_script_error_handling.py | 6 +-
.../script/test_relax_script_meta_programming.py | 2 +-
tests/python/relax/test_frontend_onnx.py | 2 +-
tests/python/relax/test_frontend_tflite.py | 174 +++----
tests/python/relax/test_op_index.py | 20 +-
tests/python/relax/test_op_manipulate.py | 32 +-
tests/python/relax/test_op_nn.py | 2 +-
tests/python/relax/test_op_nn_convolution.py | 42 +-
tests/python/relax/test_op_nn_pooling.py | 54 +-
tests/python/relax/test_relax_operators.py | 2 +-
...me_builtin_paged_attention_kv_cache_metadata.py | 57 ++-
.../relax/test_tensorrt_engine_serialization.py | 14 +-
tests/python/relax/test_transform.py | 4 +-
.../relax/test_transform_error_enrichment.py | 4 +-
tests/python/relax/test_vm_build.py | 2 +-
tests/python/runtime/rpc/test_runtime_rpc.py | 4 +-
.../test_s_tir_analysis_verify_block_scope.py | 4 +-
tests/python/s_tir/base/test_tir_data_layout.py | 11 +-
.../test_meta_schedule_trace_apply.py | 4 +-
.../script/test_s_tir_script_error_handling.py | 36 +-
.../test_s_tir_transform_canonicalize_loop.py | 4 +-
.../test_s_tir_transform_mma_tensor_layout.py | 2 +-
.../transform/test_s_tir_transform_thread_sync.py | 2 +-
tests/python/te/test_te_create_function.py | 2 +-
tirx/CMakeLists.txt | 9 +-
.../__init__.py => cmake/tvm-tirx-config.in} | 10 +-
tirx/pyproject.toml | 2 +-
tirx/python/tvm_tirx/__init__.py | 28 +-
tirx/python/tvm_tirx/backend/metal/target_tags.py | 4 +-
tirx/python/tvm_tirx/codegen/__init__.py | 204 +-------
.../tvm_tirx/codegen/{__init__.py => llvm.py} | 72 +--
tirx/python/tvm_tirx/config.py | 152 +-----
tirx/python/tvm_tirx/error.py | 126 -----
tirx/python/tvm_tirx/ir/op.py | 230 ++++-----
tirx/python/tvm_tirx/libinfo.py | 149 +++++-
tirx/python/tvm_tirx/support/clang.py | 2 +-
tirx/python/tvm_tirx/support/rocm.py | 2 +-
tirx/python/tvm_tirx/testing/env.py | 8 +-
tirx/python/tvm_tirx/tirx/__init__.py | 4 +-
tirx/python/tvm_tirx/tirx/function.py | 297 +----------
.../tvm_tirx/tirx/{function.py => index_map.py} | 169 +------
tirx/python/tvm_tirx/tirx/op/__init__.py | 4 +-
tirx/python/tvm_tirx/tirx/script/ir_builder/op.py | 2 +-
.../tirx/script/ir_builder/parser_protocol.py | 2 +-
.../python/backend/metal/codegen/test_basic.py | 12 +-
.../python/backend/webgpu/codegen/test_basic.py | 20 +-
tirx/tests/python/codegen/llvm/test_aarch64.py | 36 +-
tirx/tests/python/codegen/llvm/test_basic.py | 22 +-
tirx/tests/python/codegen/llvm/test_riscv.py | 2 +-
.../python/codegen/llvm/test_scalable_vector.py | 8 +-
tirx/tests/python/codegen/llvm/test_x86.py | 2 +-
.../test_validate_wheel_library.py} | 4 +-
tirx/tests/python/script/test_basic_usage.py | 4 +-
tirx/tests/python/support/test_config.py | 11 +-
.../tests/python/target/test_llvm_features_info.py | 34 +-
tirx/tests/python/target/test_riscv_features.py | 6 +-
tirx/tests/python/target/test_x86_features.py | 8 +-
tirx/tests/python/testing/test_env.py | 332 -------------
.../tirx/analysis/test_check_well_defined.py | 24 +-
tirx/tests/python/tirx/base/test_imm_values.py | 4 +-
.../python/tirx/base/test_scalable_datatype.py | 8 +-
tirx/tests/python/tirx/codegen/test_cuda.py | 6 +-
tirx/tests/python/tirx/codegen/test_hopper.py | 2 +-
tirx/tests/python/tirx/codegen/test_ptx_addr.py | 4 +-
tirx/tests/python/tirx/codegen/test_ptx_dialect.py | 2 +-
tirx/tests/python/tirx/script/test_basic_usage.py | 8 +-
tirx/tests/python/tirx/test_cuda_backend_config.py | 2 +-
tirx/tests/python/tirx/tile/test_dispatcher.py | 2 +-
.../tests/python/tirx/transform/test_lower_tirx.py | 2 +-
.../python/tirx/transform/test_make_packed_api.py | 4 +-
.../tirx/transform/test_split_host_device.py | 2 +-
tirx/tests/python/tirx/transform/test_vectorize.py | 16 +-
92 files changed, 990 insertions(+), 2318 deletions(-)
diff --git a/.github/actions/build-wheel-for-publish/action.yml b/.github/actions/build-wheel-for-publish/action.yml
index 6333856f83..8ae6f4156a 100644
--- a/.github/actions/build-wheel-for-publish/action.yml
+++ b/.github/actions/build-wheel-for-publish/action.yml
@@ -139,7 +139,7 @@ runs:
PATH="C:/opt/llvm/Library/bin;$PATH"
CMAKE_ARGS="-DTVM_TIRX_USE_LLVM='C:/opt/llvm/Library/bin/llvm-config.exe --link-static' -DZLIB_USE_STATIC_LIBS=ON -DCMAKE_PREFIX_PATH=C:/opt/llvm/Library ${{ inputs.cmake_defines }} -DTVM_TIRX_PACKAGE_EXTRA_LIBS=${{ env.TVM_CUDA_EXTRA_LIB }}"
# Turns the wheel-specific assertions in
- # tirx/tests/python/all-platform-minimal-test/test_validate_runtime_library.py
+ # tirx/tests/python/runtime/test_validate_wheel_library.py
# ON (they skip unless these are set). Every published wheel is LLVM-enabled,
# so TVM_WHEEL_EXPECT_LLVM is always "1"; the CUDA runtime is only bundled on
# the CUDA wheels, so TVM_WHEEL_EXPECT_CUDA_RUNTIME is "0" for CPU wheels.
diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml
index 7624a81f4d..d0ad80eb3d 100644
--- a/.github/workflows/main.yml
+++ b/.github/workflows/main.yml
@@ -89,7 +89,7 @@ jobs:
shell: bash -l {0}
run: >-
python -m pytest -v tests/python/all-platform-minimal-test tests/python/script
- tirx/tests/python/all-platform-minimal-test tirx/tests/python/script
+ tirx/tests/python/runtime/test_validate_wheel_library.py tirx/tests/python/script
- name: Minimal Metal Compile-Only
shell: bash -l {0}
run: |
@@ -143,4 +143,4 @@ jobs:
shell: cmd /C call {0}
run: >-
python -m pytest -v tests/python/all-platform-minimal-test tests/python/script
- tirx/tests/python/all-platform-minimal-test tirx/tests/python/script
+ tirx/tests/python/runtime/test_validate_wheel_library.py tirx/tests/python/script
diff --git a/docs/contribute/error_handling.rst b/docs/contribute/error_handling.rst
index 8d66a6cb74..803d4ac16c 100644
--- a/docs/contribute/error_handling.rst
+++ b/docs/contribute/error_handling.rst
@@ -24,7 +24,7 @@ Error Handling Guide
:depth: 2
:local:
-TVM contains structured error classes to indicate specific types of error.
+TVM uses Python exception types to indicate specific types of error.
Please raise a specific error type when possible, so that users can
write code to handle a specific error category if necessary.
You can directly raise the specific error object in python.
@@ -33,14 +33,14 @@ the error message(see below).
.. note::
- Please refer to :py:mod:`tvm.error` for the list of errors.
+ Prefer built-in Python exceptions for common error categories.
Raise a Specific Error in C++
-----------------------------
You can add ``<ErrorType>:`` prefix to your error message to
raise an error of the corresponding type.
Note that you do not have to add a new type
-:py:class:`tvm.error.InternalError` will be raised by default when
+``RuntimeError`` will be raised by default when
there is no error type prefix in the message.
This mechanism works for both ``LOG(FATAL)`` and ``TVM_FFI_ICHECK`` macros.
The following code gives an example on how to do so.
@@ -58,10 +58,10 @@ The following code gives an example on how to do so.
When a C++ function registered via the FFI raises an error with a typed prefix,
the TVM FFI system will automatically map it to the corresponding Python exception
class. For example, a ``ValueError:`` prefix in the error message will raise a Python
-``ValueError``, and an ``InternalError:`` prefix will raise ``tvm.error.InternalError``.
+``ValueError``, and an ``InternalError:`` prefix will raise ``RuntimeError``.
TVM's FFI system combines both the Python and C++ stacktraces into a single message,
-and generates the corresponding error class automatically.
+and uses ``RuntimeError`` for error kinds without a registered Python exception.
How to choose an Error Type
@@ -72,7 +72,7 @@ We try to keep a reasonable amount of error types.
If you feel there is a need to add a new error type, do the following steps:
- Send a RFC proposal with a description and usage examples in the current codebase.
-- Add the new error type to :py:mod:`tvm.error` with clear documents.
+- Register the Python exception with ``tvm_ffi.register_error`` and document its use.
- Update the list in this file to include the new error type.
- Change the code to use the new error type.
@@ -84,10 +84,10 @@ error messages when necessary.
def preferred():
# Very clear about what is being raised and what is the error message.
- raise OpNotImplemented("Operator relu is not implemented in the ONNX frontend")
+ raise NotImplementedError("Operator relu is not implemented in the ONNX frontend")
def _op_not_implemented(op_name):
- return OpNotImplemented("Operator {} is not implemented.").format(op_name)
+ return NotImplementedError("Operator {} is not implemented.").format(op_name)
def not_preferred():
# Introduces another level of indirection.
diff --git a/docs/reference/api/python/error.rst b/docs/reference/api/python/error.rst
deleted file mode 100644
index 297e430093..0000000000
--- a/docs/reference/api/python/error.rst
+++ /dev/null
@@ -1,23 +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.
-
-tvm_tirx.error
---------------
-.. automodule:: tvm_tirx.error
- :members:
- :imported-members:
- :autosummary:
diff --git a/docs/reference/api/python/index.rst b/docs/reference/api/python/index.rst
index 9338b21ee1..7c71735ef2 100644
--- a/docs/reference/api/python/index.rst
+++ b/docs/reference/api/python/index.rst
@@ -22,7 +22,6 @@ Python API
:maxdepth: 1
:caption: tvm
- error
ir
sym
instrument
diff --git a/python/tvm/relax/frontend/common.py b/python/tvm/relax/frontend/common.py
index 147baacbfd..baa4c03361 100644
--- a/python/tvm/relax/frontend/common.py
+++ b/python/tvm/relax/frontend/common.py
@@ -114,7 +114,7 @@ def autopad(
pad = _np.concatenate([_np.zeros([2, 2], dtype="int64"), pad], axis=0)
if pad_type not in ["constant", "edge", "reflect"]:
- raise tvm_tirx.error.OpAttributeInvalid(
+ raise AttributeError(
"Value " + pad_type + ' in attribute "mode" is invalid for operator Pad.'
)
diff --git a/python/tvm/relax/frontend/onnx/onnx_frontend.py b/python/tvm/relax/frontend/onnx/onnx_frontend.py
index f94e994cd7..3c89d51167 100644
--- a/python/tvm/relax/frontend/onnx/onnx_frontend.py
+++ b/python/tvm/relax/frontend/onnx/onnx_frontend.py
@@ -2205,7 +2205,7 @@ class Conv(OnnxOpConverter):
msg = (
f'Value {attr["auto_pad"]} in attribute "auto_pad" of operator Conv is invalid.'
)
- raise tvm_tirx.error.OpAttributeInvalid(msg)
+ raise AttributeError(msg)
attr.pop("auto_pad")
conv_out = bb.normalize(
@@ -2295,7 +2295,7 @@ class ConvTranspose(OnnxOpConverter):
elif auto_pad == "NOTSET":
pass
else:
- raise tvm_tirx.error.OpAttributeInvalid(
+ raise AttributeError(
f'Value {auto_pad} in attribute "auto_pad" of operator '
"ConvTranspose is invalid."
)
@@ -3299,7 +3299,7 @@ class Pad(OnnxOpConverter):
pad_mode = attr.get("mode", b"constant").decode("utf-8")
if pad_mode not in ["constant", "edge", "reflect"]:
- raise tvm_tirx.error.OpAttributeInvalid(
+ raise AttributeError(
"Value " + pad_mode + ' in attribute "mode" is invalid for operator Pad.'
)
@@ -3364,7 +3364,7 @@ class Pad(OnnxOpConverter):
pad_before, pad_after, constant_value = cls._parse_pads_and_axes(inputs, params)
pad_mode = attr.get("mode", b"constant").decode("utf-8")
if pad_mode not in allowed_modes:
- raise tvm_tirx.error.OpAttributeInvalid(
+ raise AttributeError(
"Value " + pad_mode + ' in attribute "mode" is invalid for operator Pad.'
)
@@ -6487,7 +6487,7 @@ class ONNXGraphImporter:
if unsupported_ops:
msg = "The following operators are not supported for frontend ONNX: "
msg += ", ".join(unsupported_ops)
- raise tvm_tirx.error.OpNotImplemented(msg)
+ raise NotImplementedError(msg)
def _construct_nodes(self, graph: onnx.onnx_ml_pb2.GraphProto):
"""Nodes are stored as directed acyclic graph."""
diff --git a/python/tvm/relax/frontend/tflite/tflite_frontend.py b/python/tvm/relax/frontend/tflite/tflite_frontend.py
index 9e389620ea..a3c9a2eb01 100644
--- a/python/tvm/relax/frontend/tflite/tflite_frontend.py
+++ b/python/tvm/relax/frontend/tflite/tflite_frontend.py
@@ -503,11 +503,11 @@ class OperatorConverter:
)
if len(raise_msg) > 0:
- raise tvm_tirx.error.OpNotImplemented(raise_msg)
+ raise NotImplementedError(raise_msg)
def convert_operator_marker(self, op, op_name):
"""Reject TFLite marker builtins with an explicit diagnostic."""
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
f"TFLite operator marker {op_name} is not a Relax tensor operator"
)
@@ -605,12 +605,12 @@ class OperatorConverter:
return (container, shared_name)
if fallback_tensor is not None:
return ("", get_tensor_name(self.subgraph, fallback_tensor.tensor_idx))
- raise tvm_tirx.error.OpNotImplemented("VAR_HANDLE requires VarHandleOptions")
+ raise NotImplementedError("VAR_HANDLE requires VarHandleOptions")
def _get_resource_key_for_handle(self, tensor, op_name):
tensor_name = get_tensor_name(self.subgraph, tensor.tensor_idx)
if tensor_name not in self.resource_handles:
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
f"{op_name} requires a VAR_HANDLE in the same TFLite subgraph"
)
return self.resource_handles[tensor_name]
@@ -620,7 +620,7 @@ class OperatorConverter:
input_tensors = self.get_input_tensors(op)
output_tensors = self.get_output_tensors(op)
if len(input_tensors) != 0 or len(output_tensors) != 1:
- raise tvm_tirx.error.OpNotImplemented("VAR_HANDLE expects no inputs and one output")
+ raise NotImplementedError("VAR_HANDLE expects no inputs and one output")
resource_key = self._get_var_handle_resource_key(op, output_tensors[0])
resource_tensor_name = get_tensor_name(self.subgraph, output_tensors[0].tensor_idx)
@@ -630,7 +630,7 @@ class OperatorConverter:
def convert_assign_variable(self, op):
"""Convert the CALL_ONCE initialization subset of ASSIGN_VARIABLE."""
if not self.conversion_state["in_call_once_init"]:
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
"ASSIGN_VARIABLE outside CALL_ONCE initialization is not supported by the "
"Relax TFLite frontend yet because it requires mutable resource state modeling."
)
@@ -638,7 +638,7 @@ class OperatorConverter:
input_tensors = self.get_input_tensors(op)
output_tensors = self.get_output_tensors(op)
if len(input_tensors) != 2 or len(output_tensors) != 0:
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
"ASSIGN_VARIABLE expects a resource handle and value input with no outputs"
)
@@ -653,12 +653,12 @@ class OperatorConverter:
input_tensors = self.get_input_tensors(op)
output_tensors = self.get_output_tensors(op)
if len(input_tensors) != 1 or len(output_tensors) != 1:
- raise tvm_tirx.error.OpNotImplemented("READ_VARIABLE expects one input and one output")
+ raise NotImplementedError("READ_VARIABLE expects one input and one output")
resource_key = self._get_resource_key_for_handle(input_tensors[0], "READ_VARIABLE")
resource_values = self.conversion_state["resource_values"]
if resource_key not in resource_values:
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
"READ_VARIABLE requires a resource initialized by a supported CALL_ONCE subgraph"
)
return resource_values[resource_key]
@@ -692,9 +692,9 @@ class OperatorConverter:
pass
if key_dtype is None or value_dtype is None:
- raise tvm_tirx.error.OpNotImplemented("HASHTABLE requires HashtableOptions")
+ raise NotImplementedError("HASHTABLE requires HashtableOptions")
if not self._is_supported_hashtable_type_pair(key_dtype, value_dtype):
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
"TFLite HASHTABLE only supports int64/string or string/int64 tables"
)
@@ -706,14 +706,12 @@ class OperatorConverter:
key_dtype,
value_dtype,
)
- raise tvm_tirx.error.OpNotImplemented("HASHTABLE requires HashtableOptions")
+ raise NotImplementedError("HASHTABLE requires HashtableOptions")
def _get_hashtable_info_for_handle(self, tensor, op_name):
tensor_name = get_tensor_name(self.subgraph, tensor.tensor_idx)
if tensor_name not in self.hashtable_handles:
- raise tvm_tirx.error.OpNotImplemented(
- f"{op_name} requires a HASHTABLE in the same TFLite subgraph"
- )
+ raise NotImplementedError(f"{op_name} requires a HASHTABLE in the same TFLite subgraph")
return self.hashtable_handles[tensor_name]
@staticmethod
@@ -733,44 +731,38 @@ class OperatorConverter:
def _get_string_tensor_value(self, tensor_wrapper, op_name):
"""Decode a constant TFLite string tensor buffer."""
if not self._is_tflite_string_type(tensor_wrapper.tensor.Type()):
- raise tvm_tirx.error.OpNotImplemented(f"{op_name} requires a TensorType.STRING tensor")
+ raise NotImplementedError(f"{op_name} requires a TensorType.STRING tensor")
if not self._has_tensor_buffer_data(tensor_wrapper):
- raise tvm_tirx.error.OpNotImplemented(f"{op_name} requires a constant string tensor")
+ raise NotImplementedError(f"{op_name} requires a constant string tensor")
data = bytes(tensor_wrapper.buffer.DataAsNumpy())
if len(data) < 4:
- raise tvm_tirx.error.OpNotImplemented(f"{op_name} has an invalid string tensor buffer")
+ raise NotImplementedError(f"{op_name} has an invalid string tensor buffer")
count = int(np.frombuffer(data, dtype="<i4", count=1)[0])
if count < 0:
- raise tvm_tirx.error.OpNotImplemented(f"{op_name} has an invalid string tensor count")
+ raise NotImplementedError(f"{op_name} has an invalid string tensor count")
header_size = 4 * (count + 2)
if len(data) < header_size:
- raise tvm_tirx.error.OpNotImplemented(f"{op_name} has an invalid string tensor offsets")
+ raise NotImplementedError(f"{op_name} has an invalid string tensor offsets")
offsets = np.frombuffer(data, dtype="<i4", count=count + 1, offset=4).astype(np.int64)
if np.any(offsets < header_size) or np.any(offsets > len(data)):
- raise tvm_tirx.error.OpNotImplemented(
- f"{op_name} has out-of-bounds string tensor offsets"
- )
+ raise NotImplementedError(f"{op_name} has out-of-bounds string tensor offsets")
if np.any(offsets[:-1] > offsets[1:]):
- raise tvm_tirx.error.OpNotImplemented(
- f"{op_name} has non-monotonic string tensor offsets"
- )
+ raise NotImplementedError(f"{op_name} has non-monotonic string tensor offsets")
try:
values = [
data[int(offsets[i]) : int(offsets[i + 1])].decode("utf-8") for i in range(count)
]
except UnicodeDecodeError as e:
- raise tvm_tirx.error.OpNotImplemented(
- f"{op_name} has invalid UTF-8 string data: {e}"
- ) from e
+ raise NotImplementedError(f"{op_name} has invalid UTF-8 string data: {e}") from e
shape = self._get_tensor_shape_tuple(tensor_wrapper)
expected_count = math.prod(shape) if shape else 1
if expected_count != count:
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
f"{op_name} string tensor buffer count does not match its shape"
)
return np.array(values, dtype=object).reshape(shape)
@@ -780,7 +772,7 @@ class OperatorConverter:
input_tensors = self.get_input_tensors(op)
output_tensors = self.get_output_tensors(op)
if len(input_tensors) != 0 or len(output_tensors) != 1:
- raise tvm_tirx.error.OpNotImplemented("HASHTABLE expects no inputs and one output")
+ raise NotImplementedError("HASHTABLE expects no inputs and one output")
table_key, key_dtype, value_dtype = self._get_hashtable_key(op, output_tensors[0])
table_tensor_name = get_tensor_name(self.subgraph, output_tensors[0].tensor_idx)
@@ -794,7 +786,7 @@ class OperatorConverter:
def convert_hashtable_import(self, op):
"""Convert static metadata for the CALL_ONCE HASHTABLE_IMPORT subset."""
if not self.conversion_state["in_call_once_init"]:
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
"HASHTABLE_IMPORT outside CALL_ONCE initialization is not supported by the "
"Relax TFLite frontend yet because it requires mutable resource state modeling."
)
@@ -802,7 +794,7 @@ class OperatorConverter:
input_tensors = self.get_input_tensors(op)
output_tensors = self.get_output_tensors(op)
if len(input_tensors) != 3 or len(output_tensors) != 0:
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
"HASHTABLE_IMPORT expects table, keys, and values inputs with no outputs"
)
@@ -813,19 +805,15 @@ class OperatorConverter:
key_tensor.tensor.Type() != table_info["key_dtype"]
or value_tensor.tensor.Type() != table_info["value_dtype"]
):
- raise tvm_tirx.error.OpNotImplemented("HASHTABLE_IMPORT key/value dtypes mismatch")
+ raise NotImplementedError("HASHTABLE_IMPORT key/value dtypes mismatch")
key_shape = self._get_tensor_shape_tuple(key_tensor)
value_shape = self._get_tensor_shape_tuple(value_tensor)
if key_shape != value_shape:
- raise tvm_tirx.error.OpNotImplemented(
- "HASHTABLE_IMPORT requires keys and values same shape"
- )
+ raise NotImplementedError("HASHTABLE_IMPORT requires keys and values same shape")
if not self._has_tensor_buffer_data(key_tensor) or not self._has_tensor_buffer_data(
value_tensor
):
- raise tvm_tirx.error.OpNotImplemented(
- "HASHTABLE_IMPORT requires constant keys and values"
- )
+ raise NotImplementedError("HASHTABLE_IMPORT requires constant keys and values")
if self._is_tflite_string_type(table_info["key_dtype"]):
keys = self._get_string_tensor_value(key_tensor, "HASHTABLE_IMPORT")
@@ -837,9 +825,7 @@ class OperatorConverter:
values = self.get_tensor_value(value_tensor)
if np.unique(keys).size != keys.size:
- raise tvm_tirx.error.OpNotImplemented(
- "HASHTABLE_IMPORT with duplicate keys is not supported"
- )
+ raise NotImplementedError("HASHTABLE_IMPORT with duplicate keys is not supported")
hashtable_values = self.conversion_state["hashtable_values"]
table_key = table_info["table_key"]
@@ -860,7 +846,7 @@ class OperatorConverter:
input_tensors = self.get_input_tensors(op)
output_tensors = self.get_output_tensors(op)
if len(input_tensors) != 3 or len(output_tensors) != 1:
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
"HASHTABLE_FIND expects table, query, and default inputs with one output"
)
@@ -870,7 +856,7 @@ class OperatorConverter:
table_key = table_info["table_key"]
hashtable_values = self.conversion_state["hashtable_values"]
if table_key not in hashtable_values:
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
"HASHTABLE_FIND requires a table initialized by a supported CALL_ONCE subgraph"
)
table_values = hashtable_values[table_key]
@@ -880,28 +866,24 @@ class OperatorConverter:
or default_tensor.tensor.Type() != table_values["value_dtype"]
or output_tensor.tensor.Type() != table_values["value_dtype"]
):
- raise tvm_tirx.error.OpNotImplemented("HASHTABLE_FIND key/value dtypes mismatch")
+ raise NotImplementedError("HASHTABLE_FIND key/value dtypes mismatch")
if not (
self._is_tflite_string_type(table_values["key_dtype"])
and table_values["value_dtype"] == TensorType.INT64
):
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
"HASHTABLE_FIND only supports constant string -> int64 tables"
)
if not self._has_tensor_buffer_data(query_tensor):
- raise tvm_tirx.error.OpNotImplemented(
- "HASHTABLE_FIND with runtime string queries is not supported"
- )
+ raise NotImplementedError("HASHTABLE_FIND with runtime string queries is not supported")
if not self._has_tensor_buffer_data(default_tensor):
- raise tvm_tirx.error.OpNotImplemented("HASHTABLE_FIND requires constant default values")
+ raise NotImplementedError("HASHTABLE_FIND requires constant default values")
query_shape = self._get_tensor_shape_tuple(query_tensor)
output_shape = self._get_tensor_shape_tuple(output_tensor)
if output_shape != query_shape:
- raise tvm_tirx.error.OpNotImplemented(
- "HASHTABLE_FIND output shape must match query shape"
- )
+ raise NotImplementedError("HASHTABLE_FIND output shape must match query shape")
query_values = self._get_string_tensor_value(query_tensor, "HASHTABLE_FIND")
default_values = self.get_tensor_value(default_tensor)
@@ -911,7 +893,7 @@ class OperatorConverter:
elif default_shape == query_shape:
result = default_values.astype(np.int64).copy()
else:
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
"HASHTABLE_FIND default value must be scalar or match query shape"
)
@@ -933,7 +915,7 @@ class OperatorConverter:
input_tensors = self.get_input_tensors(op)
output_tensors = self.get_output_tensors(op)
if len(input_tensors) != 3 or len(output_tensors) != 2:
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
"HASHTABLE_LOOKUP expects lookup, key, and value inputs with two outputs"
)
@@ -944,19 +926,17 @@ class OperatorConverter:
lookup_tensor.tensor.Type() != TensorType.INT32
or key_tensor.tensor.Type() != TensorType.INT32
):
- raise tvm_tirx.error.OpNotImplemented(
- "HASHTABLE_LOOKUP requires int32 lookup and key tensors"
- )
+ raise NotImplementedError("HASHTABLE_LOOKUP requires int32 lookup and key tensors")
if self._is_tflite_string_type(value_tensor.tensor.Type()):
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
"HASHTABLE_LOOKUP with TensorType.STRING values is not supported"
)
if value_tensor.tensor.Type() != output_tensor.tensor.Type():
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
"HASHTABLE_LOOKUP output dtype must match the value tensor dtype"
)
if hits_tensor.tensor.Type() != TensorType.UINT8:
- raise tvm_tirx.error.OpNotImplemented("HASHTABLE_LOOKUP hits output must be uint8")
+ raise NotImplementedError("HASHTABLE_LOOKUP hits output must be uint8")
lookup_shape = to_int_list(self.get_tensor_shape(lookup_tensor))
key_shape = to_int_list(self.get_tensor_shape(key_tensor))
@@ -965,25 +945,21 @@ class OperatorConverter:
hits_shape = to_int_list(self.get_tensor_shape(hits_tensor))
if len(lookup_shape) != 1 or len(key_shape) != 1 or len(value_shape) < 1:
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
"HASHTABLE_LOOKUP requires rank-1 lookup/key and rank>=1 value tensors"
)
if key_shape[0] != value_shape[0]:
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
"HASHTABLE_LOOKUP requires key and value tensors to agree on row count"
)
if key_shape[0] == 0:
- raise tvm_tirx.error.OpNotImplemented(
- "HASHTABLE_LOOKUP requires a non-empty key/value table"
- )
+ raise NotImplementedError("HASHTABLE_LOOKUP requires a non-empty key/value table")
if output_shape != [lookup_shape[0]] + value_shape[1:]:
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
"HASHTABLE_LOOKUP output shape must match lookup count and value tail shape"
)
if hits_shape != [lookup_shape[0]]:
- raise tvm_tirx.error.OpNotImplemented(
- "HASHTABLE_LOOKUP hits output shape must match lookup count"
- )
+ raise NotImplementedError("HASHTABLE_LOOKUP hits output shape must match lookup count")
lookup = self.get_tensor_expr(lookup_tensor)
key = self.get_tensor_expr(key_tensor)
@@ -1013,17 +989,17 @@ class OperatorConverter:
input_tensors = self.get_input_tensors(op)
output_tensors = self.get_output_tensors(op)
if len(input_tensors) != 1 or len(output_tensors) != 1:
- raise tvm_tirx.error.OpNotImplemented("HASHTABLE_SIZE expects one input and one output")
+ raise NotImplementedError("HASHTABLE_SIZE expects one input and one output")
from tflite.TensorType import TensorType
if output_tensors[0].tensor.Type() != TensorType.INT64:
- raise tvm_tirx.error.OpNotImplemented("HASHTABLE_SIZE output must be int64")
+ raise NotImplementedError("HASHTABLE_SIZE output must be int64")
table_info = self._get_hashtable_info_for_handle(input_tensors[0], "HASHTABLE_SIZE")
table_key = table_info["table_key"]
hashtable_values = self.conversion_state["hashtable_values"]
if table_key not in hashtable_values:
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
"HASHTABLE_SIZE requires a table initialized by a supported CALL_ONCE subgraph"
)
return relax.const(np.array([hashtable_values[table_key]["size"]], dtype=np.int64), "int64")
@@ -1125,7 +1101,7 @@ class OperatorConverter:
# Ensure that all zero points are zeros
zero_point = tflite_zero_point
if not np.all(zero_point == 0):
- raise tvm_tirx.error.OpAttributeInvalid(
+ raise AttributeError(
"TFLite per-axis quantization restricts all zero points to be"
+ " 0, but a non-zero value is observed"
)
@@ -1360,7 +1336,7 @@ class OperatorConverter:
return relax.op.clip(expr, min=max(qmin, quantize(0.0)), max=qmax)
fused_activation_fn_str = self.activation_fn_type[fused_activation_fn]
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
f"Quantized activation {fused_activation_fn_str} is not supported yet."
)
@@ -1538,7 +1514,7 @@ class OperatorConverter:
input_tensor_rank = len(input_tensor.tensor.ShapeAsNumpy())
if self.is_quantized(op):
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
"TFLite quantized L2_NORMALIZATION operator is not supported yet."
)
@@ -1552,7 +1528,7 @@ class OperatorConverter:
# if we have fused activation fn
if output_tensor.qnn_params:
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
"TFLite quantized L2_NORMALIZATION operator is not supported yet."
)
out = self.convert_fused_activation_function(out, fused_activation_fn)
@@ -1566,9 +1542,7 @@ class OperatorConverter:
from tflite.LocalResponseNormalizationOptions import LocalResponseNormalizationOptions
if self.is_quantized(op):
- raise tvm_tirx.error.OpNotImplemented(
- "TFlite quantized LRN operator is not supported yet."
- )
+ raise NotImplementedError("TFlite quantized LRN operator is not supported yet.")
input_tensors = self.get_input_tensors(op)
assert len(input_tensors) == 1, "input tensors length should be 1"
@@ -2110,9 +2084,7 @@ class OperatorConverter:
elif dtype.startswith(("int", "uint")):
op_fn = _op.bitwise_and
else:
- raise tvm_tirx.error.OpNotImplemented(
- f"STABLEHLO_AND with dtype {dtype} is not supported"
- )
+ raise NotImplementedError(f"STABLEHLO_AND with dtype {dtype} is not supported")
return self.bb.normalize(op_fn(lhs, rhs))
def _convert_stablehlo_or(self, op):
@@ -2130,9 +2102,7 @@ class OperatorConverter:
elif dtype.startswith(("int", "uint")):
op_fn = _op.bitwise_or
else:
- raise tvm_tirx.error.OpNotImplemented(
- f"STABLEHLO_OR with dtype {dtype} is not supported"
- )
+ raise NotImplementedError(f"STABLEHLO_OR with dtype {dtype} is not supported")
return self.bb.normalize(op_fn(lhs, rhs))
def _convert_stablehlo_ternary(self, op, relax_op):
@@ -2164,7 +2134,7 @@ class OperatorConverter:
# A malformed flatbuffer may declare a BuiltinOptions2 type without
# carrying the actual options table. Fail cleanly instead of raising
# an opaque AttributeError when accessing the missing payload.
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
f"{options_cls.__name__} is required but missing from the operator"
)
# Look up the expected BuiltinOptions2 enum value by matching the class
@@ -2184,9 +2154,7 @@ class OperatorConverter:
try:
return [int(dim) for dim in self.get_tensor_shape(tensor)]
except (TypeError, ValueError) as err:
- raise tvm_tirx.error.OpNotImplemented(
- f"{op_name} requires statically-known tensor shapes"
- ) from err
+ raise NotImplementedError(f"{op_name} requires statically-known tensor shapes") from err
def _get_stablehlo_i64_vector(self, vector, default):
"""Convert an optional StableHLO int64 vector field to a Python int list."""
@@ -2198,7 +2166,7 @@ class OperatorConverter:
"""Return expr dtype if the StableHLO subset supports it."""
dtype = expr.ty.dtype.dtype
if not dtype.startswith("float"):
- raise tvm_tirx.error.OpNotImplemented(f"{op_name} with dtype {dtype} is not supported")
+ raise NotImplementedError(f"{op_name} with dtype {dtype} is not supported")
return dtype
def _convert_stablehlo_cbrt(self, op):
@@ -2238,9 +2206,7 @@ class OperatorConverter:
def _get_stablehlo_simple_body_op(self, body_subgraph_index, parent_op_name, input_count):
"""Return the single operator from a simple StableHLO body subgraph."""
if body_subgraph_index <= 0 or body_subgraph_index >= self.model.SubgraphsLength():
- raise tvm_tirx.error.OpNotImplemented(
- f"{parent_op_name} requires a valid non-main body subgraph"
- )
+ raise NotImplementedError(f"{parent_op_name} requires a valid non-main body subgraph")
body_subgraph = self.model.Subgraphs(body_subgraph_index)
if (
@@ -2248,9 +2214,7 @@ class OperatorConverter:
or body_subgraph.OutputsLength() != 1
or body_subgraph.OperatorsLength() != 1
):
- raise tvm_tirx.error.OpNotImplemented(
- f"{parent_op_name} only supports single-op body subgraphs"
- )
+ raise NotImplementedError(f"{parent_op_name} only supports single-op body subgraphs")
return body_subgraph.Operators(0)
@@ -2259,13 +2223,11 @@ class OperatorConverter:
):
"""Validate that the StableHLO reduce init value matches the Relax identity."""
if self.has_expr(init_tensor.tensor_idx):
- raise tvm_tirx.error.OpNotImplemented(
- f"{parent_op_name} with dynamic init values is not supported"
- )
+ raise NotImplementedError(f"{parent_op_name} with dynamic init values is not supported")
init_value = np.asarray(self.get_tensor_value(init_tensor))
if init_value.shape not in [(), (1,)]:
- raise tvm_tirx.error.OpNotImplemented(f"{parent_op_name} requires scalar init values")
+ raise NotImplementedError(f"{parent_op_name} requires scalar init values")
dtype = init_value.dtype
scalar = init_value.item()
@@ -2288,12 +2250,10 @@ class OperatorConverter:
else:
is_identity = False
else:
- raise tvm_tirx.error.OpNotImplemented(
- f"{parent_op_name} reducer {reducer_name} is not supported"
- )
+ raise NotImplementedError(f"{parent_op_name} reducer {reducer_name} is not supported")
if not is_identity:
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
f"{parent_op_name} init value must match the reducer identity"
)
@@ -2319,9 +2279,7 @@ class OperatorConverter:
"STABLEHLO_MULTIPLY": relax.op.prod,
}
if reducer_name not in reducers:
- raise tvm_tirx.error.OpNotImplemented(
- f"STABLEHLO_REDUCE reducer {reducer_name} is not supported"
- )
+ raise NotImplementedError(f"STABLEHLO_REDUCE reducer {reducer_name} is not supported")
self._check_stablehlo_reduce_init(input_tensors[1], reducer_name)
data = self.get_tensor_expr(input_tensors[0])
@@ -2341,14 +2299,14 @@ class OperatorConverter:
)
reducer_name = self.get_op_code_str(body_op)
if reducer_name != "STABLEHLO_MAXIMUM":
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
"STABLEHLO_REDUCE_WINDOW only supports MAXIMUM reducer windows"
)
self._check_stablehlo_reduce_init(input_tensors[1], reducer_name, "STABLEHLO_REDUCE_WINDOW")
data_shape = self._get_static_tensor_shape(input_tensors[0], "STABLEHLO_REDUCE_WINDOW")
if len(data_shape) != 4:
- raise tvm_tirx.error.OpNotImplemented("STABLEHLO_REDUCE_WINDOW only supports 4D input")
+ raise NotImplementedError("STABLEHLO_REDUCE_WINDOW only supports 4D input")
window_dimensions = self._get_stablehlo_i64_vector(opts.WindowDimensionsAsNumpy(), [])
window_strides = self._get_stablehlo_i64_vector(
@@ -2371,25 +2329,21 @@ class OperatorConverter:
or len(window_dilations) != 4
or len(padding) != 8
):
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
"STABLEHLO_REDUCE_WINDOW only supports rank-4 window attributes"
)
if window_dimensions[0] != 1 or window_dimensions[3] != 1:
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
"STABLEHLO_REDUCE_WINDOW only supports pooling over spatial dimensions"
)
if window_strides[0] != 1 or window_strides[3] != 1:
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
"STABLEHLO_REDUCE_WINDOW only supports unit batch/channel strides"
)
if base_dilations != [1, 1, 1, 1]:
- raise tvm_tirx.error.OpNotImplemented(
- "STABLEHLO_REDUCE_WINDOW with base dilation is not supported"
- )
+ raise NotImplementedError("STABLEHLO_REDUCE_WINDOW with base dilation is not supported")
if padding[0] != 0 or padding[1] != 0 or padding[6] != 0 or padding[7] != 0:
- raise tvm_tirx.error.OpNotImplemented(
- "STABLEHLO_REDUCE_WINDOW only supports spatial padding"
- )
+ raise NotImplementedError("STABLEHLO_REDUCE_WINDOW only supports spatial padding")
data = self.get_tensor_expr(input_tensors[0])
return self.bb.normalize(
@@ -2427,23 +2381,23 @@ class OperatorConverter:
index_vector_dim = int(opts.IndexVectorDim())
if indices_rank == 0 or index_vector_dim != indices_rank - 1:
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
"STABLEHLO_SCATTER only supports trailing index-vector dimensions"
)
if update_window_dims:
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
"STABLEHLO_SCATTER only supports point updates without update windows"
)
if inserted_window_dims != list(range(operand_rank)):
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
"STABLEHLO_SCATTER only supports point updates for every operand dimension"
)
if scatter_dims_to_operand_dims != list(range(operand_rank)):
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
"STABLEHLO_SCATTER only supports canonical scatter-to-operand dimensions"
)
if indices_shape[-1] != operand_rank or updates_shape != indices_shape[:-1]:
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
"STABLEHLO_SCATTER requires point update shapes to match scatter indices"
)
@@ -2458,9 +2412,7 @@ class OperatorConverter:
"STABLEHLO_MULTIPLY": "mul",
}
if reducer_name not in reductions:
- raise tvm_tirx.error.OpNotImplemented(
- f"STABLEHLO_SCATTER reducer {reducer_name} is not supported"
- )
+ raise NotImplementedError(f"STABLEHLO_SCATTER reducer {reducer_name} is not supported")
operand = self.get_tensor_expr(input_tensors[0])
indices = self.get_tensor_expr(input_tensors[1])
@@ -2476,7 +2428,7 @@ class OperatorConverter:
input_tensors = self.get_input_tensors(op)
output_tensors = self.get_output_tensors(op)
if len(output_tensors) != 1:
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
"STABLEHLO_COMPOSITE only supports single-output decompositions"
)
@@ -2486,7 +2438,7 @@ class OperatorConverter:
composite_name.decode("utf-8") if composite_name is not None else "<unnamed>"
)
if opts.CompositeAttributesLength() != 0:
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
f"STABLEHLO_COMPOSITE {composite_name} with composite attributes is not supported"
)
@@ -2495,16 +2447,16 @@ class OperatorConverter:
decomposition_subgraph_index <= 0
or decomposition_subgraph_index >= self.model.SubgraphsLength()
):
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
f"STABLEHLO_COMPOSITE {composite_name} requires a valid decomposition subgraph"
)
decomposition_subgraph = self.model.Subgraphs(decomposition_subgraph_index)
if decomposition_subgraph.InputsLength() != len(input_tensors):
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
f"STABLEHLO_COMPOSITE {composite_name} decomposition input count mismatch"
)
if decomposition_subgraph.OutputsLength() != 1:
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
f"STABLEHLO_COMPOSITE {composite_name} only supports single-output decompositions"
)
@@ -2546,20 +2498,20 @@ class OperatorConverter:
input_tensors = self.get_input_tensors(op)
output_tensors = self.get_output_tensors(op)
if len(input_tensors) != 1 or len(output_tensors) != 1:
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
"STABLEHLO_SORT only supports single-input single-output sort"
)
opts = self._get_stablehlo_options(op, StablehloSortOptions)
if opts.IsStable():
- raise tvm_tirx.error.OpNotImplemented("STABLEHLO_SORT stable sort is not supported")
+ raise NotImplementedError("STABLEHLO_SORT stable sort is not supported")
body_op = self._get_stablehlo_simple_body_op(
int(opts.ComparatorSubgraphIndex()), "STABLEHLO_SORT", 2
)
comparator_name = self.get_op_code_str(body_op)
if comparator_name != "STABLEHLO_COMPARE":
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
f"STABLEHLO_SORT comparator {comparator_name} is not supported"
)
@@ -2568,9 +2520,7 @@ class OperatorConverter:
compare_opts.CompareType()
== StablehloComparisonType.STABLEHLO_COMPARISON_TYPE_FLOAT_TOTAL_ORDER
):
- raise tvm_tirx.error.OpNotImplemented(
- "STABLEHLO_SORT with TOTALORDER comparator is not supported"
- )
+ raise NotImplementedError("STABLEHLO_SORT with TOTALORDER comparator is not supported")
direction = compare_opts.ComparisonDirection()
_DIR = StablehloComparisonDirection
@@ -2579,9 +2529,7 @@ class OperatorConverter:
elif direction == _DIR.STABLEHLO_COMPARISON_DIRECTION_GT:
descending = True
else:
- raise tvm_tirx.error.OpNotImplemented(
- "STABLEHLO_SORT only supports LT or GT comparators"
- )
+ raise NotImplementedError("STABLEHLO_SORT only supports LT or GT comparators")
data = self.get_tensor_expr(input_tensors[0])
return self.bb.normalize(
@@ -2605,15 +2553,15 @@ class OperatorConverter:
# dropped for single-device import. TFLite has no runtime kernel
# for general STABLEHLO_CUSTOM_CALL targets.
if opts.HasSideEffect():
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
"STABLEHLO_CUSTOM_CALL Sharding with side effects is not supported"
)
if opts.CalledComputationsLength() != 0:
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
"STABLEHLO_CUSTOM_CALL Sharding with called computations is not supported"
)
if len(input_tensors) != 1 or len(output_tensors) != 1:
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
"STABLEHLO_CUSTOM_CALL Sharding requires one input and one output"
)
self._check_tensor_metadata_match(
@@ -2622,9 +2570,7 @@ class OperatorConverter:
return self.get_tensor_expr(input_tensors[0])
target = call_target_name or "<empty>"
- raise tvm_tirx.error.OpNotImplemented(
- f"STABLEHLO_CUSTOM_CALL target {target} is not supported"
- )
+ raise NotImplementedError(f"STABLEHLO_CUSTOM_CALL target {target} is not supported")
def _convert_stablehlo_rng_bit_generator(self, op):
"""Convert STABLEHLO_RNG_BIT_GENERATOR to a bit-exact call_tir kernel."""
@@ -2635,7 +2581,7 @@ class OperatorConverter:
input_tensors = self.get_input_tensors(op)
output_tensors = self.get_output_tensors(op)
if len(input_tensors) != 1 or len(output_tensors) != 2:
- raise tvm_tirx.error.OpNotImplemented(f"{op_name} expects one input and two outputs")
+ raise NotImplementedError(f"{op_name} expects one input and two outputs")
opts = self._get_stablehlo_options(op, StablehloRngBitGeneratorOptions)
algorithm_enum = opts.Algorithm()
@@ -2645,38 +2591,30 @@ class OperatorConverter:
elif algorithm_enum in (RngAlgorithm.PHILOX, RngAlgorithm.DEFAULT):
algorithm = "philox"
else:
- raise tvm_tirx.error.OpNotImplemented(
- f"{op_name} algorithm {algorithm_enum} is not supported"
- )
+ raise NotImplementedError(f"{op_name} algorithm {algorithm_enum} is not supported")
state_tensor = input_tensors[0]
if self.get_tensor_type_str(state_tensor.tensor.Type()) != "uint64":
- raise tvm_tirx.error.OpNotImplemented(f"{op_name} requires a uint64 initial state")
+ raise NotImplementedError(f"{op_name} requires a uint64 initial state")
state_shape = self._get_static_tensor_shape(state_tensor, op_name)
if len(state_shape) != 1:
- raise tvm_tirx.error.OpNotImplemented(f"{op_name} requires a 1-D initial state")
+ raise NotImplementedError(f"{op_name} requires a 1-D initial state")
state_len = int(state_shape[0])
# State-length constraints mirror the TFLite runtime kernel.
if algorithm == "threefry" and state_len != 2:
- raise tvm_tirx.error.OpNotImplemented(f"{op_name} THREEFRY requires a u64[2] state")
+ raise NotImplementedError(f"{op_name} THREEFRY requires a u64[2] state")
if algorithm == "philox" and state_len not in (2, 3):
- raise tvm_tirx.error.OpNotImplemented(
- f"{op_name} PHILOX requires a u64[2] or u64[3] state"
- )
+ raise NotImplementedError(f"{op_name} PHILOX requires a u64[2] or u64[3] state")
out_state_tensor, out_tensor = output_tensors
if self.get_tensor_type_str(out_state_tensor.tensor.Type()) != "uint64":
- raise tvm_tirx.error.OpNotImplemented(f"{op_name} output state must be uint64")
+ raise NotImplementedError(f"{op_name} output state must be uint64")
out_state_shape = self._get_static_tensor_shape(out_state_tensor, op_name)
if list(out_state_shape) != list(state_shape):
- raise tvm_tirx.error.OpNotImplemented(
- f"{op_name} output state shape must match the initial state"
- )
+ raise NotImplementedError(f"{op_name} output state shape must match the initial state")
out_dtype = self.get_tensor_type_str(out_tensor.tensor.Type())
if out_dtype not in ("int32", "int64", "uint32", "uint64"):
- raise tvm_tirx.error.OpNotImplemented(
- f"{op_name} output dtype {out_dtype} is not supported"
- )
+ raise NotImplementedError(f"{op_name} output dtype {out_dtype} is not supported")
out_shape = tuple(self._get_static_tensor_shape(out_tensor, op_name))
function = _build_stablehlo_rng_bit_generator_function(
@@ -2719,11 +2657,11 @@ class OperatorConverter:
op_options = op.BuiltinOptions()
if op_options is None:
- raise tvm_tirx.error.OpNotImplemented(f"{options_cls.__name__} is required")
+ raise NotImplementedError(f"{options_cls.__name__} is required")
options_type = getattr(BuiltinOptions, options_cls.__name__, None)
if options_type is not None and op.BuiltinOptionsType() != options_type:
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
f"Unexpected BuiltinOptions type: expected "
f"{options_cls.__name__}, got {op.BuiltinOptionsType()}"
)
@@ -2734,9 +2672,9 @@ class OperatorConverter:
def _get_subgraph(self, subgraph_index, op_name, allow_main=False):
"""Return a validated TFLite subgraph by index."""
if subgraph_index < 0 or subgraph_index >= self.model.SubgraphsLength():
- raise tvm_tirx.error.OpNotImplemented(f"{op_name} requires a valid subgraph index")
+ raise NotImplementedError(f"{op_name} requires a valid subgraph index")
if not allow_main and subgraph_index == 0:
- raise tvm_tirx.error.OpNotImplemented(f"{op_name} cannot target the main subgraph")
+ raise NotImplementedError(f"{op_name} cannot target the main subgraph")
return self.model.Subgraphs(subgraph_index)
def _make_tuple_or_single(self, exprs):
@@ -2753,9 +2691,9 @@ class OperatorConverter:
"""Validate a referenced subgraph's input and output counts."""
subgraph = self._get_subgraph(subgraph_index, op_name)
if input_count is not None and subgraph.InputsLength() != input_count:
- raise tvm_tirx.error.OpNotImplemented(f"{op_name} subgraph input count mismatch")
+ raise NotImplementedError(f"{op_name} subgraph input count mismatch")
if output_count is not None and subgraph.OutputsLength() != output_count:
- raise tvm_tirx.error.OpNotImplemented(f"{op_name} subgraph output count mismatch")
+ raise NotImplementedError(f"{op_name} subgraph output count mismatch")
return subgraph
def _check_subgraph_interface(
@@ -2805,9 +2743,7 @@ class OperatorConverter:
def _check_tensor_metadata_match(self, actual, expected, op_name, tensor_role):
"""Validate that two TFLite tensors have matching static metadata."""
if self._get_tensor_metadata(actual) != self._get_tensor_metadata(expected):
- raise tvm_tirx.error.OpNotImplemented(
- f"{op_name} {tensor_role} tensor metadata mismatch"
- )
+ raise NotImplementedError(f"{op_name} {tensor_role} tensor metadata mismatch")
def _check_subgraph_tensor_metadata(
self, subgraph, op_name, tensor_role, subgraph_indices, expected_tensors
@@ -2829,7 +2765,7 @@ class OperatorConverter:
tensor = tensor.tensor
dtype = self.get_tensor_type_str(tensor.Type())
if dtype != "bool" or tensor.ShapeLength() != 0:
- raise tvm_tirx.error.OpNotImplemented(f"{op_name} requires a scalar bool condition")
+ raise NotImplementedError(f"{op_name} requires a scalar bool condition")
def _get_subgraph_params(self, subgraph):
"""Create Relax parameters for a TFLite subgraph."""
@@ -2860,9 +2796,7 @@ class OperatorConverter:
lowering_stack = self.conversion_state["lowering_stack"]
if subgraph_index in lowering_stack:
- raise tvm_tirx.error.OpNotImplemented(
- f"Recursive TFLite {op_name} subgraphs are not supported"
- )
+ raise NotImplementedError(f"Recursive TFLite {op_name} subgraphs are not supported")
subgraph = self._get_subgraph(subgraph_index, op_name)
lowering_stack.append(subgraph_index)
@@ -3011,7 +2945,7 @@ class OperatorConverter:
input_tensors = self.get_input_tensors(op)
output_tensors = self.get_output_tensors(op)
if len(input_tensors) < 1:
- raise tvm_tirx.error.OpNotImplemented("IF requires a condition input")
+ raise NotImplementedError("IF requires a condition input")
self._require_scalar_bool_tensor(input_tensors[0], "IF")
branch_input_count = len(input_tensors) - 1
@@ -3048,9 +2982,9 @@ class OperatorConverter:
output_tensors = self.get_output_tensors(op)
loop_var_count = len(input_tensors)
if loop_var_count == 0:
- raise tvm_tirx.error.OpNotImplemented(f"{op_name} requires loop-carried inputs")
+ raise NotImplementedError(f"{op_name} requires loop-carried inputs")
if len(output_tensors) != loop_var_count:
- raise tvm_tirx.error.OpNotImplemented(f"{op_name} output count must match input count")
+ raise NotImplementedError(f"{op_name} output count must match input count")
cond_subgraph = self._check_subgraph_interface(
cond_subgraph_index,
@@ -3115,15 +3049,11 @@ class OperatorConverter:
input_tensors = self.get_input_tensors(op)
output_tensors = self.get_output_tensors(op)
if len(input_tensors) != 0 or len(output_tensors) != 0:
- raise tvm_tirx.error.OpNotImplemented(
- "CALL_ONCE with inputs or outputs is not supported"
- )
+ raise NotImplementedError("CALL_ONCE with inputs or outputs is not supported")
init_subgraph = self._get_subgraph(init_subgraph_index, "CALL_ONCE")
if init_subgraph.InputsLength() != 0 or init_subgraph.OutputsLength() != 0:
- raise tvm_tirx.error.OpNotImplemented(
- "CALL_ONCE with non-empty init subgraph I/O is not supported"
- )
+ raise NotImplementedError("CALL_ONCE with non-empty init subgraph I/O is not supported")
if init_subgraph.OperatorsLength() != 0:
self._convert_call_once_init_subgraph(init_subgraph)
return None
@@ -3134,7 +3064,7 @@ class OperatorConverter:
for op_idx in range(init_subgraph.OperatorsLength()):
op_name = self.get_op_code_str(init_subgraph.Operators(op_idx))
if op_name not in supported_init_ops:
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
f"CALL_ONCE init subgraph operator {op_name} is not supported"
)
@@ -3341,7 +3271,7 @@ class OperatorConverter:
# TOTALORDER compare is not expressible via Relax comparison ops.
if compare_type == StablehloComparisonType.STABLEHLO_COMPARISON_TYPE_FLOAT_TOTAL_ORDER:
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
"STABLEHLO_COMPARE with TOTALORDER comparison type is not supported"
)
@@ -3356,9 +3286,7 @@ class OperatorConverter:
}
relax_fn = direction_map.get(direction)
if relax_fn is None:
- raise tvm_tirx.error.OpNotImplemented(
- f"Unsupported StableHLO comparison direction: {direction}"
- )
+ raise NotImplementedError(f"Unsupported StableHLO comparison direction: {direction}")
lhs = self.get_tensor_expr(input_tensors[0])
rhs = self.get_tensor_expr(input_tensors[1])
@@ -3383,11 +3311,11 @@ class OperatorConverter:
interior = [int(d) for d in opts.InteriorPaddingAsNumpy()]
if any(d != 0 for d in interior):
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
"STABLEHLO_PAD with interior (dilation) padding is not supported"
)
if any(d < 0 for d in edge_low) or any(d < 0 for d in edge_high):
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
"STABLEHLO_PAD with negative edge padding (crop) is not supported"
)
@@ -3398,9 +3326,7 @@ class OperatorConverter:
if not self.has_expr(pad_value_tensor.tensor_idx):
pad_val = float(self.get_tensor_value(pad_value_tensor))
else:
- raise tvm_tirx.error.OpNotImplemented(
- "STABLEHLO_PAD with dynamic padding value is not supported"
- )
+ raise NotImplementedError("STABLEHLO_PAD with dynamic padding value is not supported")
# R.nn.pad with flat pad_width: [lo0, hi0, lo1, hi1, ...]
pad_width = []
@@ -3435,14 +3361,14 @@ class OperatorConverter:
# (assumes start values are constant in the flatbuffer)
# TODO: support dynamic start indices via Relax arithmetic
if any(self.has_expr(t.tensor_idx) for t in input_tensors[1:]):
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
"STABLEHLO_DYNAMIC_SLICE with dynamic start indices is not supported"
)
start_vals = [int(self.get_tensor_value(t)) for t in input_tensors[1:]]
operand_shape = [int(d) for d in self.get_tensor_shape(input_tensors[0])]
for start, size, dim in zip(start_vals, slice_sizes, operand_shape):
if start < 0 or start + size > dim:
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
"STABLEHLO_DYNAMIC_SLICE with out-of-bounds start indices is not supported"
)
end_vals = [s + sz for s, sz in zip(start_vals, slice_sizes)]
@@ -3480,13 +3406,13 @@ class OperatorConverter:
update_shape = self._get_static_tensor_shape(update_tensor, op_name)
rank = len(operand_shape)
if len(update_shape) != rank or len(start_tensors) != rank:
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
"STABLEHLO_DYNAMIC_UPDATE_SLICE requires operand, update, "
"and start-index ranks to match"
)
for dim, size in zip(operand_shape, update_shape):
if size > dim:
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
"STABLEHLO_DYNAMIC_UPDATE_SLICE update shape must be smaller than "
"or equal to operand shape for all dimensions"
)
@@ -3503,7 +3429,7 @@ class OperatorConverter:
start_vals = [int(np.asarray(self.get_tensor_value(t)).item()) for t in start_tensors]
for start, size, dim in zip(start_vals, update_shape, operand_shape):
if start < 0 or start + size > dim:
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
"STABLEHLO_DYNAMIC_UPDATE_SLICE with out-of-bounds update "
"indices is not supported"
)
@@ -3565,13 +3491,13 @@ class OperatorConverter:
lhs_shape = self._get_static_tensor_shape(input_tensors[0], "STABLEHLO_DOT_GENERAL")
rhs_shape = self._get_static_tensor_shape(input_tensors[1], "STABLEHLO_DOT_GENERAL")
if len(lhs_shape) != 2 or len(rhs_shape) != 2:
- raise tvm_tirx.error.OpNotImplemented("STABLEHLO_DOT_GENERAL only supports 2D matmul")
+ raise NotImplementedError("STABLEHLO_DOT_GENERAL only supports 2D matmul")
if lhs_batch_dims or rhs_batch_dims:
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
"STABLEHLO_DOT_GENERAL with batching dimensions is not supported"
)
if lhs_contract_dims != [1] or rhs_contract_dims != [0]:
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
"STABLEHLO_DOT_GENERAL only supports canonical contracting dimensions"
)
@@ -3598,17 +3524,11 @@ class OperatorConverter:
opts.OutputSpatialDimensionsAsNumpy(), []
)
if input_spatial_dims != [1, 2]:
- raise tvm_tirx.error.OpNotImplemented(
- "STABLEHLO_CONVOLUTION only supports NHWC input layout"
- )
+ raise NotImplementedError("STABLEHLO_CONVOLUTION only supports NHWC input layout")
if kernel_spatial_dims != [0, 1]:
- raise tvm_tirx.error.OpNotImplemented(
- "STABLEHLO_CONVOLUTION only supports HWIO kernel layout"
- )
+ raise NotImplementedError("STABLEHLO_CONVOLUTION only supports HWIO kernel layout")
if output_spatial_dims != [1, 2]:
- raise tvm_tirx.error.OpNotImplemented(
- "STABLEHLO_CONVOLUTION only supports NHWC output layout"
- )
+ raise NotImplementedError("STABLEHLO_CONVOLUTION only supports NHWC output layout")
if (
int(opts.InputBatchDimension()) != 0
@@ -3618,26 +3538,24 @@ class OperatorConverter:
or int(opts.OutputBatchDimension()) != 0
or int(opts.OutputFeatureDimension()) != 3
):
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
"STABLEHLO_CONVOLUTION only supports canonical NHWC/HWIO dimension numbers"
)
if int(opts.BatchGroupCount()) != 1:
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
"STABLEHLO_CONVOLUTION with batch_group_count > 1 is not supported"
)
if int(opts.FeatureGroupCount()) != 1:
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
"STABLEHLO_CONVOLUTION with feature_group_count > 1 is not supported"
)
data_shape = self._get_static_tensor_shape(input_tensors[0], "STABLEHLO_CONVOLUTION")
kernel_shape = self._get_static_tensor_shape(input_tensors[1], "STABLEHLO_CONVOLUTION")
if len(data_shape) != 4 or len(kernel_shape) != 4:
- raise tvm_tirx.error.OpNotImplemented(
- "STABLEHLO_CONVOLUTION only supports 2D convolution"
- )
+ raise NotImplementedError("STABLEHLO_CONVOLUTION only supports 2D convolution")
if data_shape[3] != kernel_shape[2]:
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
"STABLEHLO_CONVOLUTION input channels must match kernel input channels"
)
@@ -3651,21 +3569,13 @@ class OperatorConverter:
)
if len(window_strides) != 2 or len(rhs_dilation) != 2:
- raise tvm_tirx.error.OpNotImplemented(
- "STABLEHLO_CONVOLUTION only supports two spatial dimensions"
- )
+ raise NotImplementedError("STABLEHLO_CONVOLUTION only supports two spatial dimensions")
if lhs_dilation != [1, 1]:
- raise tvm_tirx.error.OpNotImplemented(
- "STABLEHLO_CONVOLUTION with lhs dilation is not supported"
- )
+ raise NotImplementedError("STABLEHLO_CONVOLUTION with lhs dilation is not supported")
if any(window_reversal):
- raise tvm_tirx.error.OpNotImplemented(
- "STABLEHLO_CONVOLUTION with window reversal is not supported"
- )
+ raise NotImplementedError("STABLEHLO_CONVOLUTION with window reversal is not supported")
if len(padding) != 4:
- raise tvm_tirx.error.OpNotImplemented(
- "STABLEHLO_CONVOLUTION only supports 2D low/high padding"
- )
+ raise NotImplementedError("STABLEHLO_CONVOLUTION only supports 2D low/high padding")
# StableHLO stores padding as [low_h, high_h, low_w, high_w].
relax_padding = [padding[0], padding[2], padding[1], padding[3]]
@@ -3690,7 +3600,7 @@ class OperatorConverter:
Only handles gather patterns equivalent to R.take along a single axis.
Multi-dimensional gathers, index_vector_dim != rank(indices)-1, and
- non-trivial slice_sizes raise OpNotImplemented.
+ non-trivial slice_sizes raise NotImplementedError.
"""
from tflite.StablehloGatherOptions import StablehloGatherOptions
@@ -3712,47 +3622,39 @@ class OperatorConverter:
output_shape = [int(d) for d in self.get_tensor_shape(output_tensors[0])]
if len(start_index_map) != 1:
- raise tvm_tirx.error.OpNotImplemented(
- "STABLEHLO_GATHER only supports one start_index_map entry"
- )
+ raise NotImplementedError("STABLEHLO_GATHER only supports one start_index_map entry")
axis = start_index_map[0]
if axis < 0 or axis >= len(data_shape):
- raise tvm_tirx.error.OpNotImplemented(f"Unsupported STABLEHLO_GATHER axis: {axis}")
+ raise NotImplementedError(f"Unsupported STABLEHLO_GATHER axis: {axis}")
if collapsed_slice_dims != [axis]:
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
"STABLEHLO_GATHER only supports collapsed_slice_dims matching the gather axis"
)
if len(slice_sizes) != len(data_shape):
- raise tvm_tirx.error.OpNotImplemented(
- "STABLEHLO_GATHER slice_sizes must match operand rank"
- )
+ raise NotImplementedError("STABLEHLO_GATHER slice_sizes must match operand rank")
for i, (size, dim) in enumerate(zip(slice_sizes, data_shape)):
expected = 1 if i == axis else dim
if size != expected:
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
"STABLEHLO_GATHER only supports take-equivalent slice_sizes"
)
if index_vector_dim != len(indices_shape) - 1:
- raise tvm_tirx.error.OpNotImplemented(
- "STABLEHLO_GATHER only supports trailing index_vector_dim"
- )
+ raise NotImplementedError("STABLEHLO_GATHER only supports trailing index_vector_dim")
if not indices_shape or indices_shape[index_vector_dim] != 1:
- raise tvm_tirx.error.OpNotImplemented(
- "STABLEHLO_GATHER only supports index vector size 1"
- )
+ raise NotImplementedError("STABLEHLO_GATHER only supports index vector size 1")
indices_batch_shape = indices_shape[:index_vector_dim]
expected_offset_dims = list(range(axis)) + list(
range(axis + len(indices_batch_shape), len(data_shape) + len(indices_batch_shape) - 1)
)
if offset_dims != expected_offset_dims:
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
"STABLEHLO_GATHER offset_dims do not match Relax take output layout"
)
expected_output_shape = data_shape[:axis] + indices_batch_shape + data_shape[axis + 1 :]
if output_shape != expected_output_shape:
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
"STABLEHLO_GATHER output shape does not match Relax take semantics"
)
@@ -3778,7 +3680,7 @@ class OperatorConverter:
def convert_gelu(self, op):
"""Convert TFLite GELU"""
if self.is_quantized(op):
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
"The TFLite to Relax converter does not support quantized GELU operator yet."
)
@@ -3861,7 +3763,7 @@ class OperatorConverter:
if input_is_quantized and not comparison_op:
if not output_tensor.qnn_params:
- raise tvm_tirx.error.OpAttributeInvalid(
+ raise AttributeError(
"Quantized TFLite elemwise operator output must have quantization parameters"
)
out = self.quantize(out, output_tensor)
@@ -3884,7 +3786,7 @@ class OperatorConverter:
def convert_cumsum(self, op):
"""Convert TFLite CUMSUM"""
if self.is_quantized(op):
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
"The TFLite to Relax converter does not support quantized CUMSUM operator yet."
)
@@ -3897,7 +3799,7 @@ class OperatorConverter:
input_expr = self.get_tensor_expr(input_tensors[0])
if self.has_expr(input_tensors[1].tensor_idx):
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
"The TFLite to Relax converter does not support dynamic axis for CUMSUM yet."
)
axis = self.get_tensor_value(input_tensors[1])
@@ -3911,7 +3813,7 @@ class OperatorConverter:
cumsum_options.Init(op_options.Bytes, op_options.Pos)
exclusive = cumsum_options.Exclusive()
if cumsum_options.Reverse():
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
"The TFLite to Relax converter does not support reverse CUMSUM operator yet."
)
@@ -4260,7 +4162,7 @@ class OperatorConverter:
def _check_random_output_dtype(self, op_name, output_dtype, supported_dtypes):
if output_dtype not in supported_dtypes:
supported = ", ".join(supported_dtypes)
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
f"The TFLite {op_name} converter currently supports output dtype(s) "
f"{supported} only, but got {output_dtype}."
)
@@ -4520,7 +4422,7 @@ class OperatorConverter:
in_f32 = self.dequantize(in_expr, input_tensor)
weight_axis = weight_tensor.qnn_params["axis"]
if weight_axis != 0:
- raise tvm_tirx.error.OpAttributeInvalid(
+ raise AttributeError(
f"FC weight QuantizedDimension() must be 0 (output-channel "
f"axis in [OC,IC] layout), got {weight_axis}"
)
@@ -4638,7 +4540,7 @@ class OperatorConverter:
if fused_activation_fn == ActivationFunctionType.TANH:
return relax.op.tanh(in_expr)
fused_activation_fn_str = self.activation_fn_type[fused_activation_fn]
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
f"Fused activation {fused_activation_fn_str} is not supported yet."
)
@@ -4678,9 +4580,7 @@ class OperatorConverter:
conv_options.Init(op_options.Bytes, op_options.Pos)
depth_multiplier = conv_options.DepthMultiplier()
else:
- raise tvm_tirx.error.OpNotImplemented(
- f"Operator {conv_type} is not supported for frontend TFLite."
- )
+ raise NotImplementedError(f"Operator {conv_type} is not supported for frontend TFLite.")
stride_h = conv_options.StrideH()
stride_w = conv_options.StrideW()
@@ -4795,7 +4695,7 @@ class OperatorConverter:
params["padding"] = [pad_top, pad_left, pad_bottom, pad_right]
else:
- raise tvm_tirx.error.OpAttributeUnImplemented(
+ raise NotImplementedError(
f"Padding format {padding} is not supported for operator Conv."
)
@@ -4810,13 +4710,13 @@ class OperatorConverter:
if is_depthwise_conv:
if per_channel_depthwise:
if weight_axis != 3:
- raise tvm_tirx.error.OpAttributeInvalid(
+ raise AttributeError(
"Per-channel DepthwiseConv2D weight QuantizedDimension() must be 3 "
f"(the flattened output-channel axis), got {weight_axis}"
)
scale_count = weight_tensor.tensor.Quantization().ScaleLength()
if scale_count != in_channels:
- raise tvm_tirx.error.OpAttributeInvalid(
+ raise AttributeError(
"Per-channel DepthwiseConv2D weight scale count must match "
f"input_channels * depth_multiplier ({in_channels}), got {scale_count}"
)
@@ -4832,7 +4732,7 @@ class OperatorConverter:
w_f32 = relax.op.reshape(w_f32, depthwise_weight_shape)
else:
if weight_axis != 0:
- raise tvm_tirx.error.OpAttributeInvalid(
+ raise AttributeError(
"Per-tensor DepthwiseConv2D weight QuantizedDimension() must be 0, "
f"got {weight_axis}"
)
@@ -4844,7 +4744,7 @@ class OperatorConverter:
)
else:
if weight_axis != 0:
- raise tvm_tirx.error.OpAttributeInvalid(
+ raise AttributeError(
f"Conv2D weight QuantizedDimension() must be 0 (output-channel "
f"axis in [OC,KH,KW,IC] layout), got {weight_axis}"
)
@@ -5016,12 +4916,12 @@ class OperatorConverter:
if do_pad:
params["padding"] = [pad_front, pad_top, pad_left, pad_back, pad_bottom, pad_right]
else:
- raise tvm_tirx.error.OpAttributeUnImplemented(
+ raise NotImplementedError(
f"Padding format {padding} is not supported for operator Conv3D."
)
if input_tensor.qnn_params:
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
"Quantized Conv3D is not yet supported in the Relax frontend."
)
@@ -5047,7 +4947,7 @@ class OperatorConverter:
# Handle fused activation.
if output_tensor.qnn_params:
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
"Quantized Conv3D is not yet supported in the Relax frontend."
)
@@ -5162,12 +5062,12 @@ class OperatorConverter:
output_pad = max(0, dim_stride - dim_kernel)
params["output_padding"][idx] = output_pad
else:
- raise tvm_tirx.error.OpAttributeUnImplemented(
+ raise NotImplementedError(
f"Padding format {padding} is not supported for operator Conv3DTranspose."
)
if input_tensor.qnn_params:
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
"Quantized Conv3DTranspose is not yet supported in the Relax frontend."
)
@@ -5193,7 +5093,7 @@ class OperatorConverter:
# Handle fused activation.
if output_tensor.qnn_params:
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
"Quantized Conv3DTranspose is not yet supported in the Relax frontend."
)
@@ -5394,7 +5294,7 @@ class OperatorConverter:
elif np.issubdtype(np_dtype, np.integer):
identity = np.iinfo(np_dtype).min
else:
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
f"UNSORTED_SEGMENT_MAX does not support output dtype {output_dtype}."
)
return relax.op.full(output_shape, relax.const(identity, output_dtype), output_dtype)
@@ -5405,7 +5305,7 @@ class OperatorConverter:
elif np.issubdtype(np_dtype, np.integer):
identity = np.iinfo(np_dtype).max
else:
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
f"UNSORTED_SEGMENT_MIN does not support output dtype {output_dtype}."
)
return relax.op.full(output_shape, relax.const(identity, output_dtype), output_dtype)
@@ -5416,20 +5316,20 @@ class OperatorConverter:
if op_name == "SEGMENT_SUM":
segment_ids_tensor = input_tensors[1]
if self.has_expr(segment_ids_tensor.tensor_idx):
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
"TFLite SEGMENT_SUM with runtime segment_ids is not supported, "
"because TFLite does not encode a reliable output segment count."
)
segment_ids = self.get_tensor_value(segment_ids_tensor)
if np.any(segment_ids < 0):
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
"TFLite SEGMENT_SUM with negative segment ids is not supported."
)
return int(np.max(segment_ids)) + 1 if segment_ids.size else 0
num_segments_tensor = input_tensors[2]
if self.has_expr(num_segments_tensor.tensor_idx):
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
f"TFLite {op_name} with runtime num_segments is not supported."
)
num_segments_value = self.get_tensor_value(num_segments_tensor)
@@ -5461,7 +5361,7 @@ class OperatorConverter:
if not self.has_expr(segment_ids_tensor.tensor_idx):
segment_ids_value = self.get_tensor_value(segment_ids_tensor)
if np.any(segment_ids_value < 0):
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
f"TFLite {op_name} with negative segment ids is not supported."
)
@@ -5524,7 +5424,7 @@ class OperatorConverter:
from tflite.ReverseSequenceOptions import ReverseSequenceOptions
if self.is_quantized(op):
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
"TFLite does not support quantized REVERSE_SEQUENCE operator yet."
)
@@ -5572,54 +5472,54 @@ class OperatorConverter:
input_tensors = self.get_input_tensors(op)
output_tensors = self.get_output_tensors(op)
if len(input_tensors) != 2 or len(output_tensors) != 1:
- raise tvm_tirx.error.OpNotImplemented("RFFT2D expects two inputs and one output")
+ raise NotImplementedError("RFFT2D expects two inputs and one output")
data_tensor, fft_length_tensor = input_tensors
output_tensor = output_tensors[0]
if data_tensor.tensor.Type() != TensorType.FLOAT32:
- raise tvm_tirx.error.OpNotImplemented("RFFT2D input must be float32")
+ raise NotImplementedError("RFFT2D input must be float32")
if not self._is_tflite_complex64_type(output_tensor.tensor.Type()):
- raise tvm_tirx.error.OpNotImplemented("RFFT2D output must be COMPLEX64")
+ raise NotImplementedError("RFFT2D output must be COMPLEX64")
if (
data_tensor.tensor.Sparsity() is not None
or fft_length_tensor.tensor.Sparsity() is not None
):
- raise tvm_tirx.error.OpNotImplemented("RFFT2D does not support sparse inputs")
+ raise NotImplementedError("RFFT2D does not support sparse inputs")
input_shape = tuple(to_int_list(self.get_tensor_shape(data_tensor)))
tflite_output_shape = tuple(to_int_list(self.get_tensor_shape(output_tensor)))
if len(input_shape) < 2:
- raise tvm_tirx.error.OpNotImplemented("RFFT2D input rank must be at least 2")
+ raise NotImplementedError("RFFT2D input rank must be at least 2")
try:
fft_length_value = self.get_tensor_value_or_prefetched(fft_length_tensor)
except (ValueError, TypeError):
- raise tvm_tirx.error.OpNotImplemented("RFFT2D requires a constant fft_length") from None
+ raise NotImplementedError("RFFT2D requires a constant fft_length") from None
if fft_length_value is None:
- raise tvm_tirx.error.OpNotImplemented("RFFT2D requires a constant fft_length")
+ raise NotImplementedError("RFFT2D requires a constant fft_length")
# Reject non-integer fft_length tensors before astype("int64") can silently
# truncate (e.g. float32 2.7 -> int64 2).
if not np.issubdtype(fft_length_value.dtype, np.integer):
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
f"RFFT2D fft_length must be an integer tensor, got dtype {fft_length_value.dtype!r}"
)
fft_length = fft_length_value.astype("int64")
if tuple(fft_length.shape) != (2,):
- raise tvm_tirx.error.OpNotImplemented("RFFT2D fft_length must be a length-2 tensor")
+ raise NotImplementedError("RFFT2D fft_length must be a length-2 tensor")
height = int(fft_length[0])
width = int(fft_length[1])
if height <= 0 or width <= 0:
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
f"RFFT2D fft_length must be positive, got ({height}, {width})"
)
if height != int(input_shape[-2]) or width != int(input_shape[-1]):
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
"RFFT2D currently supports fft_length matching the input spatial shape"
)
expected_tflite_output_shape = input_shape[:-2] + (height, width // 2 + 1)
if tflite_output_shape != expected_tflite_output_shape:
- raise tvm_tirx.error.OpNotImplemented("RFFT2D output shape does not match fft_length")
+ raise NotImplementedError("RFFT2D output shape does not match fft_length")
relax_output_shape = self._get_relax_tensor_shape(output_tensor)
# Dispatch: power-of-2 sizes use the O(N^2 log N) Cooley-Tukey FFT kernel;
@@ -5774,7 +5674,7 @@ class OperatorConverter:
pad_left, pad_right = get_pad_value(input_w, filter_w, stride_w)
params["padding"] = [pad_top, pad_left, pad_bottom, pad_right]
else:
- raise tvm_tirx.error.OpAttributeUnImplemented(
+ raise NotImplementedError(
f"Padding format {padding} for operator Pool2D is not supported."
)
@@ -5807,7 +5707,7 @@ class OperatorConverter:
avg_pool_exp = relax.op.nn.avg_pool2d(square_exp, **params)
out = relax.op.sqrt(avg_pool_exp)
else:
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
f"Operator {pool_type} pool is not supported for frontend TFLite."
)
@@ -5911,9 +5811,7 @@ class OperatorConverter:
mode = "REFLECT" if mode_byte == 0 else "SYMMETRIC"
if mode == "SYMMETRIC":
- raise tvm_tirx.error.OpAttributeUnImplemented(
- "MIRROR_PAD with SYMMETRIC mode is not yet supported."
- )
+ raise NotImplementedError("MIRROR_PAD with SYMMETRIC mode is not yet supported.")
# Flatten tuple-of-tuples to a list for relax.op.nn.pad
flat_pads = [int(v) for pair in paddings for v in pair]
out = relax.op.nn.pad(in_expr, flat_pads, pad_mode="reflect")
@@ -6036,7 +5934,7 @@ class OperatorConverter:
from tflite.LSTMOptions import LSTMOptions
if self.is_quantized(op):
- raise tvm_tirx.error.OpNotImplemented("TFLite quantized LSTM is not supported yet.")
+ raise NotImplementedError("TFLite quantized LSTM is not supported yet.")
input_tensors = self.get_input_tensors(op)
assert len(input_tensors) == 24, (
@@ -6059,7 +5957,7 @@ class OperatorConverter:
# Only coupled input-forget gate is supported.
if input_tensors[1].tensor_idx != -1 or input_tensors[5].tensor_idx != -1:
- raise tvm_tirx.error.OpNotImplemented("Only coupled input-forget LSTM is supported.")
+ raise NotImplementedError("Only coupled input-forget LSTM is supported.")
# Peephole, projection, and layer norm are not modeled yet.
if (
@@ -6067,7 +5965,7 @@ class OperatorConverter:
or any(t.tensor_idx != -1 for t in input_tensors[16:18])
or any(t.tensor_idx != -1 for t in input_tensors[20:24])
):
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
"Peephole, projection, and layer norm LSTM are not supported yet."
)
@@ -6182,7 +6080,7 @@ class OperatorConverter:
from tflite.SVDFOptions import SVDFOptions
if self.is_quantized(op):
- raise tvm_tirx.error.OpNotImplemented("TFLite quantized SVDF is not supported yet.")
+ raise NotImplementedError("TFLite quantized SVDF is not supported yet.")
input_tensors = self.get_input_tensors(op)
assert len(input_tensors) == 5, (
@@ -6209,7 +6107,7 @@ class OperatorConverter:
batch_size = int(batch_size)
num_filters = to_int_list(self.get_tensor_shape(input_tensors[1]))[0]
if num_filters % rank != 0:
- raise tvm_tirx.error.OpNotImplemented("SVDF num_filters must be divisible by rank.")
+ raise NotImplementedError("SVDF num_filters must be divisible by rank.")
num_units = num_filters // rank
memory_size = to_int_list(self.get_tensor_shape(input_tensors[2]))[1]
@@ -6273,7 +6171,7 @@ class OperatorConverter:
from tflite.SequenceRNNOptions import SequenceRNNOptions
if self.is_quantized(op):
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
"TFLite quantized UNIDIRECTIONAL_SEQUENCE_RNN is not supported yet."
)
@@ -6388,7 +6286,7 @@ class OperatorConverter:
from tflite.UnidirectionalSequenceLSTMOptions import UnidirectionalSequenceLSTMOptions
if self.is_quantized(op):
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
"TFLite quantized UNIDIRECTIONAL_SEQUENCE_LSTM is not supported yet."
)
@@ -6411,13 +6309,13 @@ class OperatorConverter:
# Only coupled input-forget gate is supported.
if input_tensors[1].tensor_idx != -1 or input_tensors[5].tensor_idx != -1:
- raise tvm_tirx.error.OpNotImplemented("Only coupled input-forget LSTM is supported.")
+ raise NotImplementedError("Only coupled input-forget LSTM is supported.")
if any(input_tensors[idx].tensor_idx != -1 for idx in [9, 10, 11]):
- raise tvm_tirx.error.OpNotImplemented("TFLite peephole LSTM is not supported yet.")
+ raise NotImplementedError("TFLite peephole LSTM is not supported yet.")
if any(input_tensors[idx].tensor_idx != -1 for idx in [16, 17]):
- raise tvm_tirx.error.OpNotImplemented("TFLite projection LSTM is not supported yet.")
+ raise NotImplementedError("TFLite projection LSTM is not supported yet.")
if any(input_tensors[idx].tensor_idx != -1 for idx in [20, 21, 22, 23]):
- raise tvm_tirx.error.OpNotImplemented("TFLite layer-norm LSTM is not supported yet.")
+ raise NotImplementedError("TFLite layer-norm LSTM is not supported yet.")
# Weights (transposed once outside the loop).
w_f_t = relax.op.permute_dims(self.get_tensor_expr(input_tensors[2]))
@@ -6537,7 +6435,7 @@ class OperatorConverter:
from tflite.BuiltinOptions import BuiltinOptions
if self.is_quantized(op):
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
"TFLite quantized BIDIRECTIONAL_SEQUENCE_RNN is not supported yet."
)
@@ -6557,7 +6455,7 @@ class OperatorConverter:
fused_activation_fn = rnn_opts.FusedActivationFunction()
merge_outputs = rnn_opts.MergeOutputs()
if any(input_tensors[idx].tensor_idx != -1 for idx in [9, 10, 11]):
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
"TFLite BIDIRECTIONAL_SEQUENCE_RNN aux input is not supported yet."
)
@@ -6700,7 +6598,7 @@ class OperatorConverter:
from tflite.BuiltinOptions import BuiltinOptions
if self.is_quantized(op):
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
"TFLite quantized BIDIRECTIONAL_SEQUENCE_LSTM is not supported yet."
)
@@ -6724,11 +6622,11 @@ class OperatorConverter:
# ── Forward LSTM weights (transposed once outside the loop) ──
if input_tensors[1].tensor_idx != -1 or input_tensors[5].tensor_idx != -1:
- raise tvm_tirx.error.OpNotImplemented("Only coupled input-forget LSTM is supported.")
+ raise NotImplementedError("Only coupled input-forget LSTM is supported.")
if any(input_tensors[idx].tensor_idx != -1 for idx in [9, 10, 11]):
- raise tvm_tirx.error.OpNotImplemented("TFLite peephole LSTM is not supported yet.")
+ raise NotImplementedError("TFLite peephole LSTM is not supported yet.")
if any(input_tensors[idx].tensor_idx != -1 for idx in [16, 17]):
- raise tvm_tirx.error.OpNotImplemented("TFLite projection LSTM is not supported yet.")
+ raise NotImplementedError("TFLite projection LSTM is not supported yet.")
fw_w_f_t = relax.op.permute_dims(self.get_tensor_expr(input_tensors[2]))
fw_w_c_t = relax.op.permute_dims(self.get_tensor_expr(input_tensors[3]))
@@ -6742,13 +6640,13 @@ class OperatorConverter:
# ── Backward LSTM weights (transposed once outside the loop) ──
if input_tensors[18].tensor_idx != -1 or input_tensors[22].tensor_idx != -1:
- raise tvm_tirx.error.OpNotImplemented("Only coupled input-forget LSTM is supported.")
+ raise NotImplementedError("Only coupled input-forget LSTM is supported.")
if any(input_tensors[idx].tensor_idx != -1 for idx in [26, 27, 28]):
- raise tvm_tirx.error.OpNotImplemented("TFLite peephole LSTM is not supported yet.")
+ raise NotImplementedError("TFLite peephole LSTM is not supported yet.")
if any(input_tensors[idx].tensor_idx != -1 for idx in [33, 34]):
- raise tvm_tirx.error.OpNotImplemented("TFLite projection LSTM is not supported yet.")
+ raise NotImplementedError("TFLite projection LSTM is not supported yet.")
if any(input_tensors[idx].tensor_idx != -1 for idx in range(39, 48)):
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
"TFLite BIDIRECTIONAL_SEQUENCE_LSTM aux input is not supported yet."
)
@@ -6999,7 +6897,7 @@ class OperatorConverter:
)
if self.has_expr(dense_shape_tensor.tensor_idx):
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
"TFLite EMBEDDING_LOOKUP_SPARSE with runtime dense_shape is not supported."
)
@@ -7012,7 +6910,7 @@ class OperatorConverter:
if not self.has_expr(ids_tensor.tensor_idx):
ids_value = self.get_tensor_value(ids_tensor)
if np.any(ids_value < 0):
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
"TFLite EMBEDDING_LOOKUP_SPARSE with negative ids is not supported."
)
@@ -7053,7 +6951,7 @@ class OperatorConverter:
elif combiner == CombinerType.SQRTN:
denominator_updates = relax.op.multiply(weights, weights)
else:
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
f"Unsupported TFLite EMBEDDING_LOOKUP_SPARSE combiner value {combiner}"
)
@@ -7375,7 +7273,7 @@ class OperatorConverter:
in_f32 = self.dequantize(in_expr, input_tensor)
weight_axis = weights_tensor.qnn_params["axis"]
if weight_axis != 0:
- raise tvm_tirx.error.OpAttributeInvalid(
+ raise AttributeError(
f"TransposeConv weight QuantizedDimension() must be 0 "
f"(output-channel axis in OHWI layout), got {weight_axis}"
)
@@ -8811,7 +8709,7 @@ def prepare_dense_matrix_from_sparse(sparse_tensor, sparse_tensor_value, sparse_
elif VectorType(v_type) == VectorType.Uint8:
return N.Uint8Flags
else:
- raise tvm_tirx.error.OpNotImplemented(f"The provided type {v_type} is not supported")
+ raise NotImplementedError(f"The provided type {v_type} is not supported")
def _get_flattened_index(indices, shape):
index = 0
@@ -9187,7 +9085,7 @@ def from_tflite(
# inputs cannot be represented. This also covers runtime string queries
# for ops like HASHTABLE_FIND, whose constant-foldable subset is handled
# in the op converter.
- raise tvm_tirx.error.OpNotImplemented(
+ raise NotImplementedError(
"Relax TFLite frontend does not support TensorType.STRING graph inputs "
"(e.g. runtime string queries)"
)
diff --git a/python/tvm/relax/op/index.py b/python/tvm/relax/op/index.py
index a32bd46dcd..3e7e7f6640 100644
--- a/python/tvm/relax/op/index.py
+++ b/python/tvm/relax/op/index.py
@@ -19,7 +19,6 @@
import tvm_ffi
from tvm.relax.expr import Tuple as _Tuple
-from tvm_tirx.error import InternalError as _InternalError
from tvm_tirx.ir import Attrs
from tvm_tirx.ir import Call as _Call
from tvm_tirx.ir.attrs import make_node as _make_attrs
@@ -142,7 +141,7 @@ def strided_slice(
len(value.fields) for value in (axes, begin, end, strides) if isinstance(value, _Tuple)
]
if lengths and any(length != lengths[0] for length in lengths):
- raise _InternalError("axes, begin, end, and strides must have the same length")
+ raise RuntimeError("axes, begin, end, and strides must have the same length")
return _Call(
"relax.strided_slice",
[x, axes, begin, end, *([] if strides is None else [strides])],
diff --git a/python/tvm/relax/op/manipulate.py b/python/tvm/relax/op/manipulate.py
index 77d40bf4b2..39a6f5816f 100644
--- a/python/tvm/relax/op/manipulate.py
+++ b/python/tvm/relax/op/manipulate.py
@@ -20,7 +20,6 @@ from collections.abc import Callable
import tvm_ffi
-from tvm_tirx.error import InternalError as _InternalError
from tvm_tirx.ir import Attrs, FloatImm, IntImm, is_prim_expr
from tvm_tirx.ir import Call as _Call
from tvm_tirx.ir.attrs import make_node as _make_attrs
@@ -326,7 +325,7 @@ def split(
indices_or_sections = [IntImm("int64", int(index)) for index in indices_or_sections]
if isinstance(indices_or_sections, IntImm):
if int(indices_or_sections) <= 0:
- raise _InternalError("The number of split sections must be positive")
+ raise RuntimeError("The number of split sections must be positive")
elif not isinstance(indices_or_sections, list | tuple):
raise TypeError("indices_or_sections must be an integer or a list of integers")
return _Call(
@@ -1219,7 +1218,7 @@ def one_hot(
on_value = prim_value(on_value)
off_value = prim_value(off_value)
if depth <= 0:
- raise _InternalError("one_hot: depth must be positive")
+ raise RuntimeError("one_hot: depth must be positive")
return _Call(
"relax.one_hot",
[indices, on_value, off_value],
diff --git a/python/tvm/relax/op/nn/nn.py b/python/tvm/relax/op/nn/nn.py
index 4e5c31344b..14980921ea 100644
--- a/python/tvm/relax/op/nn/nn.py
+++ b/python/tvm/relax/op/nn/nn.py
@@ -20,7 +20,6 @@ import tvm_ffi
from tvm import relax
from tvm_tirx import DataType
-from tvm_tirx.error import InternalError as _InternalError
from tvm_tirx.ir import Attrs, FloatImm
from tvm_tirx.ir import Call as _Call
from tvm_tirx.ir import PrimType as _PrimType
@@ -126,13 +125,13 @@ def conv1d(
if len(padding) == 1:
padding = tuple(padding) + tuple(padding)
if groups <= 0:
- raise _InternalError("The number of groups must be positive")
+ raise RuntimeError("The number of groups must be positive")
if len(strides) != 1:
- raise _InternalError("strides must contain 1 values")
+ raise RuntimeError("strides must contain 1 values")
if len(padding) != 2:
- raise _InternalError("padding must contain 2 values")
+ raise RuntimeError("padding must contain 2 values")
if len(dilation) != 1:
- raise _InternalError("dilation must contain 1 values")
+ raise RuntimeError("dilation must contain 1 values")
return _Call(
"relax.nn.conv1d",
[data, weight],
@@ -253,13 +252,13 @@ def conv2d(
if len(dilation) == 1:
dilation = tuple(dilation) * 2
if groups <= 0:
- raise _InternalError("The number of groups must be positive")
+ raise RuntimeError("The number of groups must be positive")
if len(strides) != 2:
- raise _InternalError("strides must contain 2 values")
+ raise RuntimeError("strides must contain 2 values")
if len(padding) != 4:
- raise _InternalError("padding must contain 4 values")
+ raise RuntimeError("padding must contain 4 values")
if len(dilation) != 2:
- raise _InternalError("dilation must contain 2 values")
+ raise RuntimeError("dilation must contain 2 values")
return _Call(
"relax.nn.conv2d",
[data, weight],
@@ -386,13 +385,13 @@ def conv3d(
if len(dilation) == 1:
dilation = tuple(dilation) * 3
if groups <= 0:
- raise _InternalError("The number of groups must be positive")
+ raise RuntimeError("The number of groups must be positive")
if len(strides) != 3:
- raise _InternalError("strides must contain 3 values")
+ raise RuntimeError("strides must contain 3 values")
if len(padding) != 6:
- raise _InternalError("padding must contain 6 values")
+ raise RuntimeError("padding must contain 6 values")
if len(dilation) != 3:
- raise _InternalError("dilation must contain 3 values")
+ raise RuntimeError("dilation must contain 3 values")
return _Call(
"relax.nn.conv3d",
[data, weight],
@@ -501,15 +500,15 @@ def conv1d_transpose(
if len(padding) == 1:
padding = tuple(padding) + tuple(padding)
if groups <= 0:
- raise _InternalError("The number of groups must be positive")
+ raise RuntimeError("The number of groups must be positive")
if len(strides) != 1:
- raise _InternalError("strides must contain 1 values")
+ raise RuntimeError("strides must contain 1 values")
if len(padding) != 2:
- raise _InternalError("padding must contain 2 values")
+ raise RuntimeError("padding must contain 2 values")
if len(dilation) != 1:
- raise _InternalError("dilation must contain 1 values")
+ raise RuntimeError("dilation must contain 1 values")
if len(output_padding) != 1:
- raise _InternalError("output_padding must contain 1 values")
+ raise RuntimeError("output_padding must contain 1 values")
return _Call(
"relax.nn.conv1d_transpose",
[data, weight],
@@ -636,15 +635,15 @@ def conv2d_transpose(
if len(output_padding) == 1:
output_padding = tuple(output_padding) * 2
if groups <= 0:
- raise _InternalError("The number of groups must be positive")
+ raise RuntimeError("The number of groups must be positive")
if len(strides) != 2:
- raise _InternalError("strides must contain 2 values")
+ raise RuntimeError("strides must contain 2 values")
if len(padding) != 4:
- raise _InternalError("padding must contain 4 values")
+ raise RuntimeError("padding must contain 4 values")
if len(dilation) != 2:
- raise _InternalError("dilation must contain 2 values")
+ raise RuntimeError("dilation must contain 2 values")
if len(output_padding) != 2:
- raise _InternalError("output_padding must contain 2 values")
+ raise RuntimeError("output_padding must contain 2 values")
return _Call(
"relax.nn.conv2d_transpose",
[data, weight],
@@ -772,15 +771,15 @@ def conv3d_transpose(
if len(output_padding) == 1:
output_padding = tuple(output_padding) * 3
if groups <= 0:
- raise _InternalError("The number of groups must be positive")
+ raise RuntimeError("The number of groups must be positive")
if len(strides) != 3:
- raise _InternalError("strides must contain 3 values")
+ raise RuntimeError("strides must contain 3 values")
if len(padding) != 6:
- raise _InternalError("padding must contain 6 values")
+ raise RuntimeError("padding must contain 6 values")
if len(dilation) != 3:
- raise _InternalError("dilation must contain 3 values")
+ raise RuntimeError("dilation must contain 3 values")
if len(output_padding) != 3:
- raise _InternalError("output_padding must contain 3 values")
+ raise RuntimeError("output_padding must contain 3 values")
return _Call(
"relax.nn.conv3d_transpose",
[data, weight],
@@ -977,13 +976,13 @@ def max_pool1d(
if len(padding) == 1:
padding = tuple(padding) + tuple(padding)
if len(strides) != 1:
- raise _InternalError("strides must contain 1 values")
+ raise RuntimeError("strides must contain 1 values")
if len(padding) != 2:
- raise _InternalError("padding must contain 2 values")
+ raise RuntimeError("padding must contain 2 values")
if len(dilation) != 1:
- raise _InternalError("dilation must contain 1 values")
+ raise RuntimeError("dilation must contain 1 values")
if len(pool_size) != 1:
- raise _InternalError("pool_size must contain 1 values")
+ raise RuntimeError("pool_size must contain 1 values")
return _Call(
"relax.nn.max_pool1d",
[data],
@@ -1096,13 +1095,13 @@ def max_pool2d(
if len(pool_size) == 1:
pool_size = tuple(pool_size) * 2
if len(strides) != 2:
- raise _InternalError("strides must contain 2 values")
+ raise RuntimeError("strides must contain 2 values")
if len(padding) != 4:
- raise _InternalError("padding must contain 4 values")
+ raise RuntimeError("padding must contain 4 values")
if len(dilation) != 2:
- raise _InternalError("dilation must contain 2 values")
+ raise RuntimeError("dilation must contain 2 values")
if len(pool_size) != 2:
- raise _InternalError("pool_size must contain 2 values")
+ raise RuntimeError("pool_size must contain 2 values")
return _Call(
"relax.nn.max_pool2d",
[data],
@@ -1209,13 +1208,13 @@ def max_pool3d(
if len(pool_size) == 1:
pool_size = tuple(pool_size) * 3
if len(strides) != 3:
- raise _InternalError("strides must contain 3 values")
+ raise RuntimeError("strides must contain 3 values")
if len(padding) != 6:
- raise _InternalError("padding must contain 6 values")
+ raise RuntimeError("padding must contain 6 values")
if len(dilation) != 3:
- raise _InternalError("dilation must contain 3 values")
+ raise RuntimeError("dilation must contain 3 values")
if len(pool_size) != 3:
- raise _InternalError("pool_size must contain 3 values")
+ raise RuntimeError("pool_size must contain 3 values")
return _Call(
"relax.nn.max_pool3d",
[data],
@@ -1308,13 +1307,13 @@ def avg_pool1d(
if len(padding) == 1:
padding = tuple(padding) + tuple(padding)
if len(strides) != 1:
- raise _InternalError("strides must contain 1 values")
+ raise RuntimeError("strides must contain 1 values")
if len(padding) != 2:
- raise _InternalError("padding must contain 2 values")
+ raise RuntimeError("padding must contain 2 values")
if len(dilation) != 1:
- raise _InternalError("dilation must contain 1 values")
+ raise RuntimeError("dilation must contain 1 values")
if len(pool_size) != 1:
- raise _InternalError("pool_size must contain 1 values")
+ raise RuntimeError("pool_size must contain 1 values")
return _Call(
"relax.nn.avg_pool1d",
[data],
@@ -1421,13 +1420,13 @@ def avg_pool2d(
if len(pool_size) == 1:
pool_size = tuple(pool_size) * 2
if len(strides) != 2:
- raise _InternalError("strides must contain 2 values")
+ raise RuntimeError("strides must contain 2 values")
if len(padding) != 4:
- raise _InternalError("padding must contain 4 values")
+ raise RuntimeError("padding must contain 4 values")
if len(dilation) != 2:
- raise _InternalError("dilation must contain 2 values")
+ raise RuntimeError("dilation must contain 2 values")
if len(pool_size) != 2:
- raise _InternalError("pool_size must contain 2 values")
+ raise RuntimeError("pool_size must contain 2 values")
return _Call(
"relax.nn.avg_pool2d",
[data],
@@ -1528,13 +1527,13 @@ def avg_pool3d(
if len(pool_size) == 1:
pool_size = tuple(pool_size) * 3
if len(strides) != 3:
- raise _InternalError("strides must contain 3 values")
+ raise RuntimeError("strides must contain 3 values")
if len(padding) != 6:
- raise _InternalError("padding must contain 6 values")
+ raise RuntimeError("padding must contain 6 values")
if len(dilation) != 3:
- raise _InternalError("dilation must contain 3 values")
+ raise RuntimeError("dilation must contain 3 values")
if len(pool_size) != 3:
- raise _InternalError("pool_size must contain 3 values")
+ raise RuntimeError("pool_size must contain 3 values")
return _Call(
"relax.nn.avg_pool3d",
[data],
@@ -1613,7 +1612,7 @@ def adaptive_avg_pool1d(
if isinstance(output_size, int):
output_size = (output_size,)
if output_size is not None and len(output_size) != 1:
- raise _InternalError("output_size must contain 1 values")
+ raise RuntimeError("output_size must contain 1 values")
return _Call(
"relax.nn.adaptive_avg_pool1d",
[data],
@@ -1691,7 +1690,7 @@ def adaptive_avg_pool2d(
if isinstance(output_size, int):
output_size = (output_size, output_size)
if output_size is not None and len(output_size) != 2:
- raise _InternalError("output_size must contain 2 values")
+ raise RuntimeError("output_size must contain 2 values")
return _Call(
"relax.nn.adaptive_avg_pool2d",
[data],
@@ -1769,7 +1768,7 @@ def adaptive_avg_pool3d(
if isinstance(output_size, int):
output_size = (output_size, output_size, output_size)
if output_size is not None and len(output_size) != 3:
- raise _InternalError("output_size must contain 3 values")
+ raise RuntimeError("output_size must contain 3 values")
return _Call(
"relax.nn.adaptive_avg_pool3d",
[data],
@@ -2642,7 +2641,7 @@ def nll_loss(
The computed result.
"""
if reduction not in ("none", "sum", "mean"):
- raise _InternalError("reduction must be none, sum, or mean")
+ raise RuntimeError("reduction must be none, sum, or mean")
return _Call(
"relax.nn.nll_loss",
[predictions, targets, *([] if weights is None else [weights])],
diff --git a/python/tvm/s_tir/__init__.py b/python/tvm/s_tir/__init__.py
index fb3218011e..397e7cb771 100644
--- a/python/tvm/s_tir/__init__.py
+++ b/python/tvm/s_tir/__init__.py
@@ -62,7 +62,10 @@ _register_namespace_initializer(_initialize_script_namespace, aliases=("s_tir",)
def _check_script_module(module):
from tvm_tirx.tirx import Function
- if any(isinstance(fn, Function) and not fn.is_tirx for fn in module.functions.values()):
+ if any(
+ isinstance(fn, Function) and fn.attrs.get("s_tir", False)
+ for fn in module.functions.values()
+ ):
from tvm.s_tir.script.ir_builder import _check_module_well_formed
_check_module_well_formed(module)
diff --git a/python/tvm/s_tir/dlight/cpu/reduction.py b/python/tvm/s_tir/dlight/cpu/reduction.py
index 69db2d4fb8..f8fb990d34 100644
--- a/python/tvm/s_tir/dlight/cpu/reduction.py
+++ b/python/tvm/s_tir/dlight/cpu/reduction.py
@@ -18,7 +18,7 @@
from tvm import s_tir
from tvm_tirx import tirx
-from tvm_tirx.codegen import llvm_get_vector_width
+from tvm_tirx.codegen import llvm
from tvm_tirx.target import Target
from ..analysis import normalize_function
@@ -89,7 +89,7 @@ class Reduction(CPUScheduleRule):
dtype_bits = last_block_stmt.writes[0].source.dtype.bits if last_block_stmt.writes else 32
# Determine vector lanes from target VLEN.
- vlen_bits = llvm_get_vector_width(target)
+ vlen_bits = llvm.get_vector_width(target)
if vlen_bits <= 0:
vlen_bits = 128
vec_lanes = max(vlen_bits // dtype_bits, 2)
diff --git a/python/tvm/s_tir/pipeline.py b/python/tvm/s_tir/pipeline.py
index 84473e3f99..a47fae34ea 100644
--- a/python/tvm/s_tir/pipeline.py
+++ b/python/tvm/s_tir/pipeline.py
@@ -125,7 +125,11 @@ def _partition_dialects(mod):
scheduled = {}
native = {}
for gv, func in mod.functions.items():
- group = scheduled if isinstance(func, tirx.Function) and not func.is_tirx else native
+ group = (
+ scheduled
+ if isinstance(func, tirx.Function) and func.attrs.get("s_tir", False)
+ else native
+ )
group[gv] = func
return scheduled, native
diff --git a/python/tvm/s_tir/schedule/analysis.py b/python/tvm/s_tir/schedule/analysis.py
index 045348cbcc..f2a0c3e72c 100644
--- a/python/tvm/s_tir/schedule/analysis.py
+++ b/python/tvm/s_tir/schedule/analysis.py
@@ -21,7 +21,8 @@ import tvm_ffi
from tvm_tirx.ir import For, Var
from tvm_tirx.runtime import Object
from tvm_tirx.tirx.expr import Expr
-from tvm_tirx.tirx.function import Function, IndexMap
+from tvm_tirx.tirx.function import Function
+from tvm_tirx.tirx.index_map import IndexMap
from . import _ffi_api
from .schedule import SBlockRV, Schedule
diff --git a/python/tvm/s_tir/schedule/schedule.py b/python/tvm/s_tir/schedule/schedule.py
index e00ec7d5b4..01286374d9 100644
--- a/python/tvm/s_tir/schedule/schedule.py
+++ b/python/tvm/s_tir/schedule/schedule.py
@@ -20,14 +20,14 @@ import inspect
from collections.abc import Callable
from typing import Literal
+from tvm_ffi import register_error
from tvm_ffi import register_object as _register_object
from tvm.s_tir import SBlock
-from tvm_tirx.error import register_error
from tvm_tirx.ir import Expr, FloatImm, For, GlobalVar, IntImm, IRModule, is_prim_expr
from tvm_tirx.runtime import DataTypeCode, MemoryScope, Object
from tvm_tirx.tirx import Function, Var, is_tensor_var
-from tvm_tirx.tirx.function import IndexMap
+from tvm_tirx.tirx.index_map import IndexMap
from . import _ffi_api
from ._type_checker import type_checked
diff --git a/python/tvm/s_tir/schedule/trace.py b/python/tvm/s_tir/schedule/trace.py
index 859fdacf79..faf02e7061 100644
--- a/python/tvm/s_tir/schedule/trace.py
+++ b/python/tvm/s_tir/schedule/trace.py
@@ -25,7 +25,7 @@ from tvm_ffi import register_object as _register_object
from tvm_tirx.ir import FloatImm, IntImm, save_json
from tvm_tirx.runtime import Object
-from tvm_tirx.tirx.function import IndexMap
+from tvm_tirx.tirx.index_map import IndexMap
from . import _ffi_api
from .instruction import ATTR_TYPE, INPUT_RV_TYPE, Instruction
diff --git a/python/tvm/s_tir/tensor_intrin/arm_cpu.py b/python/tvm/s_tir/tensor_intrin/arm_cpu.py
index 143b622ecc..ffd4677b44 100644
--- a/python/tvm/s_tir/tensor_intrin/arm_cpu.py
+++ b/python/tvm/s_tir/tensor_intrin/arm_cpu.py
@@ -21,7 +21,7 @@
from tvm.s_tir import script as Ts
from tvm.s_tir.script.ir_builder import function as build_function
from tvm_tirx import tirx
-from tvm_tirx.codegen import llvm_version_major
+from tvm_tirx.codegen import llvm
from tvm_tirx.script import tirx as T
from tvm_tirx.script.ir_builder import IRBuilder
@@ -801,7 +801,7 @@ ARM_SME_2SVLx2SVL_GEMM_INTERLEAVED_MOPA = "sme_2svlx2svl_gemm_interleaved_mopa"
# The following tensor intrinsics use LLVM intrinsics that are only available
# in versions of LLVM >= 15. Installations with older versions of LLVM will
# not be able to use them.
-if llvm_version_major() >= 15:
+if llvm.version_major() >= 15:
TensorIntrin.register(
ARM_SME_BLOCK2_2SVLx1SVL_FP16_TRANSPOSE_INTERLEAVE,
*get_sme_transpose_interleave_block2_2svl_fp16_intrin(),
diff --git a/python/tvm/s_tir/tensor_intrin/riscv_cpu.py b/python/tvm/s_tir/tensor_intrin/riscv_cpu.py
index 18126d4bbd..751da6f251 100644
--- a/python/tvm/s_tir/tensor_intrin/riscv_cpu.py
+++ b/python/tvm/s_tir/tensor_intrin/riscv_cpu.py
@@ -22,7 +22,7 @@ import logging
import tvm_ffi
from tvm.s_tir import script as Ts
-from tvm_tirx.codegen import llvm_get_vector_width, target_has_features
+from tvm_tirx.codegen import llvm, target_has_features
from tvm_tirx.runtime import DataType
from tvm_tirx.script import tirx as T
from tvm_tirx.target import Target
@@ -186,7 +186,7 @@ def register_rvv_isa_intrinsics(target: Target, inventory_only=False) -> dict():
if not target_has_features("v", target):
raise RuntimeError("Current target does not support `v` extension.")
- vlen = llvm_get_vector_width(target)
+ vlen = llvm.get_vector_width(target)
# get maximum reduction lanes (without grouping)
n_lanes = get_max_elems(vlen, lmul=1, sew=32)
diff --git a/tests/python/relax/script/test_relax_script_dynamic_shape.py b/tests/python/relax/script/test_relax_script_dynamic_shape.py
index 31359fef11..99bfb98f6f 100644
--- a/tests/python/relax/script/test_relax_script_dynamic_shape.py
+++ b/tests/python/relax/script/test_relax_script_dynamic_shape.py
@@ -162,7 +162,7 @@ def test_symbolic_shape():
)
return gv0
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
m = T.dynamic("m", "int64")
n = T.dynamic("n", "int32")
@@ -470,7 +470,7 @@ def test_bound_prim_param_reused_in_declared_function_signature():
def test_non_int64_prim_param_rejected_in_shape_annotation():
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
@R.function
def main(n: T.int32, x: R.Tensor([n], "float32")): # noqa: F821
diff --git a/tests/python/relax/script/test_relax_script_error_handling.py b/tests/python/relax/script/test_relax_script_error_handling.py
index 298c456f69..0caa3ac991 100644
--- a/tests/python/relax/script/test_relax_script_error_handling.py
+++ b/tests/python/relax/script/test_relax_script_error_handling.py
@@ -60,7 +60,7 @@ def _check(
def test_call_tir_requires_global_var():
- with pytest.raises(tvm_tirx.error.InternalError, match="first argument to be a GlobalVar"):
+ with pytest.raises(RuntimeError, match="first argument to be a GlobalVar"):
@R.function
def foo(x: R.Tensor((128, 128), "float32")) -> R.Tensor(None, "float32", ndim=2):
@@ -206,7 +206,7 @@ def test_unassigned_call_fail():
def test_incorrect_tensor_shape():
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
@R.function
def f(x: R.Tensor([16])):
@@ -322,7 +322,7 @@ def test_annotate_override():
assert isinstance(y_bind.var.ty, relax.TensorType)
assert isinstance(z_bind.var.ty, relax.AnyType)
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
@R.function
def test(x: R.Tensor):
diff --git a/tests/python/relax/script/test_relax_script_meta_programming.py b/tests/python/relax/script/test_relax_script_meta_programming.py
index 7462828f1c..df67887f01 100644
--- a/tests/python/relax/script/test_relax_script_meta_programming.py
+++ b/tests/python/relax/script/test_relax_script_meta_programming.py
@@ -460,7 +460,7 @@ def test_shared_meta_var_uses_ordinary_relax_bindings():
_check(func)
symbol = T.dynamic("symbol", "int64")
- with pytest.raises(tvm_tirx.error.InternalError, match="Invalid annotation"):
+ with pytest.raises(RuntimeError, match="Invalid annotation"):
@R.function(private=True)
def mismatched_binding():
diff --git a/tests/python/relax/test_frontend_onnx.py b/tests/python/relax/test_frontend_onnx.py
index 4035a8f845..bb1ed75c5c 100644
--- a/tests/python/relax/test_frontend_onnx.py
+++ b/tests/python/relax/test_frontend_onnx.py
@@ -8699,7 +8699,7 @@ def test_pad_opset18_axes():
# mode="wrap" was only added in Pad-19 and must be rejected for opset 18.
model = make_model((1, 3, 4), [2, 2], [2], "wrap", opset=18)
- with pytest.raises(tvm_tirx.error.OpAttributeInvalid):
+ with pytest.raises(AttributeError):
from_onnx(model, opset=18, keep_params_in_input=True)
diff --git a/tests/python/relax/test_frontend_tflite.py b/tests/python/relax/test_frontend_tflite.py
index ecf3e32494..e594063c09 100644
--- a/tests/python/relax/test_frontend_tflite.py
+++ b/tests/python/relax/test_frontend_tflite.py
@@ -5178,9 +5178,7 @@ def _build_tflite_operator_marker_model(builtin_name):
@pytest.mark.parametrize("builtin_name", ["DELEGATE", "PLACEHOLDER_FOR_GREATER_OP_CODES"])
def test_operator_marker_unsupported(builtin_name):
"""TFLite marker builtins report explicit unsupported diagnostics."""
- with pytest.raises(
- tvm_tirx.error.OpNotImplemented, match=f"TFLite operator marker {builtin_name}"
- ):
+ with pytest.raises(NotImplementedError, match=f"TFLite operator marker {builtin_name}"):
_load_model_from_buffer(_build_tflite_operator_marker_model(builtin_name))
@@ -5584,7 +5582,7 @@ def test_rfft2d_mismatched_fft_length_unsupported():
else:
tflite_model = tflite.Model.GetRootAsModel(buf, 0)
- with pytest.raises(tvm_tirx.error.OpNotImplemented, match="fft_length"):
+ with pytest.raises(NotImplementedError, match="fft_length"):
from_tflite(tflite_model)
@@ -5610,7 +5608,7 @@ def test_rfft2d_dynamic_fft_length_unsupported():
else:
tflite_model = tflite.Model.GetRootAsModel(buf, 0)
- with pytest.raises(tvm_tirx.error.OpNotImplemented, match="requires a constant fft_length"):
+ with pytest.raises(NotImplementedError, match="requires a constant fft_length"):
from_tflite(tflite_model)
@@ -5948,23 +5946,19 @@ def test_call_subgraph_nested_call():
def test_call_subgraph_invalid_index_unsupported():
"""Test CALL rejects invalid subgraph indices before lowering."""
- with pytest.raises(
- tvm_tirx.error.OpNotImplemented, match="CALL requires a valid subgraph index"
- ):
+ with pytest.raises(NotImplementedError, match="CALL requires a valid subgraph index"):
_load_model_from_buffer(_build_tflite_call_model(call_subgraph_index=2))
def test_call_subgraph_io_mismatch_unsupported():
"""Test CALL rejects callees whose input arity does not match the call site."""
- with pytest.raises(tvm_tirx.error.OpNotImplemented, match="CALL subgraph input count mismatch"):
+ with pytest.raises(NotImplementedError, match="CALL subgraph input count mismatch"):
_load_model_from_buffer(_build_tflite_call_model(callee_inputs=[]))
def test_call_subgraph_output_metadata_mismatch_unsupported():
"""Test CALL rejects callees whose output metadata does not match the call site."""
- with pytest.raises(
- tvm_tirx.error.OpNotImplemented, match="CALL subgraph output tensor metadata mismatch"
- ):
+ with pytest.raises(NotImplementedError, match="CALL subgraph output tensor metadata mismatch"):
_load_model_from_buffer(_build_tflite_call_model(callee_output_shape=[2]))
@@ -6292,37 +6286,31 @@ def test_if_subgraphs_multi_output():
def test_if_subgraphs_non_bool_condition_unsupported():
"""Test IF rejects non-bool condition tensors."""
- with pytest.raises(
- tvm_tirx.error.OpNotImplemented, match="IF requires a scalar bool condition"
- ):
+ with pytest.raises(NotImplementedError, match="IF requires a scalar bool condition"):
_load_model_from_buffer(_build_tflite_if_model(condition_type=_tfl_tensor_type.INT32))
def test_if_subgraphs_invalid_index_unsupported():
"""Test IF rejects invalid branch subgraph indices before lowering."""
- with pytest.raises(tvm_tirx.error.OpNotImplemented, match="IF requires a valid subgraph index"):
+ with pytest.raises(NotImplementedError, match="IF requires a valid subgraph index"):
_load_model_from_buffer(_build_tflite_if_model(then_subgraph_index=3))
def test_if_subgraphs_output_count_mismatch_unsupported():
"""Test IF rejects branches whose output arity does not match the call site."""
- with pytest.raises(tvm_tirx.error.OpNotImplemented, match="IF subgraph output count mismatch"):
+ with pytest.raises(NotImplementedError, match="IF subgraph output count mismatch"):
_load_model_from_buffer(_build_tflite_if_model(else_outputs=[]))
def test_if_subgraphs_input_metadata_mismatch_unsupported():
"""Test IF rejects branches whose input metadata does not match the call site."""
- with pytest.raises(
- tvm_tirx.error.OpNotImplemented, match="IF subgraph input tensor metadata mismatch"
- ):
+ with pytest.raises(NotImplementedError, match="IF subgraph input tensor metadata mismatch"):
_load_model_from_buffer(_build_tflite_if_model(else_input_shape=[2]))
def test_if_subgraphs_output_metadata_mismatch_unsupported():
"""Test IF rejects branches whose output metadata does not match the call site."""
- with pytest.raises(
- tvm_tirx.error.OpNotImplemented, match="IF subgraph output tensor metadata mismatch"
- ):
+ with pytest.raises(NotImplementedError, match="IF subgraph output tensor metadata mismatch"):
_load_model_from_buffer(_build_tflite_if_model(else_output_shape=[2]))
@@ -6764,31 +6752,25 @@ def test_while_subgraphs_two_loop_vars():
def test_while_subgraphs_non_bool_condition_unsupported():
"""Test WHILE rejects cond subgraphs that do not return scalar bool."""
- with pytest.raises(
- tvm_tirx.error.OpNotImplemented, match="WHILE requires a scalar bool condition"
- ):
+ with pytest.raises(NotImplementedError, match="WHILE requires a scalar bool condition"):
_load_model_from_buffer(_build_tflite_while_model(cond_output_type=_tfl_tensor_type.INT32))
def test_while_subgraphs_invalid_index_unsupported():
"""Test WHILE rejects invalid cond/body subgraph indices before lowering."""
- with pytest.raises(
- tvm_tirx.error.OpNotImplemented, match="WHILE requires a valid subgraph index"
- ):
+ with pytest.raises(NotImplementedError, match="WHILE requires a valid subgraph index"):
_load_model_from_buffer(_build_tflite_while_model(cond_subgraph_index=3))
def test_while_subgraphs_zero_loop_vars_unsupported():
"""Test WHILE rejects operators without loop-carried tensors."""
- with pytest.raises(tvm_tirx.error.OpNotImplemented, match="WHILE requires loop-carried inputs"):
+ with pytest.raises(NotImplementedError, match="WHILE requires loop-carried inputs"):
_load_model_from_buffer(_build_tflite_zero_var_while_model())
def test_while_subgraphs_loop_state_metadata_mismatch_unsupported():
"""Test WHILE rejects loop outputs whose metadata does not match loop inputs."""
- with pytest.raises(
- tvm_tirx.error.OpNotImplemented, match="WHILE loop state tensor metadata mismatch"
- ):
+ with pytest.raises(NotImplementedError, match="WHILE loop state tensor metadata mismatch"):
_load_model_from_buffer(
_build_tflite_while_model(main_output_type=_tfl_tensor_type.FLOAT32)
)
@@ -6796,25 +6778,19 @@ def test_while_subgraphs_loop_state_metadata_mismatch_unsupported():
def test_while_subgraphs_output_count_mismatch_unsupported():
"""Test WHILE rejects body subgraphs whose output arity does not match loop vars."""
- with pytest.raises(
- tvm_tirx.error.OpNotImplemented, match="WHILE subgraph output count mismatch"
- ):
+ with pytest.raises(NotImplementedError, match="WHILE subgraph output count mismatch"):
_load_model_from_buffer(_build_tflite_while_model(body_outputs=[]))
def test_while_subgraphs_input_metadata_mismatch_unsupported():
"""Test WHILE rejects cond subgraph inputs whose metadata does not match loop vars."""
- with pytest.raises(
- tvm_tirx.error.OpNotImplemented, match="WHILE subgraph input tensor metadata mismatch"
- ):
+ with pytest.raises(NotImplementedError, match="WHILE subgraph input tensor metadata mismatch"):
_load_model_from_buffer(_build_tflite_while_model(cond_input_type=_tfl_tensor_type.FLOAT32))
def test_while_subgraphs_output_metadata_mismatch_unsupported():
"""Test WHILE rejects body outputs whose metadata does not match loop vars."""
- with pytest.raises(
- tvm_tirx.error.OpNotImplemented, match="WHILE subgraph output tensor metadata mismatch"
- ):
+ with pytest.raises(NotImplementedError, match="WHILE subgraph output tensor metadata mismatch"):
_load_model_from_buffer(
_build_tflite_while_model(body_output_type=_tfl_tensor_type.FLOAT32)
)
@@ -6917,13 +6893,13 @@ def test_call_once_empty_init_subgraph():
def test_call_once_non_empty_init_subgraph_unsupported():
"""Test CALL_ONCE rejects init subgraphs with side-effect-like bodies."""
- with pytest.raises(tvm_tirx.error.OpNotImplemented, match="CALL_ONCE"):
+ with pytest.raises(NotImplementedError, match="CALL_ONCE"):
_load_model_from_buffer(_build_tflite_call_once_model(init_has_op=True))
def test_call_once_inputs_outputs_unsupported():
"""Test CALL_ONCE rejects operator inputs and outputs."""
- with pytest.raises(tvm_tirx.error.OpNotImplemented, match="CALL_ONCE with inputs or outputs"):
+ with pytest.raises(NotImplementedError, match="CALL_ONCE with inputs or outputs"):
_load_model_from_buffer(
_build_tflite_call_once_model(call_once_inputs=[0], call_once_outputs=[0])
)
@@ -6931,17 +6907,13 @@ def test_call_once_inputs_outputs_unsupported():
def test_call_once_init_subgraph_io_unsupported():
"""Test CALL_ONCE rejects init subgraphs with inputs or outputs."""
- with pytest.raises(
- tvm_tirx.error.OpNotImplemented, match="CALL_ONCE with non-empty init subgraph I/O"
- ):
+ with pytest.raises(NotImplementedError, match="CALL_ONCE with non-empty init subgraph I/O"):
_load_model_from_buffer(_build_tflite_call_once_model(init_inputs=[0], init_outputs=[0]))
def test_call_once_invalid_index_unsupported():
"""Test CALL_ONCE rejects invalid init subgraph indices before lowering."""
- with pytest.raises(
- tvm_tirx.error.OpNotImplemented, match="CALL_ONCE requires a valid subgraph index"
- ):
+ with pytest.raises(NotImplementedError, match="CALL_ONCE requires a valid subgraph index"):
_load_model_from_buffer(_build_tflite_call_once_model(init_subgraph_index=2))
@@ -7685,13 +7657,13 @@ def test_resource_variable_call_once_init_read():
def test_assign_variable_main_subgraph_unsupported():
"""Test ASSIGN_VARIABLE remains unsupported outside CALL_ONCE initialization."""
- with pytest.raises(tvm_tirx.error.OpNotImplemented, match="ASSIGN_VARIABLE outside CALL_ONCE"):
+ with pytest.raises(NotImplementedError, match="ASSIGN_VARIABLE outside CALL_ONCE"):
_load_model_from_buffer(_build_tflite_resource_assign_in_main_model())
def test_read_variable_uninitialized_unsupported():
"""Test READ_VARIABLE rejects resource handles without supported initialization."""
- with pytest.raises(tvm_tirx.error.OpNotImplemented, match="READ_VARIABLE requires a resource"):
+ with pytest.raises(NotImplementedError, match="READ_VARIABLE requires a resource"):
_load_model_from_buffer(_build_tflite_resource_read_uninitialized_model())
@@ -7736,13 +7708,13 @@ def test_hashtable_call_once_import_find_string_to_int64_2d_query():
def test_hashtable_call_once_import_find_int64_to_string_unsupported():
"""Test HASHTABLE_FIND rejects int64-to-string tables until string outputs exist."""
- with pytest.raises(tvm_tirx.error.OpNotImplemented, match="string -> int64"):
+ with pytest.raises(NotImplementedError, match="string -> int64"):
_load_model_from_buffer(_build_tflite_hashtable_find_int64_to_string_model())
def test_hashtable_call_once_import_find_runtime_query_unsupported():
"""Test HASHTABLE_FIND rejects runtime string queries."""
- with pytest.raises(tvm_tirx.error.OpNotImplemented, match="string queries|STRING graph inputs"):
+ with pytest.raises(NotImplementedError, match="string queries|STRING graph inputs"):
_load_model_from_buffer(
_build_tflite_hashtable_find_string_to_int64_model(query_is_input=True)
)
@@ -7750,7 +7722,7 @@ def test_hashtable_call_once_import_find_runtime_query_unsupported():
def test_hashtable_call_once_import_duplicate_keys_unsupported():
"""Test HASHTABLE_IMPORT rejects duplicate static keys."""
- with pytest.raises(tvm_tirx.error.OpNotImplemented, match="duplicate keys"):
+ with pytest.raises(NotImplementedError, match="duplicate keys"):
_load_model_from_buffer(
_build_tflite_hashtable_find_string_to_int64_model(
table_keys=["alpha", "alpha"], table_values=[10, 20]
@@ -7777,13 +7749,13 @@ def test_hashtable_call_once_import_size():
def test_hashtable_import_main_subgraph_unsupported():
"""Test HASHTABLE_IMPORT remains unsupported outside CALL_ONCE initialization."""
- with pytest.raises(tvm_tirx.error.OpNotImplemented, match="HASHTABLE_IMPORT outside CALL_ONCE"):
+ with pytest.raises(NotImplementedError, match="HASHTABLE_IMPORT outside CALL_ONCE"):
_load_model_from_buffer(_build_tflite_hashtable_import_in_main_model())
def test_hashtable_size_uninitialized_unsupported():
"""Test HASHTABLE_SIZE rejects tables without supported initialization."""
- with pytest.raises(tvm_tirx.error.OpNotImplemented, match="HASHTABLE_SIZE requires a table"):
+ with pytest.raises(NotImplementedError, match="HASHTABLE_SIZE requires a table"):
_load_model_from_buffer(_build_tflite_hashtable_size_uninitialized_model())
@@ -7944,7 +7916,7 @@ def test_hashtable_lookup_2d_value():
def test_hashtable_lookup_string_value_unsupported():
string_type = _get_string_tensor_type()
- with pytest.raises(tvm_tirx.error.OpNotImplemented, match="STRING graph inputs"):
+ with pytest.raises(NotImplementedError, match="STRING graph inputs"):
_load_model_from_buffer(
_build_tflite_hashtable_lookup_model(value_shape=[3], value_type=string_type)
)
@@ -8737,7 +8709,7 @@ def test_stablehlo_reduce_unsupported_reducer():
else:
tflite_model = tflite.Model.GetRootAsModel(buf, 0)
- with pytest.raises(tvm_tirx.error.OpNotImplemented, match="reducer"):
+ with pytest.raises(NotImplementedError, match="reducer"):
from_tflite(tflite_model)
@@ -8749,7 +8721,7 @@ def test_stablehlo_reduce_non_identity_init_unsupported():
else:
tflite_model = tflite.Model.GetRootAsModel(buf, 0)
- with pytest.raises(tvm_tirx.error.OpNotImplemented, match="init value"):
+ with pytest.raises(NotImplementedError, match="init value"):
from_tflite(tflite_model)
@@ -8792,7 +8764,7 @@ def test_stablehlo_sort_unsupported_comparator():
else:
tflite_model = tflite.Model.GetRootAsModel(buf, 0)
- with pytest.raises(tvm_tirx.error.OpNotImplemented, match="LT or GT"):
+ with pytest.raises(NotImplementedError, match="LT or GT"):
from_tflite(tflite_model)
@@ -8805,7 +8777,7 @@ def test_stablehlo_sort_stable_unsupported():
else:
tflite_model = tflite.Model.GetRootAsModel(buf, 0)
- with pytest.raises(tvm_tirx.error.OpNotImplemented, match="stable sort"):
+ with pytest.raises(NotImplementedError, match="stable sort"):
from_tflite(tflite_model)
@@ -8845,7 +8817,7 @@ def test_stablehlo_reduce_window_unsupported_reducer():
else:
tflite_model = tflite.Model.GetRootAsModel(buf, 0)
- with pytest.raises(tvm_tirx.error.OpNotImplemented, match="MAXIMUM"):
+ with pytest.raises(NotImplementedError, match="MAXIMUM"):
from_tflite(tflite_model)
@@ -8857,7 +8829,7 @@ def test_stablehlo_reduce_window_base_dilation_unsupported():
else:
tflite_model = tflite.Model.GetRootAsModel(buf, 0)
- with pytest.raises(tvm_tirx.error.OpNotImplemented, match="base dilation"):
+ with pytest.raises(NotImplementedError, match="base dilation"):
from_tflite(tflite_model)
@@ -8901,7 +8873,7 @@ def test_stablehlo_scatter_unsupported_reducer():
else:
tflite_model = tflite.Model.GetRootAsModel(buf, 0)
- with pytest.raises(tvm_tirx.error.OpNotImplemented, match="reducer"):
+ with pytest.raises(NotImplementedError, match="reducer"):
from_tflite(tflite_model)
@@ -8913,7 +8885,7 @@ def test_stablehlo_scatter_update_window_unsupported():
else:
tflite_model = tflite.Model.GetRootAsModel(buf, 0)
- with pytest.raises(tvm_tirx.error.OpNotImplemented, match="point updates"):
+ with pytest.raises(NotImplementedError, match="point updates"):
from_tflite(tflite_model)
@@ -8938,7 +8910,7 @@ def test_stablehlo_custom_call_unsupported_target():
"""TFLite StableHLO CUSTOM_CALL rejects unknown external call targets."""
buf = _build_stablehlo_custom_call_model(call_target_name="custom_backend")
with pytest.raises(
- tvm_tirx.error.OpNotImplemented,
+ NotImplementedError,
match="STABLEHLO_CUSTOM_CALL target custom_backend is not supported",
):
_load_model_from_buffer(buf)
@@ -8947,14 +8919,14 @@ def test_stablehlo_custom_call_unsupported_target():
def test_stablehlo_custom_call_sharding_side_effect_unsupported():
"""TFLite StableHLO CUSTOM_CALL rejects side-effecting Sharding calls."""
buf = _build_stablehlo_custom_call_model(has_side_effect=True)
- with pytest.raises(tvm_tirx.error.OpNotImplemented, match="side effects"):
+ with pytest.raises(NotImplementedError, match="side effects"):
_load_model_from_buffer(buf)
def test_stablehlo_custom_call_sharding_metadata_mismatch_unsupported():
"""TFLite StableHLO CUSTOM_CALL rejects Sharding calls that change tensor metadata."""
buf = _build_stablehlo_custom_call_model(output_tensor_type=_tfl_tensor_type.INT32)
- with pytest.raises(tvm_tirx.error.OpNotImplemented, match="Sharding tensor metadata mismatch"):
+ with pytest.raises(NotImplementedError, match="Sharding tensor metadata mismatch"):
_load_model_from_buffer(buf)
@@ -8962,7 +8934,7 @@ def test_stablehlo_options_missing_payload_unsupported():
"""A StableHLO op that declares an options type but omits the payload fails cleanly."""
buf = _build_stablehlo_custom_call_model(include_options=False)
with pytest.raises(
- tvm_tirx.error.OpNotImplemented,
+ NotImplementedError,
match="StablehloCustomCallOptions is required but missing from the operator",
):
_load_model_from_buffer(buf)
@@ -9163,16 +9135,14 @@ def test_stablehlo_rng_bit_generator_constant_state():
def test_stablehlo_rng_bit_generator_unsupported_output_dtype():
"""TFLite STABLEHLO_RNG_BIT_GENERATOR rejects non-integer output dtypes."""
buf = _build_stablehlo_rng_model(_tfl_rng_algorithm.PHILOX, 3, [2, 3], _tfl_tensor_type.FLOAT32)
- with pytest.raises(
- tvm_tirx.error.OpNotImplemented, match="output dtype float32 is not supported"
- ):
+ with pytest.raises(NotImplementedError, match="output dtype float32 is not supported"):
_load_model_from_buffer(buf)
def test_stablehlo_rng_bit_generator_threefry_invalid_state_unsupported():
"""TFLite STABLEHLO_RNG_BIT_GENERATOR rejects a u64[3] state for THREEFRY."""
buf = _build_stablehlo_rng_model(_tfl_rng_algorithm.THREEFRY, 3, [2, 3], _tfl_tensor_type.INT32)
- with pytest.raises(tvm_tirx.error.OpNotImplemented, match="THREEFRY requires a u64.2. state"):
+ with pytest.raises(NotImplementedError, match="THREEFRY requires a u64.2. state"):
_load_model_from_buffer(buf)
@@ -9207,7 +9177,7 @@ def test_stablehlo_rng_bit_generator_non_uint64_state_unsupported():
buf = _finish_tflite_model(
builder, subgraph=subgraph, operator_codes=[rng_code], buffers=buffers
)
- with pytest.raises(tvm_tirx.error.OpNotImplemented, match="requires a uint64 initial state"):
+ with pytest.raises(NotImplementedError, match="requires a uint64 initial state"):
_load_model_from_buffer(buf)
@@ -9272,7 +9242,7 @@ def test_stablehlo_while():
def test_stablehlo_while_non_bool_condition_unsupported():
"""STABLEHLO_WHILE rejects cond subgraphs that do not return scalar bool."""
with pytest.raises(
- tvm_tirx.error.OpNotImplemented, match="STABLEHLO_WHILE requires a scalar bool condition"
+ NotImplementedError, match="STABLEHLO_WHILE requires a scalar bool condition"
):
_load_model_from_buffer(
_build_stablehlo_while_model(cond_output_type=_tfl_tensor_type.INT32)
@@ -9282,23 +9252,21 @@ def test_stablehlo_while_non_bool_condition_unsupported():
def test_stablehlo_while_invalid_index_unsupported():
"""STABLEHLO_WHILE rejects invalid cond/body subgraph indices before lowering."""
with pytest.raises(
- tvm_tirx.error.OpNotImplemented, match="STABLEHLO_WHILE requires a valid subgraph index"
+ NotImplementedError, match="STABLEHLO_WHILE requires a valid subgraph index"
):
_load_model_from_buffer(_build_stablehlo_while_model(cond_subgraph_index=3))
def test_stablehlo_while_output_count_mismatch_unsupported():
"""STABLEHLO_WHILE rejects body subgraphs whose output arity does not match loop vars."""
- with pytest.raises(
- tvm_tirx.error.OpNotImplemented, match="STABLEHLO_WHILE subgraph output count mismatch"
- ):
+ with pytest.raises(NotImplementedError, match="STABLEHLO_WHILE subgraph output count mismatch"):
_load_model_from_buffer(_build_stablehlo_while_model(body_outputs=[]))
def test_stablehlo_while_input_metadata_mismatch_unsupported():
"""STABLEHLO_WHILE rejects cond subgraph inputs whose metadata does not match loop vars."""
with pytest.raises(
- tvm_tirx.error.OpNotImplemented,
+ NotImplementedError,
match="STABLEHLO_WHILE subgraph input tensor metadata mismatch",
):
_load_model_from_buffer(
@@ -9309,7 +9277,7 @@ def test_stablehlo_while_input_metadata_mismatch_unsupported():
def test_stablehlo_while_output_metadata_mismatch_unsupported():
"""STABLEHLO_WHILE rejects body outputs whose metadata does not match loop vars."""
with pytest.raises(
- tvm_tirx.error.OpNotImplemented,
+ NotImplementedError,
match="STABLEHLO_WHILE subgraph output tensor metadata mismatch",
):
_load_model_from_buffer(
@@ -9362,7 +9330,7 @@ def test_stablehlo_composite_attributes_unsupported():
else:
tflite_model = tflite.Model.GetRootAsModel(buf, 0)
- with pytest.raises(tvm_tirx.error.OpNotImplemented, match="composite attributes"):
+ with pytest.raises(NotImplementedError, match="composite attributes"):
from_tflite(tflite_model)
@@ -10054,7 +10022,7 @@ def test_stablehlo_compare(direction_enum, relax_op):
def test_stablehlo_compare_totalorder_unsupported():
- """STABLEHLO_COMPARE with TOTALORDER type raises OpNotImplemented."""
+ """STABLEHLO_COMPARE with TOTALORDER type raises NotImplementedError."""
builder = flatbuffers.Builder(1024)
_DIR = _tfl_stablehlo_comp_dir.StablehloComparisonDirection
@@ -10103,7 +10071,7 @@ def test_stablehlo_compare_totalorder_unsupported():
else:
tflite_model = tflite.Model.GetRootAsModel(buf, 0)
- with pytest.raises(tvm_tirx.error.OpNotImplemented, match="TOTALORDER"):
+ with pytest.raises(NotImplementedError, match="TOTALORDER"):
from_tflite(tflite_model)
@@ -10246,7 +10214,7 @@ def test_stablehlo_gather_complex_unsupported():
else:
tflite_model = tflite.Model.GetRootAsModel(buf, 0)
- with pytest.raises(tvm_tirx.error.OpNotImplemented, match="start_index_map"):
+ with pytest.raises(NotImplementedError, match="start_index_map"):
from_tflite(tflite_model)
@@ -10342,7 +10310,7 @@ def test_stablehlo_pad():
def test_stablehlo_pad_interior_unsupported():
- """STABLEHLO_PAD with interior padding raises OpNotImplemented."""
+ """STABLEHLO_PAD with interior padding raises NotImplementedError."""
builder = flatbuffers.Builder(1024)
lo_vec = _pad_vector(
@@ -10402,12 +10370,12 @@ def test_stablehlo_pad_interior_unsupported():
tflite_model = tflite.Model.Model.GetRootAsModel(buf, 0)
else:
tflite_model = tflite.Model.GetRootAsModel(buf, 0)
- with pytest.raises(tvm_tirx.error.OpNotImplemented, match="interior"):
+ with pytest.raises(NotImplementedError, match="interior"):
from_tflite(tflite_model)
def test_stablehlo_pad_negative_unsupported():
- """STABLEHLO_PAD with negative edge padding raises OpNotImplemented."""
+ """STABLEHLO_PAD with negative edge padding raises NotImplementedError."""
builder = flatbuffers.Builder(1024)
lo_vec = _pad_vector(
@@ -10467,7 +10435,7 @@ def test_stablehlo_pad_negative_unsupported():
tflite_model = tflite.Model.Model.GetRootAsModel(buf, 0)
else:
tflite_model = tflite.Model.GetRootAsModel(buf, 0)
- with pytest.raises(tvm_tirx.error.OpNotImplemented, match="negative"):
+ with pytest.raises(NotImplementedError, match="negative"):
from_tflite(tflite_model)
@@ -10607,7 +10575,7 @@ def test_stablehlo_dynamic_slice_dynamic_starts_unsupported():
else:
tflite_model = tflite.Model.GetRootAsModel(buf, 0)
- with pytest.raises(tvm_tirx.error.OpNotImplemented, match="dynamic start"):
+ with pytest.raises(NotImplementedError, match="dynamic start"):
from_tflite(tflite_model)
@@ -10619,7 +10587,7 @@ def test_stablehlo_dynamic_slice_out_of_bounds_unsupported():
else:
tflite_model = tflite.Model.GetRootAsModel(buf, 0)
- with pytest.raises(tvm_tirx.error.OpNotImplemented, match="out-of-bounds"):
+ with pytest.raises(NotImplementedError, match="out-of-bounds"):
from_tflite(tflite_model)
@@ -10793,7 +10761,7 @@ def test_stablehlo_dynamic_update_slice_out_of_bounds_unsupported():
else:
tflite_model = tflite.Model.GetRootAsModel(buf, 0)
- with pytest.raises(tvm_tirx.error.OpNotImplemented, match="out-of-bounds"):
+ with pytest.raises(NotImplementedError, match="out-of-bounds"):
from_tflite(tflite_model)
@@ -10893,7 +10861,7 @@ def test_stablehlo_dot_general_noncanonical_unsupported():
else:
tflite_model = tflite.Model.GetRootAsModel(buf, 0)
- with pytest.raises(tvm_tirx.error.OpNotImplemented, match="contracting"):
+ with pytest.raises(NotImplementedError, match="contracting"):
from_tflite(tflite_model)
@@ -11035,7 +11003,7 @@ def test_stablehlo_convolution_feature_group_unsupported():
else:
tflite_model = tflite.Model.GetRootAsModel(buf, 0)
- with pytest.raises(tvm_tirx.error.OpNotImplemented, match="feature_group_count"):
+ with pytest.raises(NotImplementedError, match="feature_group_count"):
from_tflite(tflite_model)
@@ -11047,7 +11015,7 @@ def test_stablehlo_convolution_dimension_numbers_unsupported():
else:
tflite_model = tflite.Model.GetRootAsModel(buf, 0)
- with pytest.raises(tvm_tirx.error.OpNotImplemented, match="dimension numbers"):
+ with pytest.raises(NotImplementedError, match="dimension numbers"):
from_tflite(tflite_model)
@@ -12062,7 +12030,7 @@ def test_quantized_add_fused_relu6_uses_float_clip_before_quantize():
def test_quantized_add_without_output_qparams_invalid():
- """Quantized ADD with missing output qparams raises OpAttributeInvalid."""
+ """Quantized ADD with missing output qparams raises AttributeError."""
builder = flatbuffers.Builder(1024)
in_q = _build_quantization_parameters(
@@ -12105,7 +12073,7 @@ def test_quantized_add_without_output_qparams_invalid():
else:
tflite_model = tflite.Model.GetRootAsModel(buf, 0)
- with pytest.raises(tvm_tirx.error.OpAttributeInvalid, match="output must have quantization"):
+ with pytest.raises(AttributeError, match="output must have quantization"):
from_tflite(tflite_model)
@@ -12139,7 +12107,7 @@ def test_quantized_square_unsupported():
buffers=[_build_buffer(builder)] * 2,
)
- with pytest.raises(tvm_tirx.error.OpNotImplemented, match="SQUARE"):
+ with pytest.raises(NotImplementedError, match="SQUARE"):
_load_model_from_buffer(buf)
@@ -13784,7 +13752,7 @@ def test_lstm_rejects_unsupported_features():
zeros_r = np.zeros((num_units, num_units), dtype=np.float32)
zeros_b = np.zeros(num_units, dtype=np.float32)
- with pytest.raises(tvm_tirx.error.OpNotImplemented, match="not supported yet"):
+ with pytest.raises(NotImplementedError, match="not supported yet"):
_load_model_from_buffer(
_build_lstm_model(
batch,
@@ -14407,7 +14375,7 @@ def test_unidirectional_sequence_lstm_rejects_projection():
recurrent = np.eye(num_units, dtype=np.float32)
bias = np.zeros(num_units, dtype=np.float32)
- with pytest.raises(tvm_tirx.error.OpNotImplemented, match="projection LSTM"):
+ with pytest.raises(NotImplementedError, match="projection LSTM"):
_load_model_from_buffer(
_build_unidirectional_sequence_lstm_model(
batch,
@@ -14681,7 +14649,7 @@ def test_bidirectional_sequence_rnn_rejects_aux_input():
recurrent = np.eye(num_units, dtype=np.float32)
bias = np.zeros(num_units, dtype=np.float32)
- with pytest.raises(tvm_tirx.error.OpNotImplemented, match="aux input"):
+ with pytest.raises(NotImplementedError, match="aux input"):
_load_model_from_buffer(
_build_bidirectional_sequence_rnn_model(
batch,
@@ -14989,7 +14957,7 @@ def test_bidirectional_sequence_lstm_rejects_aux_input():
recurrent = np.eye(num_units, dtype=np.float32)
bias = np.zeros(num_units, dtype=np.float32)
- with pytest.raises(tvm_tirx.error.OpNotImplemented, match="aux input"):
+ with pytest.raises(NotImplementedError, match="aux input"):
_load_model_from_buffer(
_build_bidirectional_sequence_lstm_model(
batch,
diff --git a/tests/python/relax/test_op_index.py b/tests/python/relax/test_op_index.py
index e99f53a82b..c2a38eb656 100644
--- a/tests/python/relax/test_op_index.py
+++ b/tests/python/relax/test_op_index.py
@@ -665,11 +665,11 @@ def test_strided_slice_begin_end_strides_int64():
def test_strided_slice_inconsistent_axes_begin_end_strides_length():
x = relax.Var("x", R.Tensor((8, 9), "float32"))
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
relax.op.strided_slice(x, axes=[1], begin=[], end=[9])
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
relax.op.strided_slice(x, axes=[1], begin=[0], end=[])
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
relax.op.strided_slice(x, axes=[1], begin=[0], end=[9], strides=[])
@@ -698,9 +698,9 @@ def test_strided_slice_infer_ty_wrong_input_type():
x0 = relax.Var("x", relax.ShapeType((8, 9)))
x1 = relax.Var("x", relax.FuncType([], R.Tensor((8, 9), "float32")))
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
bb.normalize(relax.op.strided_slice(x0, axes=[0], begin=[0], end=[8]))
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
bb.normalize(relax.op.strided_slice(x1, axes=[0], begin=[0], end=[8]))
@@ -873,7 +873,7 @@ def test_dynamic_strided_slice_infer_ty_arg_wrong_dtype():
e0 = relax.Var("end", R.Tensor((4,), "float32"))
s0 = relax.Var("stride", R.Tensor((4,), "float32"))
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
bb.normalize(relax.op.strided_slice(x0, b0, e0, s0))
@@ -890,13 +890,13 @@ def test_dynamic_strided_slice_infer_ty_arg_wrong_shape_info():
e0 = relax.Var("end", R.Tensor((4,), "int64"))
s0 = relax.Var("stride", R.Tensor((4,), "int64"))
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
bb.normalize(relax.op.strided_slice(x0, b0, e0, s0))
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
bb.normalize(relax.op.strided_slice(x0, b1, e0, s0))
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
bb.normalize(relax.op.strided_slice(x0, b2, e0, s0))
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
bb.normalize(relax.op.strided_slice(x0, b3, e0, s0))
diff --git a/tests/python/relax/test_op_manipulate.py b/tests/python/relax/test_op_manipulate.py
index 42897a58b6..137778c4ea 100644
--- a/tests/python/relax/test_op_manipulate.py
+++ b/tests/python/relax/test_op_manipulate.py
@@ -239,13 +239,13 @@ def test_reshape_infer_ty_inference_not_deducible():
x2 = relax.Var("x", relax.TensorType(s0, "float32"))
x3 = relax.Var("x", relax.TensorType(s1, "float32"))
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
bb.normalize(relax.op.reshape(x0, (2, 3, -1)))
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
bb.normalize(relax.op.reshape(x1, (2, 3, -1)))
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
bb.normalize(relax.op.reshape(x2, (2, 3, -1)))
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
bb.normalize(relax.op.reshape(x3, (2, 3, -1)))
@@ -260,11 +260,11 @@ def test_reshape_infer_ty_new_shape_not_integer():
bb = relax.BlockBuilder()
x = relax.Var("x", R.Tensor((2, 3, 4, 5), "float32"))
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
bb.normalize(relax.op.reshape(x, (2.0, 3, 4, 5)))
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
bb.normalize(relax.op.reshape(x, (2, 3, -1.0)))
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
bb.normalize(relax.op.reshape(x, (2, 3, 4.0, -1)))
@@ -272,9 +272,9 @@ def test_reshape_infer_ty_multiple_dim_inference():
bb = relax.BlockBuilder()
x = relax.Var("x", R.Tensor((2, 3, 4, 5), "float32"))
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
bb.normalize(relax.op.reshape(x, (2, -1, -1, 5)))
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
bb.normalize(relax.op.reshape(x, (-1, -1, -1, -1)))
@@ -282,7 +282,7 @@ def test_reshape_infer_ty_non_positive_new_shape():
bb = relax.BlockBuilder()
x = relax.Var("x", R.Tensor((2, 3, 4, 5), "float32"))
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
bb.normalize(relax.op.reshape(x, (-2, -3, -4, -5)))
@@ -433,9 +433,9 @@ def test_permute_dims_infer_ty_unknown_ndim_with_axes():
x0 = relax.Var("x", R.Tensor("float32"))
x1 = relax.Var("x", relax.TensorType(s, "float32"))
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
bb.normalize(relax.op.permute_dims(x0, [2, 3, 1, 0]))
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
bb.normalize(relax.op.permute_dims(x1, [2, 3, 1, 0]))
@@ -2199,9 +2199,9 @@ def test_split_invalid_n_section():
n = tirx.Var("n", "int64")
x = relax.Var("x", R.Tensor((3, 4), "float32"))
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
relax.op.split(x, 0, axis=1)
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
relax.op.split(x, -1, axis=1)
with pytest.raises(TypeError):
relax.op.split(x, n, axis=1)
@@ -3497,7 +3497,7 @@ def test_one_hot_infer_ty():
# Test case 5: With different on_value and off_value dtypes
i3 = relax.Var("indices", R.Tensor((2, 3), "int32"))
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
bb.normalize(
relax.op.one_hot(
i3,
@@ -3521,7 +3521,7 @@ def test_one_hot_infer_ty():
# Test case 7: With invalid depth
i5 = relax.Var("indices", R.Tensor((2, 3), "int32"))
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
bb.normalize(
relax.op.one_hot(
i5,
diff --git a/tests/python/relax/test_op_nn.py b/tests/python/relax/test_op_nn.py
index 7c1d0ac1ef..36eb983b1e 100644
--- a/tests/python/relax/test_op_nn.py
+++ b/tests/python/relax/test_op_nn.py
@@ -1771,7 +1771,7 @@ def test_nll_loss_infer_ty_wrong_reduction():
y = relax.Var("x", R.Tensor((3, 10, 10), "int64"))
w = relax.Var("w", R.Tensor((5,), "float32"))
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
bb.normalize(relax.op.nn.nll_loss(x, y, w, reduction="foo"))
diff --git a/tests/python/relax/test_op_nn_convolution.py b/tests/python/relax/test_op_nn_convolution.py
index c720701f88..7552c928aa 100644
--- a/tests/python/relax/test_op_nn_convolution.py
+++ b/tests/python/relax/test_op_nn_convolution.py
@@ -279,9 +279,9 @@ def test_conv1d_non_positive_group():
x = relax.Var("x", R.Tensor((2, 128, 28), "float32"))
w = relax.Var("w", R.Tensor((48, 16, 3), "float32"))
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
relax.op.nn.conv1d(x, w, groups=0)
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
relax.op.nn.conv1d(x, w, groups=-2)
@@ -355,11 +355,11 @@ def test_conv1d_stride_padding_dilation_int64():
def test_conv1d_wrong_strides_padding_dilation_length():
x = relax.Var("x", R.Tensor((2, 3, 28), "float32"))
w = relax.Var("w", R.Tensor((4, 3, 3), "float32"))
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
relax.op.nn.conv1d(x, w, strides=(1, 2))
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
relax.op.nn.conv1d(x, w, padding=(1, 2, 3))
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
relax.op.nn.conv1d(x, w, dilation=(1, 2))
@@ -645,9 +645,9 @@ def test_conv1d_transpose_non_positive_group():
x = relax.Var("x", R.Tensor((2, 128, 28), "float32"))
w = relax.Var("w", R.Tensor((128, 16, 3), "float32"))
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
relax.op.nn.conv1d_transpose(x, w, groups=0)
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
relax.op.nn.conv1d_transpose(x, w, groups=-2)
@@ -709,11 +709,11 @@ def test_conv1d_transpose_stride_padding_dilation_int64():
def test_conv1d_transpose_wrong_strides_padding_dilation_length():
x = relax.Var("x", R.Tensor((2, 3, 28), "float32"))
w = relax.Var("w", R.Tensor((3, 4, 3), "float32"))
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
relax.op.nn.conv1d_transpose(x, w, strides=(1, 2))
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
relax.op.nn.conv1d_transpose(x, w, padding=(1, 2, 3))
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
relax.op.nn.conv1d_transpose(x, w, dilation=(1, 2))
@@ -1034,9 +1034,9 @@ def test_conv2d_non_positive_group():
x = relax.Var("x", R.Tensor((2, 128, 28, 28), "float32"))
w = relax.Var("w", R.Tensor((48, 16, 3, 3), "float32"))
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
relax.op.nn.conv2d(x, w, groups=0)
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
relax.op.nn.conv2d(x, w, groups=-2)
@@ -1114,11 +1114,11 @@ def test_conv2d_stride_padding_dilation_int64():
def test_conv2d_wrong_strides_padding_dilation_length():
x = relax.Var("x", R.Tensor((2, 3, 28, 28), "float32"))
w = relax.Var("w", R.Tensor((4, 3, 3, 3), "float32"))
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
relax.op.nn.conv2d(x, w, strides=(1, 2, 3))
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
relax.op.nn.conv2d(x, w, padding=(1, 2, 3))
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
relax.op.nn.conv2d(x, w, dilation=(1, 2, 3))
@@ -1425,9 +1425,9 @@ def test_conv2d_transpose_non_positive_group():
x = relax.Var("x", R.Tensor((2, 128, 28, 28), "float32"))
w = relax.Var("w", R.Tensor((128, 16, 3, 3), "float32"))
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
relax.op.nn.conv2d_transpose(x, w, groups=0)
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
relax.op.nn.conv2d_transpose(x, w, groups=-2)
@@ -1502,13 +1502,13 @@ def test_conv2d_transpose_stride_padding_dilation_int64():
def test_conv2d_transpose_wrong_strides_padding_dilation_length():
x = relax.Var("x", R.Tensor((2, 3, 28, 28), "float32"))
w = relax.Var("w", R.Tensor((3, 4, 3, 3), "float32"))
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
relax.op.nn.conv2d_transpose(x, w, strides=(1, 2, 3))
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
relax.op.nn.conv2d_transpose(x, w, padding=(1, 2, 3))
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
relax.op.nn.conv2d_transpose(x, w, output_padding=(1, 2, 3))
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
relax.op.nn.conv2d_transpose(x, w, dilation=(1, 2, 3))
diff --git a/tests/python/relax/test_op_nn_pooling.py b/tests/python/relax/test_op_nn_pooling.py
index da1fbe2898..5c26e97471 100644
--- a/tests/python/relax/test_op_nn_pooling.py
+++ b/tests/python/relax/test_op_nn_pooling.py
@@ -190,13 +190,13 @@ def test_max_pool1d_stride_padding_dilation_int64():
def test_max_pool1d_wrong_pool_size_strides_padding_dilation_length():
x = relax.Var("x", R.Tensor((2, 3, 28), "float32"))
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
relax.op.nn.max_pool1d(x, pool_size=(1, 2))
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
relax.op.nn.max_pool1d(x, strides=(1, 2))
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
relax.op.nn.max_pool1d(x, padding=(1, 2, 3))
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
relax.op.nn.max_pool1d(x, dilation=(1, 2))
@@ -413,13 +413,13 @@ def test_max_pool2d_stride_padding_dilation_int64():
def test_max_pool2d_wrong_pool_size_strides_padding_dilation_length():
x = relax.Var("x", R.Tensor((2, 3, 28, 28), "float32"))
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
relax.op.nn.max_pool2d(x, pool_size=(1, 2, 3))
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
relax.op.nn.max_pool2d(x, strides=(1, 2, 3))
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
relax.op.nn.max_pool2d(x, padding=(1, 2, 3))
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
relax.op.nn.max_pool2d(x, dilation=(1, 2, 3))
@@ -660,13 +660,13 @@ def test_max_pool3d_stride_padding_dilation_int64():
def test_max_pool3d_wrong_pool_size_strides_padding_dilation_length():
x = relax.Var("x", R.Tensor((2, 3, 28, 28, 28), "float32"))
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
relax.op.nn.max_pool3d(x, pool_size=(1, 2, 3, 4))
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
relax.op.nn.max_pool3d(x, strides=(1, 2, 3, 4))
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
relax.op.nn.max_pool3d(x, padding=(1, 2, 3, 4))
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
relax.op.nn.max_pool3d(x, dilation=(1, 2, 3, 4))
@@ -860,13 +860,13 @@ def test_avg_pool1d_stride_padding_dilation_int64():
def test_avg_pool1d_wrong_pool_size_strides_padding_dilation_length():
x = relax.Var("x", R.Tensor((2, 3, 28), "float32"))
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
relax.op.nn.avg_pool1d(x, pool_size=(1, 2))
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
relax.op.nn.avg_pool1d(x, strides=(1, 2))
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
relax.op.nn.avg_pool1d(x, padding=(1, 2, 3))
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
relax.op.nn.avg_pool1d(x, dilation=(1, 2))
@@ -1080,13 +1080,13 @@ def test_avg_pool2d_stride_padding_dilation_int64():
def test_avg_pool2d_wrong_pool_size_strides_padding_dilation_length():
x = relax.Var("x", R.Tensor((2, 3, 28, 28), "float32"))
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
relax.op.nn.avg_pool2d(x, pool_size=(1, 2, 3))
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
relax.op.nn.avg_pool2d(x, strides=(1, 2, 3))
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
relax.op.nn.avg_pool2d(x, padding=(1, 2, 3))
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
relax.op.nn.avg_pool2d(x, dilation=(1, 2, 3))
@@ -1326,13 +1326,13 @@ def test_avg_pool3d_stride_padding_dilation_int64():
def test_avg_pool3d_wrong_pool_size_strides_padding_dilation_length():
x = relax.Var("x", R.Tensor((2, 3, 28, 28, 28), "float32"))
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
relax.op.nn.avg_pool3d(x, pool_size=(1, 2, 3, 4))
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
relax.op.nn.avg_pool3d(x, strides=(1, 2, 3, 4))
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
relax.op.nn.avg_pool3d(x, padding=(1, 2, 3, 4))
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
relax.op.nn.avg_pool3d(x, dilation=(1, 2, 3, 4))
@@ -1475,7 +1475,7 @@ def test_adaptive_avg_pool1d_infer_ty_more_input_dtype():
def test_adaptive_avg_pool1d_wrong_output_size_ndim():
x = relax.Var("x", R.Tensor((2, 3, 64), "float32"))
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
relax.op.nn.adaptive_avg_pool1d(x, output_size=(32, 32))
@@ -1645,7 +1645,7 @@ def test_adaptive_avg_pool2d_infer_ty_more_input_dtype():
def test_adaptive_avg_pool2d_wrong_output_size_ndim():
x = relax.Var("x", R.Tensor((2, 3, 32, 32), "float32"))
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
relax.op.nn.adaptive_avg_pool2d(x, (32, 32, 32))
@@ -1830,7 +1830,7 @@ def test_adaptive_avg_pool3d_infer_ty_more_input_dtype():
def test_adaptive_avg_pool3d_wrong_output_size_ndim():
x = relax.Var("x", R.Tensor((2, 3, 32, 32, 32), "float32"))
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
relax.op.nn.adaptive_avg_pool3d(x, (32, 32, 32, 32))
diff --git a/tests/python/relax/test_relax_operators.py b/tests/python/relax/test_relax_operators.py
index 9781a98a08..a1cd7d2af0 100644
--- a/tests/python/relax/test_relax_operators.py
+++ b/tests/python/relax/test_relax_operators.py
@@ -722,7 +722,7 @@ def test_py_func_registry_is_scoped_to_its_module():
assert module_ref() is None, "the registry must not keep the module alive"
assert get_func("registry_probe") is not None, "another owner's function was dropped"
- with pytest.raises(tvm_tirx.error.InternalError, match="not found in registry"):
+ with pytest.raises(RuntimeError, match="not found in registry"):
get_func("registry_owned")
tvm_tirx.get_global_func("vm.builtin.unregister_py_func")("registry_probe")
diff --git a/tests/python/relax/test_runtime_builtin_paged_attention_kv_cache_metadata.py b/tests/python/relax/test_runtime_builtin_paged_attention_kv_cache_metadata.py
index 0c4d4d625a..8217c7684e 100644
--- a/tests/python/relax/test_runtime_builtin_paged_attention_kv_cache_metadata.py
+++ b/tests/python/relax/test_runtime_builtin_paged_attention_kv_cache_metadata.py
@@ -23,7 +23,6 @@ from tvm_ffi import Shape
import tvm_tirx
import tvm_tirx.testing
from tvm.relax.frontend.nn.llm.kv_cache import AttnKind, RopeMode
-from tvm_tirx.error import InternalError
reserved_nseq = 4
maximum_total_seq_length = 128
@@ -170,7 +169,7 @@ def test_checkpoint_metadata_reports_layout_pages_and_groups():
prefill_chunk_size_value=prefill_chunk_size // 2,
)
fprepare_import(import_cache, 0, metadata_json)
- with pytest.raises(InternalError, match="until checkpoint import is finished"):
+ with pytest.raises(RuntimeError, match="until checkpoint import is finished"):
fget_sequence_length(import_cache, 0)
for group_metadata, group in zip(metadata["groups"], exported_groups):
fimport_page_group(import_cache, 0, group_metadata["group_index"], group)
@@ -223,21 +222,21 @@ def test_checkpoint_metadata_rejects_unsupported_layouts_and_sequence_ids():
(1, 1, 2, num_kv_heads, page_size, head_dim), "float16", device=device
)
- with pytest.raises(InternalError, match="sliding-window"):
+ with pytest.raises(RuntimeError, match="sliding-window"):
fget_layout_hash(sliding_cache)
- with pytest.raises(InternalError, match="sliding-window"):
+ with pytest.raises(RuntimeError, match="sliding-window"):
fget_checkpoint_metadata(sliding_cache, 0)
- with pytest.raises(InternalError, match="sliding-window"):
+ with pytest.raises(RuntimeError, match="sliding-window"):
fexport_page_group(sliding_cache, 0, 0, dst)
- with pytest.raises(InternalError, match="sequence id 0"):
+ with pytest.raises(RuntimeError, match="sequence id 0"):
fget_checkpoint_metadata(create_kv_cache(), 1)
- with pytest.raises(InternalError, match="full-context MHA/GQA"):
+ with pytest.raises(RuntimeError, match="full-context MHA/GQA"):
fget_layout_hash(mla_cache)
- with pytest.raises(InternalError, match="full-context MHA/GQA"):
+ with pytest.raises(RuntimeError, match="full-context MHA/GQA"):
fexport_page_group(mla_cache, 0, 0, dst)
- with pytest.raises(InternalError, match="qk_head_dim to equal v_head_dim"):
+ with pytest.raises(RuntimeError, match="qk_head_dim to equal v_head_dim"):
fget_layout_hash(asymmetric_cache)
- with pytest.raises(InternalError, match="RoPE extension factors"):
+ with pytest.raises(RuntimeError, match="RoPE extension factors"):
fget_layout_hash(rope_ext_cache)
tree_cache = create_kv_cache()
@@ -245,7 +244,7 @@ def test_checkpoint_metadata_rejects_unsupported_layouts_and_sequence_ids():
tvm_tirx.get_global_func("vm.builtin.kv_state_begin_forward")(
tree_cache, Shape([0]), Shape([2]), Shape([-1, 0])
)
- with pytest.raises(InternalError, match="committed token-chain state"):
+ with pytest.raises(RuntimeError, match="committed token-chain state"):
fexport_page_group(tree_cache, 0, 0, dst)
@@ -260,7 +259,7 @@ def test_checkpoint_export_page_group_validates_group_shape():
metadata = json.loads(fget_checkpoint_metadata(kv_cache, 0))
shape = metadata["groups"][0]["shape"]
- with pytest.raises(InternalError, match="group id"):
+ with pytest.raises(RuntimeError, match="group id"):
fexport_page_group(
kv_cache,
0,
@@ -270,7 +269,7 @@ def test_checkpoint_export_page_group_validates_group_shape():
bad_shape = shape.copy()
bad_shape[-1] += 1
- with pytest.raises(InternalError, match="ExportPageGroup expects"):
+ with pytest.raises(RuntimeError, match="ExportPageGroup expects"):
fexport_page_group(
kv_cache,
0,
@@ -278,7 +277,7 @@ def test_checkpoint_export_page_group_validates_group_shape():
tvm_tirx.runtime.empty(tuple(bad_shape), "float16", device=device),
)
- with pytest.raises(InternalError, match="dtype mismatches"):
+ with pytest.raises(RuntimeError, match="dtype mismatches"):
fexport_page_group(
kv_cache,
0,
@@ -298,33 +297,33 @@ def test_checkpoint_prepare_import_validates_metadata():
metadata_json = fget_checkpoint_metadata(kv_cache, 0)
metadata = json.loads(metadata_json)
- with pytest.raises(InternalError, match="sequence id 0"):
+ with pytest.raises(RuntimeError, match="sequence id 0"):
fprepare_import(create_kv_cache(), 1, metadata_json)
- with pytest.raises(InternalError, match="dtype"):
+ with pytest.raises(RuntimeError, match="dtype"):
fprepare_import(create_kv_cache(dtype="float32"), 0, metadata_json)
bad_length = json.loads(metadata_json)
bad_length["seq_length"] = page_size * 2 + 1
- with pytest.raises(InternalError, match="sequence length"):
+ with pytest.raises(RuntimeError, match="sequence length"):
fprepare_import(create_kv_cache(), 0, json.dumps(bad_length))
bad_group = json.loads(metadata_json)
bad_group["groups"][0]["shape"][-1] += 1
- with pytest.raises(InternalError, match="shape"):
+ with pytest.raises(RuntimeError, match="shape"):
fprepare_import(create_kv_cache(), 0, json.dumps(bad_group))
bad_nbytes = json.loads(metadata_json)
bad_nbytes["groups"][0]["nbytes"] += 1
- with pytest.raises(InternalError, match="nbytes"):
+ with pytest.raises(RuntimeError, match="nbytes"):
fprepare_import(create_kv_cache(), 0, json.dumps(bad_nbytes))
bad_version = json.loads(metadata_json)
bad_version["format_version"] += 1
- with pytest.raises(InternalError, match="format_version"):
+ with pytest.raises(RuntimeError, match="format_version"):
fprepare_import(create_kv_cache(), 0, json.dumps(bad_version))
- with pytest.raises(InternalError, match="only has 1 pages"):
+ with pytest.raises(RuntimeError, match="only has 1 pages"):
fprepare_import(
create_kv_cache(maximum_total_seq_length_value=0),
0,
@@ -332,7 +331,7 @@ def test_checkpoint_prepare_import_validates_metadata():
)
metadata["layout_hash"] = "bad-layout-hash"
- with pytest.raises(InternalError, match="layout hash mismatch"):
+ with pytest.raises(RuntimeError, match="layout hash mismatch"):
fprepare_import(create_kv_cache(), 0, json.dumps(metadata))
@@ -352,7 +351,7 @@ def test_checkpoint_import_page_group_validates_group_shape():
import_cache = create_kv_cache()
fprepare_import(import_cache, 0, metadata_json)
- with pytest.raises(InternalError, match="group id"):
+ with pytest.raises(RuntimeError, match="group id"):
fimport_page_group(
import_cache,
0,
@@ -362,7 +361,7 @@ def test_checkpoint_import_page_group_validates_group_shape():
bad_shape = shape.copy()
bad_shape[-1] += 1
- with pytest.raises(InternalError, match="ImportPageGroup expects"):
+ with pytest.raises(RuntimeError, match="ImportPageGroup expects"):
fimport_page_group(
import_cache,
0,
@@ -370,7 +369,7 @@ def test_checkpoint_import_page_group_validates_group_shape():
tvm_tirx.runtime.empty(tuple(bad_shape), "float16", device=device),
)
- with pytest.raises(InternalError, match="dtype mismatches"):
+ with pytest.raises(RuntimeError, match="dtype mismatches"):
fimport_page_group(
import_cache,
0,
@@ -403,17 +402,17 @@ def test_checkpoint_import_requires_all_groups_and_explicit_finish():
fprepare_import(import_cache, 0, metadata_json)
fimport_page_group(import_cache, 0, 0, groups[0])
- with pytest.raises(InternalError, match="already imported"):
+ with pytest.raises(RuntimeError, match="already imported"):
fimport_page_group(import_cache, 0, 0, groups[0])
- with pytest.raises(InternalError, match="missing group 1"):
+ with pytest.raises(RuntimeError, match="missing group 1"):
ffinish_import(import_cache, 0)
- with pytest.raises(InternalError, match="before checkpoint import is finished"):
+ with pytest.raises(RuntimeError, match="before checkpoint import is finished"):
fbegin_forward(import_cache, Shape([0]), Shape([1]), None)
for group_id in range(1, num_layers):
fimport_page_group(import_cache, 0, group_id, groups[group_id])
ffinish_import(import_cache, 0)
- with pytest.raises(InternalError, match="has not been prepared"):
+ with pytest.raises(RuntimeError, match="has not been prepared"):
ffinish_import(import_cache, 0)
diff --git a/tests/python/relax/test_tensorrt_engine_serialization.py b/tests/python/relax/test_tensorrt_engine_serialization.py
index c1b1641998..6769a55794 100644
--- a/tests/python/relax/test_tensorrt_engine_serialization.py
+++ b/tests/python/relax/test_tensorrt_engine_serialization.py
@@ -170,7 +170,7 @@ def test_eager_requires_runtime():
)
def test_reject_malformed_engine_trailer(trailer, message):
module = _external_modules(_codegen(_relu_partition()))[0]
- with pytest.raises(tvm_tirx.error.InternalError, match=message):
+ with pytest.raises(RuntimeError, match=message):
_load_bytes(_legacy_bytes(module) + trailer)
@@ -186,7 +186,7 @@ def test_eager_requires_static_positive_dimensions(batch):
def test_eager_rejects_int8_calibration(monkeypatch):
monkeypatch.setenv("TVM_TENSORRT_USE_INT8", "1")
monkeypatch.setenv("TENSORRT_NUM_CALI_INT8", "1")
- with pytest.raises(tvm_tirx.error.InternalError, match="INT8 calibration"):
+ with pytest.raises(RuntimeError, match="INT8 calibration"):
_codegen(_relu_partition(), eager=True)
@@ -267,7 +267,7 @@ def test_failed_engine_build_can_be_retried():
def check():
for _ in range(2):
- with pytest.raises(tvm_tirx.error.InternalError, match="Unsupported operator"):
+ with pytest.raises(RuntimeError, match="Unsupported operator"):
failing["build_engine"](constants)
assert _module_bytes(failing) == legacy
assert _module_bytes(_load_bytes(legacy)) == legacy
@@ -396,9 +396,7 @@ def test_exported_engines_run_without_builder(
calibration.setenv("TVM_TENSORRT_USE_INT8", use_int8)
calibration.setenv("TENSORRT_NUM_CALI_INT8", "1")
loaded = _load_bytes(_module_bytes(module))
- with pytest.raises(
- tvm_tirx.error.InternalError, match="prebuilt TensorRT.*INT8 calibration"
- ):
+ with pytest.raises(RuntimeError, match="prebuilt TensorRT.*INT8 calibration"):
loaded["__init_" + loaded["get_symbol"]()](constants)
# A corrupt plan must fail deserialization instead of rebuilding from the JSON.
@@ -412,9 +410,7 @@ def test_exported_engines_run_without_builder(
device = tvm_tirx.cpu() if execution_device == "cpu" else tvm_tirx.cuda(device_id)
argument = tvm_tirx.runtime.tensor(np.zeros(data.shape[1:], dtype=dtype), device)
output = tvm_tirx.runtime.tensor(np.zeros(expected.shape[1:], dtype=dtype), device)
- with pytest.raises(
- tvm_tirx.error.InternalError, match="deserialize the embedded TensorRT engine"
- ):
+ with pytest.raises(RuntimeError, match="deserialize the embedded TensorRT engine"):
corrupt[symbol](argument, output)
tvm_tirx.testing.run_with_gpu_lock(check)
diff --git a/tests/python/relax/test_transform.py b/tests/python/relax/test_transform.py
index 66c8ec4738..1481678359 100644
--- a/tests/python/relax/test_transform.py
+++ b/tests/python/relax/test_transform.py
@@ -55,7 +55,7 @@ def test_dataflowblock_pass_rejects_deleting_binding_role_of_symbolic_var():
def delete_ordinary_binding(block, _mod, _ctx):
return relax.DataflowBlock([block.bindings[1]])
- with pytest.raises(tvm_tirx.error.InternalError, match="global-scope Var"):
+ with pytest.raises(RuntimeError, match="global-scope Var"):
delete_ordinary_binding(mod)
@@ -74,7 +74,7 @@ def test_dataflowblock_pass_rejects_rewriting_match_cast_role_of_binding_var():
)
return relax.DataflowBlock([block.bindings[0], new_match_cast])
- with pytest.raises(tvm_tirx.error.InternalError, match="symbolic Var declared by a MatchCast"):
+ with pytest.raises(RuntimeError, match="symbolic Var declared by a MatchCast"):
rewrite_match_cast_symbol(mod)
diff --git a/tests/python/relax/test_transform_error_enrichment.py b/tests/python/relax/test_transform_error_enrichment.py
index 3606823b34..1cb8f6667b 100644
--- a/tests/python/relax/test_transform_error_enrichment.py
+++ b/tests/python/relax/test_transform_error_enrichment.py
@@ -93,10 +93,10 @@ def test_error_without_resolvable_node_is_not_masked():
class ThrowUnresolvable:
def transform_module(self, mod, ctx):
# A bare error with no VisitErrorContext payload -> nothing to resolve.
- raise tvm_tirx.error.InternalError("deliberate failure with no resolvable location")
+ raise RuntimeError("deliberate failure with no resolvable location")
mod = _bad_matmul_module()
- with pytest.raises(tvm_tirx.error.InternalError) as excinfo:
+ with pytest.raises(RuntimeError) as excinfo:
ThrowUnresolvable()(mod)
msg = str(excinfo.value)
assert "deliberate failure with no resolvable location" in msg
diff --git a/tests/python/relax/test_vm_build.py b/tests/python/relax/test_vm_build.py
index a4f097bf99..33025c8f65 100644
--- a/tests/python/relax/test_vm_build.py
+++ b/tests/python/relax/test_vm_build.py
@@ -102,7 +102,7 @@ def test_vm_compile_unlowered_operator_error():
mod = relax.transform.LegalizeOps()(Conv2dTranspose)
with pytest.raises(
- tvm_tirx.error.InternalError,
+ RuntimeError,
match=r"(?s)Offending call:.*(?:R|relax)\.nn\.conv2d_transpose.*data_layout.*NHWC",
):
relax.build(mod, target="llvm")
diff --git a/tests/python/runtime/rpc/test_runtime_rpc.py b/tests/python/runtime/rpc/test_runtime_rpc.py
index 73929d702d..9da61daa38 100644
--- a/tests/python/runtime/rpc/test_runtime_rpc.py
+++ b/tests/python/runtime/rpc/test_runtime_rpc.py
@@ -361,7 +361,7 @@ def test_rpc_session_constructor_args():
assert nd.numpy()[1] == 2
def check_error_handling():
- with pytest.raises(tvm_tirx.error.RPCError):
+ with pytest.raises(RuntimeError):
client = rpc.connect(
"127.0.0.1",
server0.port,
@@ -655,7 +655,7 @@ def test_rpc_session_timeout_error(with_proxy):
rpc_sess = rpc.connect_tracker(*tracker_addr).request(key="x1", session_timeout=5)
f1 = rpc_sess.get_function("rpc.test.addone")
time.sleep(6)
- with pytest.raises(tvm_tirx.error.RPCSessionTimeoutError):
+ with pytest.raises(RuntimeError):
f1(10)
finally:
server.terminate()
diff --git a/tests/python/s_tir/analysis/test_s_tir_analysis_verify_block_scope.py b/tests/python/s_tir/analysis/test_s_tir_analysis_verify_block_scope.py
index dcb8519598..2a4329e570 100644
--- a/tests/python/s_tir/analysis/test_s_tir_analysis_verify_block_scope.py
+++ b/tests/python/s_tir/analysis/test_s_tir_analysis_verify_block_scope.py
@@ -152,7 +152,5 @@ def test_error_undeclared_tensor_in_schedulable_tir():
)
# B is used in the block but was never declared — should fail.
- with pytest.raises(
- (ValueError, tvm_tirx.error.InternalError), match="tensor B.*without a prior DeclTensor"
- ):
+ with pytest.raises((ValueError, RuntimeError), match="tensor B.*without a prior DeclTensor"):
tvm.s_tir.analysis.verify_well_formed(function)
diff --git a/tests/python/s_tir/base/test_tir_data_layout.py b/tests/python/s_tir/base/test_tir_data_layout.py
index 6016dd338e..dc7736dcb7 100644
--- a/tests/python/s_tir/base/test_tir_data_layout.py
+++ b/tests/python/s_tir/base/test_tir_data_layout.py
@@ -22,7 +22,6 @@ import tvm
import tvm_tirx
import tvm_tirx.testing
from tvm.topi.utils import get_const_tuple
-from tvm_tirx.error import InternalError
def test_layout():
@@ -86,15 +85,15 @@ def test_layout():
assert layout[3] == "W"
assert layout[4] == "4o4i"
- with pytest.raises(InternalError):
+ with pytest.raises(RuntimeError):
layout = tvm.s_tir.slayout("[N4o]C")
- with pytest.raises(InternalError):
+ with pytest.raises(RuntimeError):
layout = tvm.s_tir.slayout("[O4o]")
- with pytest.raises(InternalError):
+ with pytest.raises(RuntimeError):
layout = tvm.s_tir.slayout("C4o")
- with pytest.raises(InternalError):
+ with pytest.raises(RuntimeError):
layout = tvm.s_tir.slayout("OI[4o4i][]")
- with pytest.raises(InternalError):
+ with pytest.raises(RuntimeError):
layout = tvm.s_tir.slayout("C4c[4c]")
diff --git a/tests/python/s_tir/meta_schedule/test_meta_schedule_trace_apply.py b/tests/python/s_tir/meta_schedule/test_meta_schedule_trace_apply.py
index ee1d4dc931..e08d3271a2 100644
--- a/tests/python/s_tir/meta_schedule/test_meta_schedule_trace_apply.py
+++ b/tests/python/s_tir/meta_schedule/test_meta_schedule_trace_apply.py
@@ -24,7 +24,7 @@ import tvm_tirx.testing
from tvm.s_tir import Schedule
from tvm.s_tir import script as Ts
from tvm.s_tir.tensor_intrin.x86 import VNNI_DOT_16x4_INTRIN as VNNI_INTRIN
-from tvm_tirx.codegen import llvm_lookup_intrinsic_id
+from tvm_tirx.codegen import llvm
from tvm_tirx.script import tirx as T
from tvm_tirx.target import Target
from tvm_tirx.tirx import floordiv, floormod
@@ -2178,7 +2178,7 @@ def test_conv2d_int8_vnni():
sch.unannotate(block_or_loop=b194, ann_key="meta_schedule.auto_tensorize")
sch.tensorize(block_or_loop=b194, tensor_intrin=VNNI_INTRIN)
- vnni_id = llvm_lookup_intrinsic_id("llvm.x86.avx512.vpdpbusd.512")
+ vnni_id = llvm.lookup_intrinsic_id("llvm.x86.avx512.vpdpbusd.512")
verify(
Conv2dInt8_NCHWc,
apply_trace,
diff --git a/tests/python/s_tir/script/test_s_tir_script_error_handling.py b/tests/python/s_tir/script/test_s_tir_script_error_handling.py
index 0be874eeea..3ec3f14cd4 100644
--- a/tests/python/s_tir/script/test_s_tir_script_error_handling.py
+++ b/tests/python/s_tir/script/test_s_tir_script_error_handling.py
@@ -133,8 +133,8 @@ def test_inconsistent_binding():
vi, vj = Ts.axis.remap("S", [i, j]) # error
T.evaluate(1.0)
- check_error(inconsistent_binding_value, 3, tvm_tirx.error.InternalError)
- check_error(inconsistent_binding_type, 3, tvm_tirx.error.InternalError)
+ check_error(inconsistent_binding_value, 3, RuntimeError)
+ check_error(inconsistent_binding_type, 3, RuntimeError)
def test_error_remap_args():
@@ -150,8 +150,8 @@ def test_error_remap_args():
vi, vj = Ts.axis.remap("SS", [i + j, j]) # error
T.evaluate(1.0)
- check_error(error_remap_type, 4, tvm_tirx.error.InternalError)
- check_error(error_remap_value, 4, tvm_tirx.error.InternalError)
+ check_error(error_remap_type, 4, RuntimeError)
+ check_error(error_remap_value, 4, RuntimeError)
def test_invalid_block_axes():
@@ -295,15 +295,15 @@ def test_duplicate_block_signature():
Ts.sblock_attr({"key1": "block2"}) # error
T.evaluate(1.0)
- check_error(duplicate_reads, 7, tvm_tirx.error.InternalError)
- check_error(duplicate_writes, 7, tvm_tirx.error.InternalError)
- check_error(duplicate_predicate, 6, tvm_tirx.error.InternalError)
+ check_error(duplicate_reads, 7, RuntimeError)
+ check_error(duplicate_writes, 7, RuntimeError)
+ check_error(duplicate_predicate, 6, RuntimeError)
check_error(duplicate_init, 7, ValueError)
parsed = duplicate_axes
axes = parsed.body[0].block.body[0].body[0].body[0].block.iter_vars
assert len(axes) == 3
assert not axes[0].var.same_as(axes[2].var)
- check_error(duplicate_sblock_attrs_with_same_key_diff_value, 6, tvm_tirx.error.InternalError)
+ check_error(duplicate_sblock_attrs_with_same_key_diff_value, 6, RuntimeError)
def test_opaque_access_during_complete():
@@ -346,14 +346,14 @@ def test_tvm_exception_catch_from_bare_intrin():
def intrin_except_unassign(A: T.Tensor((16, 16), "float32")) -> None:
T.evaluate(A) # error
- check_error(intrin_except_unassign, 2, tvm_tirx.error.InternalError)
+ check_error(intrin_except_unassign, 2, RuntimeError)
def test_tvm_exception_catch_from_assigned_intrin():
def intrin_except_assign(A: T.Tensor((16, 16), "float32")) -> None:
A[0, 0] = A[A] # error
- check_error(intrin_except_assign, 2, tvm_tirx.error.InternalError)
+ check_error(intrin_except_assign, 2, RuntimeError)
def test_match_tensor_shape_mismatch():
@@ -368,7 +368,7 @@ def test_match_tensor_shape_mismatch():
for jj in range(0, 4):
sub_A[i, j * 4 + jj] = 1
- check_error(tensor_shape_mismatch, 6, tvm_tirx.error.InternalError)
+ check_error(tensor_shape_mismatch, 6, RuntimeError)
def test_high_dim_store():
@@ -378,7 +378,7 @@ def test_high_dim_store():
for i, j in T.grid(16, 16):
B[i, j] = 1.0 # error: Store is only allowed with one index
- check_error(high_dim_store, 5, tvm_tirx.error.InternalError)
+ check_error(high_dim_store, 5, RuntimeError)
def test_block_has_option_vars():
@@ -412,9 +412,9 @@ def test_implicit_root_has_attrs():
check_error(implicit_root_has_read, 2, ValueError)
check_error(implicit_root_has_write, 2, ValueError)
- check_error(implicit_root_has_attrs, 2, tvm_tirx.error.InternalError)
+ check_error(implicit_root_has_attrs, 2, RuntimeError)
check_error(implicit_root_has_predicate, 2, ValueError)
- check_error(implicit_root_has_axes, 2, tvm_tirx.error.InternalError)
+ check_error(implicit_root_has_axes, 2, RuntimeError)
@Ts.function
@@ -551,7 +551,7 @@ def test_non_integer_typed_block_iter():
with Ts.sblock():
i = Ts.axis.S(0.1, 0.1) # error IterVar requires an integer dtype
- check_error(non_integer_typed_block_iter, 3, tvm_tirx.error.InternalError)
+ check_error(non_integer_typed_block_iter, 3, RuntimeError)
def test_illegal_tensor_slice():
@@ -575,7 +575,7 @@ def test_illegal_tensor_slice():
T.evaluate(A[0:i:1]) # error
check_error(strided_tensor_region, 6, ValueError)
- check_error(access_reversed_slice, 4, tvm_tirx.error.InternalError)
+ check_error(access_reversed_slice, 4, RuntimeError)
check_error(access_non_const_slice_length, 5, TypeError)
@@ -605,7 +605,7 @@ def test_multi_line_error_report():
]
)
- with pytest.raises(tvm_tirx.error.InternalError) as caught:
+ with pytest.raises(RuntimeError) as caught:
from_source(source_code, extra_vars={"T": T, "Ts": Ts})
frames = [
frame
@@ -628,7 +628,7 @@ def test_multi_line_error_report():
def test_tir_func_private_manual_global_symbol_fail():
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
@Ts.function(private=True)
def matmul(
diff --git a/tests/python/s_tir/transform/test_s_tir_transform_canonicalize_loop.py b/tests/python/s_tir/transform/test_s_tir_transform_canonicalize_loop.py
index 1e9ba5f264..804b22bf26 100644
--- a/tests/python/s_tir/transform/test_s_tir_transform_canonicalize_loop.py
+++ b/tests/python/s_tir/transform/test_s_tir_transform_canonicalize_loop.py
@@ -71,7 +71,7 @@ def test_canonicalize_negative_step():
B[i] = A[i] + 1.0
mod = tvm_tirx.IRModule.from_expr(before)
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
mod = s_tir.transform.CanonicalizeLoop()(mod)
@@ -85,7 +85,7 @@ def test_canonicalize_dynamic_step():
B[i] = A[i] + 1.0
mod = tvm_tirx.IRModule.from_expr(before)
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
mod = s_tir.transform.CanonicalizeLoop()(mod)
diff --git a/tests/python/s_tir/transform/test_s_tir_transform_mma_tensor_layout.py b/tests/python/s_tir/transform/test_s_tir_transform_mma_tensor_layout.py
index 2ff814e5ea..a4d7f1d09e 100644
--- a/tests/python/s_tir/transform/test_s_tir_transform_mma_tensor_layout.py
+++ b/tests/python/s_tir/transform/test_s_tir_transform_mma_tensor_layout.py
@@ -36,7 +36,7 @@ def test_explicit_matrix_ab_access_is_rejected(scope, shape, access_kind):
block = s_tir.SBlock([], [], [], "root", body, alloc_tensors=[tensor])
func = tirx.Function([], s_tir.SBlockRealize([], True, block))
- with pytest.raises(tvm_tirx.error.InternalError, match=f"{scope}.*explicit"):
+ with pytest.raises(RuntimeError, match=f"{scope}.*explicit"):
s_tir.transform.TransformMmaTensorLayout()(tvm_tirx.IRModule.from_expr(func))
diff --git a/tests/python/s_tir/transform/test_s_tir_transform_thread_sync.py b/tests/python/s_tir/transform/test_s_tir_transform_thread_sync.py
index 67b047520e..7f9f645dce 100644
--- a/tests/python/s_tir/transform/test_s_tir_transform_thread_sync.py
+++ b/tests/python/s_tir/transform/test_s_tir_transform_thread_sync.py
@@ -96,7 +96,7 @@ def test_sync_inside_condition():
for i, j in T.grid(4, 4):
A[i, j] = A_shared[i, j] + 1.0
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
s_tir.transform.ThreadSync("shared")(tvm_tirx.IRModule.from_expr(func1))
for func in (func2, func3):
diff --git a/tests/python/te/test_te_create_function.py b/tests/python/te/test_te_create_function.py
index 703bd11e00..e0c7c0f9d6 100644
--- a/tests/python/te/test_te_create_function.py
+++ b/tests/python/te/test_te_create_function.py
@@ -387,7 +387,7 @@ def test_error_reporting():
try:
te.create_function(te_scan())
assert False
- except (TypeError, tvm_tirx.error.InternalError) as e:
+ except (TypeError, RuntimeError) as e:
error_message = str(e)
assert error_message.find("Unsupported Operation: te.ScanOp.") != -1
return
diff --git a/tirx/CMakeLists.txt b/tirx/CMakeLists.txt
index 4001e955d9..d2581b2b5f 100644
--- a/tirx/CMakeLists.txt
+++ b/tirx/CMakeLists.txt
@@ -292,14 +292,19 @@ install(TARGETS tvm_tirx_header tvm_tirx_compiler tvm_runtime tvm_runtime_static
# CMake package and dependency helpers
install(FILES "${CMAKE_CURRENT_SOURCE_DIR}/cmake/tvm_tirx-config.cmake"
"${CMAKE_CURRENT_SOURCE_DIR}/python/tvm_tirx/config.py"
+ "${CMAKE_CURRENT_SOURCE_DIR}/python/tvm_tirx/libinfo.py"
DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/tvm_tirx" COMPONENT tvm_tirx)
install(DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/cmake/utils/"
DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/tvm_tirx/utils"
COMPONENT tvm_tirx FILES_MATCHING PATTERN "Find*.cmake")
if(NOT TVM_TIRX_BUILD_PYTHON_MODULE)
- install(PROGRAMS "${CMAKE_CURRENT_SOURCE_DIR}/python/tvm_tirx/config.py"
- DESTINATION "${CMAKE_INSTALL_BINDIR}" RENAME tvm-tirx-config COMPONENT tvm_tirx)
+ file(RELATIVE_PATH TVM_TIRX_CONFIG_PREFIX_RELATIVE
+ "${CMAKE_INSTALL_FULL_BINDIR}" "${CMAKE_INSTALL_PREFIX}")
+ configure_file("${CMAKE_CURRENT_SOURCE_DIR}/cmake/tvm-tirx-config.in"
+ "${CMAKE_CURRENT_BINARY_DIR}/tvm-tirx-config" @ONLY)
+ install(PROGRAMS "${CMAKE_CURRENT_BINARY_DIR}/tvm-tirx-config"
+ DESTINATION "${CMAKE_INSTALL_BINDIR}" COMPONENT tvm_tirx)
endif()
# Python package artifacts and licenses
diff --git a/tirx/python/tvm_tirx/tirx/backend/__init__.py b/tirx/cmake/tvm-tirx-config.in
similarity index 69%
rename from tirx/python/tvm_tirx/tirx/backend/__init__.py
rename to tirx/cmake/tvm-tirx-config.in
index 6f5333629f..ebe607d13e 100644
--- a/tirx/python/tvm_tirx/tirx/backend/__init__.py
+++ b/tirx/cmake/tvm-tirx-config.in
@@ -1,3 +1,4 @@
+#!/usr/bin/env python3
# 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
@@ -14,4 +15,11 @@
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
-"""TIRx backend compatibility package."""
+"""Run the configuration helper installed with the native CMake package."""
+
+import runpy
+from pathlib import Path
+
+prefix = (Path(__file__).resolve().parent / "@TVM_TIRX_CONFIG_PREFIX_RELATIVE@").resolve()
+config = runpy.run_path(str(prefix / "@CMAKE_INSTALL_LIBDIR@" / "cmake/tvm_tirx/config.py"))
+config["__main__"]()
diff --git a/tirx/pyproject.toml b/tirx/pyproject.toml
index 4ef79dcb0c..333c1e8696 100644
--- a/tirx/pyproject.toml
+++ b/tirx/pyproject.toml
@@ -143,7 +143,7 @@ markers = [
skip = "*-win32 *-manylinux_i686 *-musllinux*"
build-verbosity = 1
test-requires = ["pytest", "numpy"]
-test-command = "python -I -c \"import importlib.util; assert importlib.util.find_spec('tvm') is None\" && python -I -m pytest -vvs {package}/tests/python/all-platform-minimal-test {package}/tests/python/runtime/test_tensor.py {package}/tests/python/ir/test_type.py {package}/tests/python/script/test_ir_builder.py {package}/tests/python/codegen/llvm/test_basic.py::test_llvm_vadd_pipeline {package}/tests/python/codegen/gpu_common/test_allreduce.py::test_allreduce_sum_compile"
+test-command = "python -I -c \"import importlib.util; assert importlib.util.find_spec('tvm') is None\" && python -I -m pytest -vvs {package}/tests/python/runtime/test_validate_wheel_library.py {package}/tests/python/runtime/test_tensor.py {package}/tests/python/ir/test_type.py {package}/tests/python/script/test_ir_builder.py {package}/tests/python/codegen/llvm/test_basic.py::test_llvm_vadd_pipeline {package}/tests/python/codegen/gpu_common/test_allreduce.py::test_allreduce_sum_compile"
[tool.cibuildwheel.linux]
repair-wheel-command = "auditwheel repair --exclude libtvm_ffi.so --exclude libtvm_runtime_cuda.so --exclude 'libcuda.so.*' --exclude 'libcudart.so.*' --exclude 'libnvrtc.so.*' --exclude 'libnvrtc-builtins.so.*' -w {dest_dir} {wheel}"
diff --git a/tirx/python/tvm_tirx/__init__.py b/tirx/python/tvm_tirx/__init__.py
index fcdeb1f0bd..8244906d9c 100644
--- a/tirx/python/tvm_tirx/__init__.py
+++ b/tirx/python/tvm_tirx/__init__.py
@@ -49,9 +49,6 @@ if TYPE_CHECKING or not _is_config_mode():
from .runtime._tensor import vpi, rocm, ext_dev, hexagon
from .runtime import DataType, DataTypeCode
- # tvm.error
- from . import error
-
# tvm.ir
from .ir import IRModule, transform
from . import ir
@@ -83,35 +80,12 @@ if TYPE_CHECKING or not _is_config_mode():
# Side-effect imports: register CUDA/ROCm FFI callbacks at TVM startup
from .support import rocm as _rocm, nvcc as _nvcc
- # NOTE: This file should be python2 compatible so we can
- # raise proper error message when user run the package using
- # an older version of the python
-
- def _should_print_backtrace():
- in_pytest = "PYTEST_CURRENT_TEST" in os.environ
- tvm_backtrace = os.environ.get("TVM_BACKTRACE", "0")
-
- try:
- tvm_backtrace = bool(int(tvm_backtrace))
- except ValueError:
- raise ValueError(
- f"invalid value for TVM_BACKTRACE {tvm_backtrace}, please set to 0 or 1."
- )
-
- return in_pytest or tvm_backtrace
-
def tvm_wrap_excepthook(exception_hook):
"""Wrap given excepthook with TVM additional work."""
def wrapper(exctype, value, trbk):
"""Clean subprocesses when TVM is interrupted."""
- if exctype is error.DiagnosticError and not _should_print_backtrace():
- # TODO(@jroesch): consider moving to C++?
- print(
- "note: run with `TVM_BACKTRACE=1` environment variable to display a backtrace."
- )
- else:
- exception_hook(exctype, value, trbk)
+ exception_hook(exctype, value, trbk)
if hasattr(multiprocessing, "active_children"):
# pylint: disable=not-callable
diff --git a/tirx/python/tvm_tirx/backend/metal/target_tags.py b/tirx/python/tvm_tirx/backend/metal/target_tags.py
index 30f406c963..b1073c0e1e 100644
--- a/tirx/python/tvm_tirx/backend/metal/target_tags.py
+++ b/tirx/python/tvm_tirx/backend/metal/target_tags.py
@@ -23,9 +23,9 @@ _METAL_HOST_TRIPLE = "arm64-apple-macos"
def _register_metal_tag(name, max_threads, shared_mem, warp_size, mcpu):
try:
- from tvm_tirx.codegen import llvm_is_valid_cpu
+ from tvm_tirx.codegen import llvm
- if not llvm_is_valid_cpu(mcpu, _METAL_HOST_TRIPLE):
+ if not llvm.is_valid_cpu(mcpu, _METAL_HOST_TRIPLE):
return
except Exception: # pylint: disable=broad-except
pass # LLVM not available; register unconditionally
diff --git a/tirx/python/tvm_tirx/codegen/__init__.py b/tirx/python/tvm_tirx/codegen/__init__.py
index afc5fc7c3f..5396028ac1 100644
--- a/tirx/python/tvm_tirx/codegen/__init__.py
+++ b/tirx/python/tvm_tirx/codegen/__init__.py
@@ -20,6 +20,7 @@ from tvm_ffi import Array, get_global_func
from tvm_tirx.target import Target
+from . import llvm
from .executable import Executable, load_static_library
@@ -65,206 +66,3 @@ def target_has_features(cpu_features, target=None):
for feat in cpu_features:
has_feats &= get_global_func("codegen.target_has_feature")(feat, target)
return has_feats
-
-
-def llvm_lookup_intrinsic_id(name):
- """Lookup LLVM intrinsic id by name.
-
- Parameters
- ----------
- name : str
- The name of the intrinsic.
-
- Returns
- -------
- intrin_id : int
- The intrinsic id.
- """
- return get_global_func("codegen.llvm_lookup_intrinsic_id")(name)
-
-
-def llvm_get_intrinsic_name(intrin_id: int) -> str:
- """Get the name of an intrinsic for a given id.
-
- Parameters
- ----------
- intrin_id : int
- The id of the intrinsic.
-
- Returns
- -------
- name : str
- The name of the intrinsic.
- """
- return get_global_func("codegen.llvm_get_intrinsic_name")(intrin_id)
-
-
-def llvm_get_system_x86_vendor():
- """Get system x86 vendor info.
-
- Parameters
- ----------
-
- Returns
- -------
- vendor : str
- The current system's cpu vendor.
- """
- return get_global_func("codegen.llvm_get_system_x86_vendor")()
-
-
-def llvm_get_system_triple():
- """Get system host triple.
-
- Parameters
- ----------
-
- Returns
- -------
- triple : str
- The current system's triple.
- """
- return get_global_func("codegen.llvm_get_system_triple")()
-
-
-def llvm_get_system_cpu():
- """Get system host cpu name.
-
- Parameters
- ----------
-
- Returns
- -------
- cpu_name : str
- The current system's cpu name.
- """
- return get_global_func("codegen.llvm_get_system_cpu")()
-
-
-def llvm_get_targets():
- """Get LLVM target list.
-
- Parameters
- ----------
-
- Returns
- -------
- llvm_targets : list[str]
- List of available LLVM targets.
- """
- return get_global_func("codegen.llvm_get_targets")()
-
-
-def llvm_get_cpu_archlist(target=None):
- """Get CPU architectures for the target's `-mtriple`.
-
- Parameters
- ----------
- target : Target
- The TVM target.
-
- Returns
- -------
- cpu_archlist : list[str]
- List of available CPU architectures.
- """
- assert isinstance(target, Target) or target is None
- return get_global_func("codegen.llvm_get_cpu_archlist")(target)
-
-
-def llvm_get_cpu_features(target=None):
- """Get CPU features for the target's `-mtriple` and `-mcpu` and considering `-mattr`.
-
- Parameters
- ----------
- target : Target
- The TVM target.
-
- Returns
- -------
- cpu_features : list[str]
- List of available CPU features.
- """
- assert isinstance(target, Target) or target is None
- feature_map = get_global_func("codegen.llvm_get_cpu_features")(target)
- return set(feature_map.keys())
-
-
-def llvm_cpu_has_features(cpu_features, target=None):
- """Check CPU features for the target's `-mtriple` and `-mcpu` and considering `-mattr`.
-
- Parameters
- ----------
- target : Target
- The TVM target.
- cpu_features : str or Array
- CPU Feature(s) to check.
-
- Returns
- -------
- has_features : bool
- True if target CPU has the feature(s).
- """
- assert isinstance(target, Target) or target is None
- assert isinstance(cpu_features, Array | list | tuple | str)
- has_feats = True
- cpu_features = [cpu_features] if isinstance(cpu_features, str) else cpu_features
- for feat in cpu_features:
- has_feats &= get_global_func("codegen.llvm_cpu_has_feature")(feat, target)
- return has_feats
-
-
-def llvm_get_vector_width(target=None):
- """Get vector width from LLVM target's `-mtriple` and `-mcpu` and considering `-mattr`.
-
- Parameters
- ----------
- target : Target
- The TVM target.
-
- Returns
- -------
- vector_width : int
- Vector with of target in number of bits, -1 on error.
- """
- assert isinstance(target, Target) or target is None
- return get_global_func("codegen.llvm_get_vector_width")(target)
-
-
-def llvm_is_valid_cpu(cpu, triple):
- """Check if a CPU name is valid for the given LLVM triple.
-
- Parameters
- ----------
- cpu : str
- The CPU name to check (e.g. "apple-m1").
- triple : str
- The LLVM target triple (e.g. "arm64-apple-macos").
-
- Returns
- -------
- is_valid : bool
- True if the CPU name is recognized by LLVM for the given triple.
- """
- return get_global_func("codegen.llvm_is_valid_cpu")(cpu, triple)
-
-
-def llvm_version_major(allow_none=False):
- """Get the major LLVM version.
-
- Parameters
- ----------
- allow_none : bool
- Whether do we allow none.
-
- Returns
- -------
- major : int
- The major LLVM version.
- """
- try:
- return get_global_func("codegen.llvm_version_major")()
- except (ValueError, AttributeError):
- if allow_none:
- return None
- raise RuntimeError("LLVM version is not available, please check if you built TVM with LLVM")
diff --git a/tirx/python/tvm_tirx/codegen/__init__.py b/tirx/python/tvm_tirx/codegen/llvm.py
similarity index 75%
copy from tirx/python/tvm_tirx/codegen/__init__.py
copy to tirx/python/tvm_tirx/codegen/llvm.py
index afc5fc7c3f..8734fea963 100644
--- a/tirx/python/tvm_tirx/codegen/__init__.py
+++ b/tirx/python/tvm_tirx/codegen/llvm.py
@@ -14,60 +14,14 @@
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
-"""Code generation related functions."""
+"""LLVM code generation and target information."""
from tvm_ffi import Array, get_global_func
from tvm_tirx.target import Target
-from .executable import Executable, load_static_library
-
-def build_module(mod, target):
- """Build IRModule into Module.
-
- Parameters
- ----------
- mod : tvm_tirx.IRModule
- The ir module.
-
- target : str
- The target module type.
-
- Returns
- -------
- module : runtime.Module
- The corresponding module.
- """
- target = Target(target) if isinstance(target, str) else target
- return get_global_func("codegen.Build")(mod, target)
-
-
-def target_has_features(cpu_features, target=None):
- """Check CPU features for the target's `-mtriple` and `-mcpu` and `-mattr`.
-
- Parameters
- ----------
- target : Target
- The TVM target.
- cpu_features : str or Array
- CPU Feature(s) to check.
-
- Returns
- -------
- has_features : bool
- True if target has the feature(s).
- """
- assert isinstance(target, Target) or target is None
- assert isinstance(cpu_features, Array | list | tuple | str)
- has_feats = True
- cpu_features = [cpu_features] if isinstance(cpu_features, str) else cpu_features
- for feat in cpu_features:
- has_feats &= get_global_func("codegen.target_has_feature")(feat, target)
- return has_feats
-
-
-def llvm_lookup_intrinsic_id(name):
+def lookup_intrinsic_id(name):
"""Lookup LLVM intrinsic id by name.
Parameters
@@ -83,7 +37,7 @@ def llvm_lookup_intrinsic_id(name):
return get_global_func("codegen.llvm_lookup_intrinsic_id")(name)
-def llvm_get_intrinsic_name(intrin_id: int) -> str:
+def get_intrinsic_name(intrin_id: int) -> str:
"""Get the name of an intrinsic for a given id.
Parameters
@@ -99,7 +53,7 @@ def llvm_get_intrinsic_name(intrin_id: int) -> str:
return get_global_func("codegen.llvm_get_intrinsic_name")(intrin_id)
-def llvm_get_system_x86_vendor():
+def get_system_x86_vendor():
"""Get system x86 vendor info.
Parameters
@@ -113,7 +67,7 @@ def llvm_get_system_x86_vendor():
return get_global_func("codegen.llvm_get_system_x86_vendor")()
-def llvm_get_system_triple():
+def get_system_triple():
"""Get system host triple.
Parameters
@@ -127,7 +81,7 @@ def llvm_get_system_triple():
return get_global_func("codegen.llvm_get_system_triple")()
-def llvm_get_system_cpu():
+def get_system_cpu():
"""Get system host cpu name.
Parameters
@@ -141,7 +95,7 @@ def llvm_get_system_cpu():
return get_global_func("codegen.llvm_get_system_cpu")()
-def llvm_get_targets():
+def get_targets():
"""Get LLVM target list.
Parameters
@@ -155,7 +109,7 @@ def llvm_get_targets():
return get_global_func("codegen.llvm_get_targets")()
-def llvm_get_cpu_archlist(target=None):
+def get_cpu_archlist(target=None):
"""Get CPU architectures for the target's `-mtriple`.
Parameters
@@ -172,7 +126,7 @@ def llvm_get_cpu_archlist(target=None):
return get_global_func("codegen.llvm_get_cpu_archlist")(target)
-def llvm_get_cpu_features(target=None):
+def get_cpu_features(target=None):
"""Get CPU features for the target's `-mtriple` and `-mcpu` and considering `-mattr`.
Parameters
@@ -190,7 +144,7 @@ def llvm_get_cpu_features(target=None):
return set(feature_map.keys())
-def llvm_cpu_has_features(cpu_features, target=None):
+def cpu_has_features(cpu_features, target=None):
"""Check CPU features for the target's `-mtriple` and `-mcpu` and considering `-mattr`.
Parameters
@@ -214,7 +168,7 @@ def llvm_cpu_has_features(cpu_features, target=None):
return has_feats
-def llvm_get_vector_width(target=None):
+def get_vector_width(target=None):
"""Get vector width from LLVM target's `-mtriple` and `-mcpu` and considering `-mattr`.
Parameters
@@ -231,7 +185,7 @@ def llvm_get_vector_width(target=None):
return get_global_func("codegen.llvm_get_vector_width")(target)
-def llvm_is_valid_cpu(cpu, triple):
+def is_valid_cpu(cpu, triple):
"""Check if a CPU name is valid for the given LLVM triple.
Parameters
@@ -249,7 +203,7 @@ def llvm_is_valid_cpu(cpu, triple):
return get_global_func("codegen.llvm_is_valid_cpu")(cpu, triple)
-def llvm_version_major(allow_none=False):
+def version_major(allow_none=False):
"""Get the major LLVM version.
Parameters
diff --git a/tirx/python/tvm_tirx/config.py b/tirx/python/tvm_tirx/config.py
index 466a30fe14..da829bb6dc 100644
--- a/tirx/python/tvm_tirx/config.py
+++ b/tirx/python/tvm_tirx/config.py
@@ -22,88 +22,21 @@ there with an exact library directory, independently of Python package search.
"""
import argparse
-import importlib.machinery
import importlib.util
import json
-import os
import shlex
import sys
from pathlib import Path
-__version__ = "0.1.0a0"
-
-_LIBRARY_NAMES = ("tvm_tirx_compiler", "tvm_runtime")
-_COMPONENTS = {
- "compiler": "tvm_tirx_compiler",
- "runtime": "tvm_runtime",
- "cuda": "tvm_runtime_cuda",
- "metal": "tvm_runtime_metal",
- "opencl": "tvm_runtime_opencl",
- "vulkan": "tvm_runtime_vulkan",
- "rocm": "tvm_runtime_rocm",
-}
-
-
-def _find_prefix(start: Path) -> Path:
- for candidate in (start, *start.parents):
- if (candidate / "include/tvm/runtime/base.h").is_file():
- return candidate
- raise RuntimeError(f"Cannot find TIRx public headers above {start}")
-
-
-def _paths(prefix: Path | None, library_dir: Path | None) -> tuple[Path, Path]:
- explicit_prefix = prefix is not None
- if library_dir is not None:
- library_dir = library_dir.resolve()
- prefix = prefix.resolve() if prefix is not None else _find_prefix(library_dir)
- else:
- prefix = prefix.resolve() if prefix is not None else _find_prefix(Path(__file__).parent)
- library_dir = prefix / "lib"
- candidates = [prefix / "lib", prefix / "lib64", prefix / "build/lib"]
- if prefix.name == "tirx":
- candidates.append(prefix.parent / "build/lib")
- if not explicit_prefix and os.environ.get("TVM_TIRX_LIBRARY_PATH"):
- candidates.insert(0, Path(os.environ["TVM_TIRX_LIBRARY_PATH"]))
- for candidate in candidates:
- if all(
- any(
- (candidate / filename).is_file()
- for filename in (f"lib{name}.so", f"lib{name}.dylib", f"{name}.dll")
- )
- for name in ("tvm_runtime",)
- ):
- library_dir = candidate
- break
- if not (prefix / "include/tvm/runtime/base.h").is_file():
- raise RuntimeError(f"Cannot find TIRx public headers in {prefix / 'include'}")
- return prefix, library_dir
-
-
-def _libraries(library_dir: Path, platform: str, names=_LIBRARY_NAMES) -> dict[str, dict[str, str]]:
- libraries = {}
- windows = platform in ("Windows", "win32")
- apple = platform in ("Darwin", "iOS", "darwin")
- for name in names:
- if windows:
- filenames = (f"{name}.dll",)
- elif apple:
- filenames = (f"lib{name}.dylib", f"lib{name}.so")
- else:
- filenames = (f"lib{name}.so",)
- location = next((library_dir / f for f in filenames if (library_dir / f).is_file()), None)
- if location is None:
- raise RuntimeError(f"Cannot find TIRx library {name} in {library_dir}")
- implib = ""
- if windows:
- import_names = (f"{name}.lib", f"lib{name}.dll.a")
- import_library = next(
- (library_dir / f for f in import_names if (library_dir / f).is_file()), None
- )
- if import_library is None:
- raise RuntimeError(f"Missing import library for {location}")
- implib = str(import_library)
- libraries[name] = {"location": str(location), "implib": implib}
- return libraries
+if __package__:
+ from . import libinfo
+else:
+ # The native CMake package installs the pure Python helper beside this file.
+ spec = importlib.util.spec_from_file_location(
+ "_tvm_tirx_libinfo", Path(__file__).with_name("libinfo.py")
+ )
+ libinfo = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(libinfo)
def configuration(
@@ -112,62 +45,7 @@ def configuration(
platform: str = sys.platform,
) -> dict:
"""Return the public include and core shared-library paths for one installation."""
- prefix, library_dir = _paths(prefix, library_dir)
- return {
- "version": __version__,
- "include_dir": str(prefix / "include"),
- "library_dir": str(library_dir),
- "cmake_dir": str(library_dir / "cmake/tvm_tirx"),
- "libraries": _libraries(library_dir, platform),
- }
-
-
-def _ffi_info():
- """Read the selected FFI package's pure Python helper without importing its runtime."""
- spec = importlib.machinery.PathFinder.find_spec("tvm_ffi")
- if spec is None or spec.origin is None:
- raise RuntimeError("Cannot find the matching apache-tvm-ffi Python package")
- helper = Path(spec.origin).parent / "libinfo.py"
- spec = importlib.util.spec_from_file_location("_tvm_ffi_libinfo", helper)
- module = importlib.util.module_from_spec(spec)
- spec.loader.exec_module(module)
- return module
-
-
-def _available(library_dir, platform):
- available = []
- for component, name in _COMPONENTS.items():
- try:
- _libraries(library_dir, platform, (name,))
- except RuntimeError:
- continue
- available.append(component)
- return available
-
-
-def _link_inputs(library_dir, platform, components):
- available = _available(library_dir, platform)
- selected = list(dict.fromkeys(components or ["all"]))
- if "all" in selected:
- selected = [*available, *(name for name in selected if name != "all")]
- for name in selected:
- if name != "ffi" and name not in available:
- raise RuntimeError(
- f"Component '{name}' is unavailable; available: {' '.join(available)} ffi"
- )
- # Dependents precede their dependencies even if the command line lists runtime first.
- ordered = [name for name in selected if name not in ("runtime", "ffi")]
- if any(name != "ffi" for name in selected):
- ordered.append("runtime")
- libraries = _libraries(library_dir, platform, [_COMPONENTS[name] for name in ordered])
- ffi = _ffi_info()
- ffi_library = (
- ffi.find_windows_implib() if platform in ("Windows", "win32") else ffi.find_libtvm_ffi()
- )
- return [
- *(Path(lib["implib"] or lib["location"]) for lib in libraries.values()),
- Path(ffi_library),
- ]
+ return libinfo.configuration(prefix, library_dir, platform)
def __main__() -> None:
@@ -216,10 +94,10 @@ def __main__() -> None:
"complete static dependency closure (including TVM FFI and its dependencies)"
)
if args.show_version:
- print(__version__)
+ print(libinfo.__version__)
if all(not getattr(args, "show_" + output) for output in outputs if output != "version"):
return
- prefix, library_dir = _paths(args.install_prefix, args.library_dir)
+ prefix, library_dir = libinfo._paths(args.install_prefix, args.library_dir)
paths = {
"prefix": prefix,
"includedir": prefix / "include",
@@ -232,11 +110,11 @@ def __main__() -> None:
if getattr(args, "show_" + output):
print(path)
if args.show_components:
- print(" ".join([*_available(library_dir, args.platform), "ffi"]))
+ print(" ".join([*libinfo._available(library_dir, args.platform), "ffi"]))
if args.show_json:
print(json.dumps(configuration(prefix, library_dir, args.platform)))
if args.show_cflags or args.show_cxxflags:
- ffi = _ffi_info()
+ ffi = libinfo._ffi_info()
includes = dict.fromkeys(
[str(prefix / "include"), ffi.find_include_path(), ffi.find_dlpack_include_path()]
)
@@ -246,7 +124,7 @@ def __main__() -> None:
if args.show_cxxflags:
print(shlex.join([*flags, "-std=c++20"]))
if any((args.show_ldflags, args.show_libs, args.show_libnames, args.show_libfiles)):
- libraries = _link_inputs(library_dir, args.platform, args.components)
+ libraries = libinfo._link_inputs(library_dir, args.platform, args.components)
apple = args.platform in ("Darwin", "iOS", "darwin")
if args.show_ldflags:
print(
diff --git a/tirx/python/tvm_tirx/error.py b/tirx/python/tvm_tirx/error.py
deleted file mode 100644
index e1a5fdd9b2..0000000000
--- a/tirx/python/tvm_tirx/error.py
+++ /dev/null
@@ -1,126 +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.
-"""Structured error classes in TVM.
-
-Each error class takes an error message as its input.
-See the example sections for suggested message conventions.
-To make the code more readable, we recommended developers to
-copy the examples and raise errors with the same message convention.
-
-.. note::
-
- Please also refer to :ref:`error-handling-guide`.
-"""
-
-from tvm_ffi import register_error
-
-
-@register_error
-class InternalError(RuntimeError):
- """Internal error in the system.
-
- Examples
- --------
- .. code :: c++
-
- // Example code C++
- LOG(FATAL) << "InternalError: internal error detail.";
-
- .. code :: python
-
- # Example code in python
- raise InternalError("internal error detail")
- """
-
-
-@register_error
-class RPCError(RuntimeError):
- """Error thrown by the remote server handling the RPC call."""
-
-
-@register_error
-class RPCSessionTimeoutError(RPCError, TimeoutError):
- """Error thrown by the remote server when the RPC session has expired."""
-
-
-@register_error
-class OpError(RuntimeError):
- """Base class of all operator errors in frontends."""
-
-
-@register_error
-class OpNotImplemented(OpError, NotImplementedError):
- """Operator is not implemented.
-
- Example
- -------
- .. code:: python
-
- raise OpNotImplemented(
- "Operator {} is not supported in {} frontend".format(
- missing_op, frontend_name))
- """
-
-
-@register_error
-class OpAttributeRequired(OpError, AttributeError):
- """Required attribute is not found.
-
- Example
- -------
- .. code:: python
-
- raise OpAttributeRequired(
- "Required attribute {} not found in operator {}".format(
- attr_name, op_name))
- """
-
-
-@register_error
-class OpAttributeInvalid(OpError, AttributeError):
- """Attribute value is invalid when taking in a frontend operator.
-
- Example
- -------
- .. code:: python
-
- raise OpAttributeInvalid(
- "Value {} in attribute {} of operator {} is not valid".format(
- value, attr_name, op_name))
- """
-
-
-@register_error
-class OpAttributeUnImplemented(OpError, NotImplementedError):
- """Attribute is not supported in a certain frontend.
-
- Example
- -------
- .. code:: python
-
- raise OpAttributeUnImplemented(
- "Attribute {} is not supported in operator {}".format(
- attr_name, op_name))
- """
-
-
-@register_error
-class DiagnosticError(RuntimeError):
- """Error diagnostics were reported during the execution of a pass.
-
- See the configured diagnostic renderer for detailed error information.
- """
diff --git a/tirx/python/tvm_tirx/ir/op.py b/tirx/python/tvm_tirx/ir/op.py
index 7773e33129..e9c5ac10ca 100644
--- a/tirx/python/tvm_tirx/ir/op.py
+++ b/tirx/python/tvm_tirx/ir/op.py
@@ -30,121 +30,6 @@ from . import _ffi_api
from .expr import Expr
-def _make_op_api(op, module_name):
- """Build a callable whose operands and result are governed by its Op."""
- from .attrs import make_node # pylint: disable=import-outside-toplevel
- from .expr import Call # pylint: disable=import-outside-toplevel
-
- def call(
- *args,
- attrs=None,
- ty_args=None,
- loc: Location = UNKNOWN_LOC,
- ty=None,
- **kwargs,
- ):
- # Bind named operands using the registered signature, without inventing
- # defaults or interpreting arbitrary Python wrapper signatures.
- is_region = op.get_attr("FRegionGetBodyParams") is not None
- body_params = kwargs.pop("body_params", None) if is_region else None
- operands = list(args)
- for index, info in enumerate(op.args_info):
- if index < len(args):
- if info.name in kwargs:
- raise TypeError(f"{op.name}: multiple values for {info.name!r}")
- elif info.name in kwargs:
- operands.append(kwargs.pop(info.name))
- else:
- raise TypeError(f"{op.name}: missing operand {info.name!r}")
- if kwargs or (attrs is None and op.attrs_type_key):
- if not op.attrs_type_key:
- raise TypeError(f"{op.name}: unexpected keyword operands {tuple(kwargs)}")
- if attrs is not None:
- raise TypeError(f"{op.name}: cannot mix attrs with attribute keywords")
- attrs = make_node(op.attrs_type_key, **kwargs)
- if is_region:
- from tvm_tirx.script.ir_builder.stmt import region
-
- if (
- ty is not None
- or ty_args is not None
- or not isinstance(loc, Location)
- or not loc.same_as(UNKNOWN_LOC)
- ):
- raise TypeError(
- f"{op.name}: region builders do not accept ty, ty_args or an explicit loc"
- )
- return region(op, operands, body_params=body_params, attrs=attrs)
- return Call(op, operands, attrs=attrs, ty_args=ty_args, loc=loc, ty=ty)
-
- call.__name__ = op.name.rsplit(".", 1)[-1]
- call.__module__ = module_name
- call.__doc__ = op.doc or f"Construct a call to {op.name}."
- return call
-
-
-def _init_op_api(namespace, target_module_name=None, *, wrapper=None):
- """Initialize registered Op callables in an already loaded Python module.
-
- Like :func:`tvm_ffi.init_ffi_api`, the registry prefix comes first and the
- target defaults to that module name. For example, a backend module uses
- ``_init_op_api("tirx.cuda", __name__)``. Dotted suffixes require existing
- module or SimpleNamespace containers; underscores are ordinary name parts.
-
- Generated functions accept registered positional/named operands plus
- ``attrs``, ``ty_args``, ``loc`` and ``ty``.
- Region operations construct a RegionFrame and accept ``body_params`` instead
- of Call result/type arguments.
- Omitting the result invokes an available Op inference hook; without one,
- Call retains a missing type.
- Explicit results and inference errors are preserved; Call.validate checks
- the operator contract separately. Attribute
- keywords construct the registered attrs schema, when one is declared.
-
- Existing Python callables retain ownership of their names; only missing
- exposures are generated. Existing functions must accept printed calls or
- have an appropriate exceptional printer hook. Non-callable collisions fail
- before any functions are installed. An optional ``wrapper`` adapts newly
- generated Call constructors at export time; existing exposures and region
- builders are untouched.
- Returns None.
- """
- if not namespace or any(
- not part.isidentifier() or keyword.iskeyword(part) for part in namespace.split(".")
- ):
- raise ValueError(f"Invalid Op namespace {namespace!r}")
- target = sys.modules[target_module_name or namespace]
- pending = []
- destinations = set()
- for name in sorted(Op.list_op_names()):
- if not name.startswith(namespace + "."):
- continue
- parts = name[len(namespace) + 1 :].split(".")
- if any(not part.isidentifier() or keyword.iskeyword(part) for part in parts):
- raise ValueError(f"Op {name!r} has no Python attribute spelling")
- container = target
- for part in parts[:-1]:
- container = vars(container).get(part)
- if not isinstance(container, ModuleType | SimpleNamespace):
- raise ValueError(f"Op {name!r} requires an existing namespace at {part!r}")
- destination = (id(container), parts[-1])
- if destination in destinations:
- raise ValueError(f"Op {name!r} aliases another exposure destination")
- destinations.add(destination)
- op = Op.get(name)
- if parts[-1] in vars(container):
- current = vars(container)[parts[-1]]
- if not callable(current):
- raise ValueError(f"Op {name!r} conflicts with an existing Python attribute")
- else:
- call = _make_op_api(op, target.__name__)
- if wrapper is not None and op.get_attr("FRegionGetBodyParams") is None:
- call = wrapper(call)
- pending.append((container, parts[-1], call))
- for container, name, call in pending:
- setattr(container, name, call)
-
-
@tvm_ffi.register_object("ir.Op")
class Op(Expr):
"""Primitive operator in the IR."""
@@ -280,3 +165,118 @@ def register_op_attr(op_name, attr_key, value=None, override=False):
return v
return _register(value) if value is not None else _register
+
+
+def _make_op_api(op, module_name):
+ """Build a callable whose operands and result are governed by its Op."""
+ from .attrs import make_node # pylint: disable=import-outside-toplevel
+ from .expr import Call # pylint: disable=import-outside-toplevel
+
+ def call(
+ *args,
+ attrs=None,
+ ty_args=None,
+ loc: Location = UNKNOWN_LOC,
+ ty=None,
+ **kwargs,
+ ):
+ # Bind named operands using the registered signature, without inventing
+ # defaults or interpreting arbitrary Python wrapper signatures.
+ is_region = op.get_attr("FRegionGetBodyParams") is not None
+ body_params = kwargs.pop("body_params", None) if is_region else None
+ operands = list(args)
+ for index, info in enumerate(op.args_info):
+ if index < len(args):
+ if info.name in kwargs:
+ raise TypeError(f"{op.name}: multiple values for {info.name!r}")
+ elif info.name in kwargs:
+ operands.append(kwargs.pop(info.name))
+ else:
+ raise TypeError(f"{op.name}: missing operand {info.name!r}")
+ if kwargs or (attrs is None and op.attrs_type_key):
+ if not op.attrs_type_key:
+ raise TypeError(f"{op.name}: unexpected keyword operands {tuple(kwargs)}")
+ if attrs is not None:
+ raise TypeError(f"{op.name}: cannot mix attrs with attribute keywords")
+ attrs = make_node(op.attrs_type_key, **kwargs)
+ if is_region:
+ from tvm_tirx.script.ir_builder.stmt import region
+
+ if (
+ ty is not None
+ or ty_args is not None
+ or not isinstance(loc, Location)
+ or not loc.same_as(UNKNOWN_LOC)
+ ):
+ raise TypeError(
+ f"{op.name}: region builders do not accept ty, ty_args or an explicit loc"
+ )
+ return region(op, operands, body_params=body_params, attrs=attrs)
+ return Call(op, operands, attrs=attrs, ty_args=ty_args, loc=loc, ty=ty)
+
+ call.__name__ = op.name.rsplit(".", 1)[-1]
+ call.__module__ = module_name
+ call.__doc__ = op.doc or f"Construct a call to {op.name}."
+ return call
+
+
+def _init_op_api(namespace, target_module_name=None, *, wrapper=None):
+ """Initialize registered Op callables in an already loaded Python module.
+
+ Like :func:`tvm_ffi.init_ffi_api`, the registry prefix comes first and the
+ target defaults to that module name. For example, a backend module uses
+ ``_init_op_api("tirx.cuda", __name__)``. Dotted suffixes require existing
+ module or SimpleNamespace containers; underscores are ordinary name parts.
+
+ Generated functions accept registered positional/named operands plus
+ ``attrs``, ``ty_args``, ``loc`` and ``ty``.
+ Region operations construct a RegionFrame and accept ``body_params`` instead
+ of Call result/type arguments.
+ Omitting the result invokes an available Op inference hook; without one,
+ Call retains a missing type.
+ Explicit results and inference errors are preserved; Call.validate checks
+ the operator contract separately. Attribute
+ keywords construct the registered attrs schema, when one is declared.
+
+ Existing Python callables retain ownership of their names; only missing
+ exposures are generated. Existing functions must accept printed calls or
+ have an appropriate exceptional printer hook. Non-callable collisions fail
+ before any functions are installed. An optional ``wrapper`` adapts newly
+ generated Call constructors at export time; existing exposures and region
+ builders are untouched.
+ Returns None.
+ """
+ if not namespace or any(
+ not part.isidentifier() or keyword.iskeyword(part) for part in namespace.split(".")
+ ):
+ raise ValueError(f"Invalid Op namespace {namespace!r}")
+ target = sys.modules[target_module_name or namespace]
+ pending = []
+ destinations = set()
+ for name in sorted(Op.list_op_names()):
+ if not name.startswith(namespace + "."):
+ continue
+ parts = name[len(namespace) + 1 :].split(".")
+ if any(not part.isidentifier() or keyword.iskeyword(part) for part in parts):
+ raise ValueError(f"Op {name!r} has no Python attribute spelling")
+ container = target
+ for part in parts[:-1]:
+ container = vars(container).get(part)
+ if not isinstance(container, ModuleType | SimpleNamespace):
+ raise ValueError(f"Op {name!r} requires an existing namespace at {part!r}")
+ destination = (id(container), parts[-1])
+ if destination in destinations:
+ raise ValueError(f"Op {name!r} aliases another exposure destination")
+ destinations.add(destination)
+ op = Op.get(name)
+ if parts[-1] in vars(container):
+ current = vars(container)[parts[-1]]
+ if not callable(current):
+ raise ValueError(f"Op {name!r} conflicts with an existing Python attribute")
+ else:
+ call = _make_op_api(op, target.__name__)
+ if wrapper is not None and op.get_attr("FRegionGetBodyParams") is None:
+ call = wrapper(call)
+ pending.append((container, parts[-1], call))
+ for container, name, call in pending:
+ setattr(container, name, call)
diff --git a/tirx/python/tvm_tirx/libinfo.py b/tirx/python/tvm_tirx/libinfo.py
index 79345f706b..cbe13ae515 100644
--- a/tirx/python/tvm_tirx/libinfo.py
+++ b/tirx/python/tvm_tirx/libinfo.py
@@ -18,11 +18,12 @@
from __future__ import annotations
+import importlib.machinery
+import importlib.util
import os
+import sys
from pathlib import Path
-from tvm_ffi import libinfo as tvm_ffi_libinfo
-
def _rel_top_directory() -> Path:
"""Top directory in the installed (wheel) layout: ``python/tvm_tirx/``."""
@@ -72,17 +73,17 @@ def find_libtvm_runtime() -> str:
RuntimeError
If the runtime library cannot be found.
"""
- candidate = tvm_ffi_libinfo._find_library_by_basename(
+ candidate = _ffi_info()._find_library_by_basename(
"tvm_tirx", "tvm_runtime", extra_lib_paths=package_lib_paths()
)
- if ret := tvm_ffi_libinfo._resolve_and_validate([candidate], cond=lambda _: True):
+ if ret := _ffi_info()._resolve_and_validate([candidate], cond=lambda _: True):
return ret
raise RuntimeError("Cannot find libtvm_runtime")
def find_include_path() -> str:
"""Return the path to TVM's own ``include/`` directory."""
- if ret := tvm_ffi_libinfo._resolve_and_validate(
+ if ret := _ffi_info()._resolve_and_validate(
paths=[
_rel_top_directory() / "include",
_dev_top_directory() / "include",
@@ -94,3 +95,141 @@ def find_include_path() -> str:
__version__ = "0.1.0a0"
+
+
+_LIBRARY_NAMES = ("tvm_tirx_compiler", "tvm_runtime")
+_COMPONENTS = {
+ "compiler": "tvm_tirx_compiler",
+ "runtime": "tvm_runtime",
+ "cuda": "tvm_runtime_cuda",
+ "metal": "tvm_runtime_metal",
+ "opencl": "tvm_runtime_opencl",
+ "vulkan": "tvm_runtime_vulkan",
+ "rocm": "tvm_runtime_rocm",
+}
+
+
+def _find_prefix(start: Path) -> Path:
+ for candidate in (start, *start.parents):
+ if (candidate / "include/tvm/runtime/base.h").is_file():
+ return candidate
+ raise RuntimeError(f"Cannot find TIRx public headers above {start}")
+
+
+def _paths(prefix: Path | None, library_dir: Path | None) -> tuple[Path, Path]:
+ explicit_prefix = prefix is not None
+ if library_dir is not None:
+ library_dir = library_dir.resolve()
+ prefix = prefix.resolve() if prefix is not None else _find_prefix(library_dir)
+ else:
+ prefix = prefix.resolve() if prefix is not None else _find_prefix(Path(__file__).parent)
+ library_dir = prefix / "lib"
+ candidates = [prefix / "lib", prefix / "lib64", prefix / "build/lib"]
+ if prefix.name == "tirx":
+ candidates.append(prefix.parent / "build/lib")
+ if not explicit_prefix and os.environ.get("TVM_TIRX_LIBRARY_PATH"):
+ candidates.insert(0, Path(os.environ["TVM_TIRX_LIBRARY_PATH"]))
+ for candidate in candidates:
+ if all(
+ any(
+ (candidate / filename).is_file()
+ for filename in (f"lib{name}.so", f"lib{name}.dylib", f"{name}.dll")
+ )
+ for name in ("tvm_runtime",)
+ ):
+ library_dir = candidate
+ break
+ if not (prefix / "include/tvm/runtime/base.h").is_file():
+ raise RuntimeError(f"Cannot find TIRx public headers in {prefix / 'include'}")
+ return prefix, library_dir
+
+
+def _libraries(library_dir: Path, platform: str, names=_LIBRARY_NAMES) -> dict[str, dict[str, str]]:
+ libraries = {}
+ windows = platform in ("Windows", "win32")
+ apple = platform in ("Darwin", "iOS", "darwin")
+ for name in names:
+ if windows:
+ filenames = (f"{name}.dll",)
+ elif apple:
+ filenames = (f"lib{name}.dylib", f"lib{name}.so")
+ else:
+ filenames = (f"lib{name}.so",)
+ location = next((library_dir / f for f in filenames if (library_dir / f).is_file()), None)
+ if location is None:
+ raise RuntimeError(f"Cannot find TIRx library {name} in {library_dir}")
+ implib = ""
+ if windows:
+ import_names = (f"{name}.lib", f"lib{name}.dll.a")
+ import_library = next(
+ (library_dir / f for f in import_names if (library_dir / f).is_file()), None
+ )
+ if import_library is None:
+ raise RuntimeError(f"Missing import library for {location}")
+ implib = str(import_library)
+ libraries[name] = {"location": str(location), "implib": implib}
+ return libraries
+
+
+def configuration(
+ prefix: Path | None = None,
+ library_dir: Path | None = None,
+ platform: str = sys.platform,
+) -> dict:
+ """Return the public include and core shared-library paths for one installation."""
+ prefix, library_dir = _paths(prefix, library_dir)
+ return {
+ "version": __version__,
+ "include_dir": str(prefix / "include"),
+ "library_dir": str(library_dir),
+ "cmake_dir": str(library_dir / "cmake/tvm_tirx"),
+ "libraries": _libraries(library_dir, platform),
+ }
+
+
+def _ffi_info():
+ """Read the selected FFI package's pure Python helper without importing its runtime."""
+ spec = importlib.machinery.PathFinder.find_spec("tvm_ffi")
+ if spec is None or spec.origin is None:
+ raise RuntimeError("Cannot find the matching apache-tvm-ffi Python package")
+ helper = Path(spec.origin).parent / "libinfo.py"
+ spec = importlib.util.spec_from_file_location("_tvm_ffi_libinfo", helper)
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+
+
+def _available(library_dir, platform):
+ available = []
+ for component, name in _COMPONENTS.items():
+ try:
+ _libraries(library_dir, platform, (name,))
+ except RuntimeError:
+ continue
+ available.append(component)
+ return available
+
+
+def _link_inputs(library_dir, platform, components):
+ available = _available(library_dir, platform)
+ selected = list(dict.fromkeys(components or ["all"]))
+ if "all" in selected:
+ selected = [*available, *(name for name in selected if name != "all")]
+ for name in selected:
+ if name != "ffi" and name not in available:
+ raise RuntimeError(
+ f"Component '{name}' is unavailable; available: {' '.join(available)} ffi"
+ )
+ # Dependents precede their dependencies even if the command line lists runtime first.
+ ordered = [name for name in selected if name not in ("runtime", "ffi")]
+ if any(name != "ffi" for name in selected):
+ ordered.append("runtime")
+ libraries = _libraries(library_dir, platform, [_COMPONENTS[name] for name in ordered])
+ ffi = _ffi_info()
+ ffi_library = (
+ ffi.find_windows_implib() if platform in ("Windows", "win32") else ffi.find_libtvm_ffi()
+ )
+ return [
+ *(Path(lib["implib"] or lib["location"]) for lib in libraries.values()),
+ Path(ffi_library),
+ ]
diff --git a/tirx/python/tvm_tirx/support/clang.py b/tirx/python/tvm_tirx/support/clang.py
index c0763dfcd0..09120be9e5 100644
--- a/tirx/python/tvm_tirx/support/clang.py
+++ b/tirx/python/tvm_tirx/support/clang.py
@@ -44,7 +44,7 @@ def find_clang(required=True):
matches the major llvm version that built with tvm
"""
cc_list = []
- major = tvm_tirx.codegen.llvm_version_major(allow_none=True)
+ major = tvm_tirx.codegen.llvm.version_major(allow_none=True)
if major is not None:
cc_list += [f"clang-{major}.0"]
cc_list += [f"clang-{major}"]
diff --git a/tirx/python/tvm_tirx/support/rocm.py b/tirx/python/tvm_tirx/support/rocm.py
index 8da215a0fe..962b999787 100644
--- a/tirx/python/tvm_tirx/support/rocm.py
+++ b/tirx/python/tvm_tirx/support/rocm.py
@@ -49,7 +49,7 @@ def find_lld(required=True):
matches the major llvm version that built with tvm
"""
lld_list = []
- major = tvm_tirx.codegen.llvm_version_major(allow_none=True)
+ major = tvm_tirx.codegen.llvm.version_major(allow_none=True)
if major is not None:
lld_list += [f"ld.lld-{major}.0"]
lld_list += [f"ld.lld-{major}"]
diff --git a/tirx/python/tvm_tirx/testing/env.py b/tirx/python/tvm_tirx/testing/env.py
index 7e58d5c269..6ce5d3cd34 100644
--- a/tirx/python/tvm_tirx/testing/env.py
+++ b/tirx/python/tvm_tirx/testing/env.py
@@ -404,7 +404,7 @@ def has_nvcc_version(major: int, minor: int = 0, release: int = 0) -> bool:
def _llvm_version_major() -> int:
"""Return the major LLVM version, or 0 if LLVM is unavailable."""
try:
- return int(tvm_tirx.codegen.llvm_version_major())
+ return int(tvm_tirx.codegen.llvm.version_major())
except Exception: # pylint: disable=broad-except
return 0
@@ -451,7 +451,7 @@ def has_hexagon_toolchain() -> bool:
try:
return (
_runtime_enabled("llvm")
- and "hexagon" in tvm_tirx.codegen.llvm_get_targets()
+ and "hexagon" in tvm_tirx.codegen.llvm.get_targets()
and "HEXAGON_TOOLCHAIN" in os.environ
)
except Exception: # pylint: disable=broad-except
@@ -485,8 +485,8 @@ def _has_cpu_feature(features) -> bool:
"""True if the host CPU advertises the given LLVM target ``features``."""
try:
codegen = tvm_tirx.codegen
- cpu = codegen.llvm_get_system_cpu()
- triple = codegen.llvm_get_system_triple()
+ cpu = codegen.llvm.get_system_cpu()
+ triple = codegen.llvm.get_system_triple()
target = tvm_tirx.target.Target({"kind": "llvm", "mtriple": triple, "mcpu": cpu})
return bool(codegen.target_has_features(features, target))
except Exception: # pylint: disable=broad-except
diff --git a/tirx/python/tvm_tirx/tirx/__init__.py b/tirx/python/tvm_tirx/tirx/__init__.py
index c6653bfa1f..cbbde24567 100644
--- a/tirx/python/tvm_tirx/tirx/__init__.py
+++ b/tirx/python/tvm_tirx/tirx/__init__.py
@@ -44,7 +44,8 @@ from .expr import Select, TensorLoad
from .expr import Let
-from .function import Function, IndexMap, renew_def
+from .function import Function, renew_def
+from .index_map import IndexMap
from .op import call_packed_lowered, call_cpacked_lowered, register_intrin_lowering
from .op import call_packed, call_cpacked, call_intrin, call_pure_extern, call_extern
@@ -84,7 +85,6 @@ from .thread_scope import ThreadScope
from .layout import TileLayout, Layout, ComposeLayout
from . import transform
from . import analysis
-from . import backend
# Compiler-only submodules. Skip under `TVM_USE_RUNTIME_LIB=1` since they
# perform compiler-side FFI at module load (schema engine looks up
diff --git a/tirx/python/tvm_tirx/tirx/function.py b/tirx/python/tvm_tirx/tirx/function.py
index 2a7ce72203..daa9b20d30 100644
--- a/tirx/python/tvm_tirx/tirx/function.py
+++ b/tirx/python/tvm_tirx/tirx/function.py
@@ -17,20 +17,16 @@
# pylint: disable=unrecognized-inline-option
"""Function data types."""
-import collections
-import inspect
-from collections.abc import Callable, Mapping, Sequence
-from typing import Optional
+from collections.abc import Mapping, Sequence
import tvm_ffi
import tvm_tirx
import tvm_tirx.runtime
-from tvm_tirx.ir import BaseFunc, Range, Scriptable, SeqStmt, Stmt, Var
+from tvm_tirx.ir import BaseFunc, Scriptable, SeqStmt, Stmt, Var
from tvm_tirx.ir.location import UNKNOWN_LOC, Location
from tvm_tirx.runtime import Object
-from ..runtime._tensor import Tensor
from . import _ffi_api
from .expr import Expr
@@ -88,11 +84,6 @@ class Function(BaseFunc, Scriptable):
loc,
) # type: ignore
- @property
- def is_tirx(self):
- """Whether this primitive function uses the TIRx dialect."""
- return not bool(self.attrs.get("s_tir", False))
-
def with_body(self, new_body: Stmt | Sequence[Stmt] | None, loc: Location = UNKNOWN_LOC):
"""Create a new Function with the same set signatures but a new body.
@@ -191,287 +182,3 @@ def renew_def(func: Function) -> Function:
The function with fresh variable definitions.
"""
return _ffi_api.RenewDef(func)
-
-
-@tvm_ffi.register_object("tirx.IndexMap")
-class IndexMap(Object):
- """A mapping from multi-dimensional indices to another set of multi-dimensional indices
-
- Parameters
- ----------
- initial_indices : List[Var]
- Variables representing the indices prior to remapping.
- final_indices : List[Expr]
- Expressions defining the indices after remapping.
- inverse_index_map : Union[Callable, Optional[IndexMap]]
- The optional pre-defined inverse index map.
- When this is defined, IndexMap::Inverse will return the pre-defined inverse index map.
- Otherwise, the inverse index map will be computed on the fly.
- It is the user's responsibility to ensure the correctness of the pre-defined inverse
- index map.
- """
-
- initial_indices: list[Var]
- final_indices: list[Expr]
-
- def __init__(self, initial_indices, final_indices, inverse_index_map):
- if isinstance(inverse_index_map, Callable):
- inverse_index_map = IndexMap.from_func(inverse_index_map)
- self.__init_handle_by_constructor__(
- _ffi_api.IndexMap, initial_indices, final_indices, inverse_index_map
- )
-
- @staticmethod
- def from_func(
- mapping_function: Callable,
- ndim: int | None = None,
- inverse_index_map: Callable | Optional["IndexMap"] = None,
- *,
- index_dtype: str = "int64",
- ):
- """Create an index map from a function
-
- Parameters
- ----------
- mapping_function : Callable
-
- The function to map from source indices to target indices.
- The function should accept `tirx.Var` parameters and return
- a either a `tirx.Expr`, or a list of `tirx.Expr`.
- Returning a `tirx.Expr` is equivalent to returning a
- list of length 1 containing that `tirx.Expr`.
-
- ndim: Optional[int]
-
- The dimensionality of the tensor to which this
- transformation should be applied. If mapping_function uses
- variadic argument `*args`, `ndim` must be specified. If
- mapping_function does not use variadic arguments, ndim is
- optional.
-
- inverse_index_map : Union[Callable, Optional[IndexMap]]
- The optional pre-defined inverse index map.
- When this is defined, IndexMap::Inverse will return the pre-defined inverse index map.
- Otherwise, the inverse index map will be computed on the fly.
- It is the user's responsibility to ensure the correctness of the pre-defined inverse
- index map.
-
- index_dtype : str
- The default index dtype to use for input iters in the mapping function.
-
- Returns
- -------
- index_map: IndexMap
-
- Returns an IndexMap representing the `mapping_function`.
-
- """
- params = inspect.signature(mapping_function).parameters
-
- args = []
- var_arg_name = None
- kwargs = collections.OrderedDict()
-
- for name, param in params.items():
- if param.kind in [
- inspect.Parameter.POSITIONAL_ONLY,
- inspect.Parameter.POSITIONAL_OR_KEYWORD,
- ]:
- args.append(tvm_tirx.tirx.Var(name, index_dtype))
-
- elif param.kind == inspect.Parameter.VAR_POSITIONAL:
- var_arg_name = name
-
- elif param.kind == inspect.Parameter.KEYWORD_ONLY:
- kwargs[name] = tvm_tirx.tirx.Var(name, index_dtype)
-
- else:
- raise ValueError("transform_layout mapping may not have *args")
-
- # Now that all the named arguments have been collected,
- # everything that remains should go to the *args, if
- # specified.
- if var_arg_name is not None:
- assert ndim is not None, "ndim must be specified when *args is used"
- num_var_args = ndim - len(args) - len(kwargs)
- for i in range(num_var_args):
- args.append(tvm_tirx.tirx.Var(f"{var_arg_name}_{i}", index_dtype))
-
- mapping = mapping_function(*args, **kwargs)
-
- initial_indices = args + list(kwargs.values())
-
- final_indices = []
-
- if tvm_tirx.ir.is_prim_expr(mapping):
- is_iterable = False
- else:
- try:
- iter(mapping)
- is_iterable = True
- except TypeError:
- is_iterable = False
-
- if is_iterable:
- for val in mapping:
- if tvm_tirx.ir.is_prim_expr(val):
- final_indices.append(val)
- else:
- raise TypeError(
- "Expected mapping function to return tvm_tirx.ir.Expr "
- "or a list of tvm_tirx.ir.Expr. "
- f"Instead received {val} of type {type(val)}."
- )
- else:
- final_indices.append(mapping)
-
- return IndexMap(initial_indices, final_indices, inverse_index_map)
-
- def is_equivalent_to(self, other_map: "IndexMap", analyzer=None) -> bool:
- """Return if the index maps are equivalent.
-
- Parameters
- ----------
- other_map: IndexMap
-
- The IndexMap to which the comparison should be made.
-
- analyzer : Optional[tvm_tirx.sym.Analyzer]
-
- The analyzer to use while comparing the mapped indices. When
- provided, its accumulated bindings and constraints are reused so
- that maps that are only equivalent under those bindings can be
- proven equal.
-
- Returns
- -------
- is_equivalent: bool
-
- True if the two mappings represent the same
- transformation, otherwise False
- """
- if len(self.initial_indices) != len(other_map.initial_indices):
- return False
- if len(self.final_indices) != len(other_map.final_indices):
- return False
-
- if analyzer is None:
- analyzer = tvm_tirx.sym.Analyzer()
-
- mapped_other_final_indices = other_map.map_indices(self.initial_indices, analyzer=analyzer)
- for self_index, other_index in zip(self.final_indices, mapped_other_final_indices):
- if not analyzer.can_prove_equal(self_index, other_index):
- return False
-
- return True
-
- def map_indices(self, indices: list[Expr], analyzer=None) -> list[Expr]:
- """Apply the index map to a set of indices
-
- Parameters
- ----------
- indices : List[Expr]
- The indices to be mapped
- analyzer : Optional[tvm_tirx.sym.Analyzer]
- The analyzer to use while simplifying mapped indices.
-
- Returns
- -------
- result : List[Expr]
- The mapped indices
- """
- return _ffi_api.IndexMapMapIndices(self, indices, analyzer)
-
- def map_shape(self, shape: list[Expr], analyzer=None) -> list[Expr]:
- """Apply the index map to a tensor shape
-
- Parameters
- ----------
- shape : List[Expr]
- The tensor shape to be mapped
- analyzer : Optional[tvm_tirx.sym.Analyzer]
- The analyzer to use while simplifying mapped shape expressions.
-
- Returns
- -------
- result : List[Expr]
- The mapped shape
- """
- return _ffi_api.IndexMapMapShape(self, shape, analyzer)
-
- def map_tensor(self, arr_src: Tensor) -> Tensor:
- """Apply thie index map to transform the layout of the input Tensor
-
- Parameters
- ----------
- arr_src : runtime.Tensor
- The Tensor to be transformed
-
- Returns
- -------
- arr_dst : runtime.Tensor
- The transformed Tensor
- """
- return _ffi_api.IndexMapMapTensor(self, arr_src)
-
- def inverse(self, shape: list[Range | Expr], analyzer=None) -> "IndexMap":
- """Return the inverse of the map
-
- Throws an error if the function is not bijective.
-
- Parameters
- ----------
- shape: List[Union[Range,Expr]]
-
- The region over which the inverse should be determined.
- Used for validating that the mapping is bijective over
- this range.
- analyzer : Optional[tvm_tirx.sym.Analyzer]
- The analyzer to use while deriving and validating the inverse.
-
- Returns
- -------
- inverse : IndexMap
-
- The inverse
- """
-
- shape = [dim if isinstance(dim, Range) else Range(0, dim) for dim in shape]
- return _ffi_api.IndexMapInverse(self, shape, analyzer)
-
- def non_surjective_inverse(
- self, shape: list[Range | Expr], analyzer=None
- ) -> tuple["IndexMap", Expr]:
- """Return the inverse of the map
-
- Can be applied to transformations that introduce padding.
-
- Parameters
- ----------
- shape: List[Union[Range,Expr]]
-
- The region over which the inverse should be determined.
- Used for determining the predicate.
- analyzer : Optional[tvm_tirx.sym.Analyzer]
- The analyzer to use while deriving the inverse and padding predicate.
-
- Returns
- -------
- result : Tuple[IndexMap, Expr]
-
- The inverse, and a predicate for which the inverse maps to
- a valid index in the input range.
-
- Examples
- --------
-
- .. code-block:: python
-
- index_map = IndexMap.from_func(lambda i: [i//4, i%4])
- inverse_map, predicate = index_map.non_surjective_inverse([14])
- assert inverse_map.is_equivalent_to(IndexMap.from_func(lambda j,k: [4*j + k])
- print(predicate) # Prints "(axis0==3) && (axis2 >= 2)"
- """
-
- shape = [dim if isinstance(dim, Range) else Range(0, dim) for dim in shape]
- return _ffi_api.IndexMapNonSurjectiveInverse(self, shape, analyzer)
diff --git a/tirx/python/tvm_tirx/tirx/function.py b/tirx/python/tvm_tirx/tirx/index_map.py
similarity index 69%
copy from tirx/python/tvm_tirx/tirx/function.py
copy to tirx/python/tvm_tirx/tirx/index_map.py
index 2a7ce72203..0ddc175520 100644
--- a/tirx/python/tvm_tirx/tirx/function.py
+++ b/tirx/python/tvm_tirx/tirx/index_map.py
@@ -15,182 +15,21 @@
# specific language governing permissions and limitations
# under the License.
# pylint: disable=unrecognized-inline-option
-"""Function data types."""
+"""Mappings between multi-dimensional indices."""
import collections
import inspect
-from collections.abc import Callable, Mapping, Sequence
+from collections.abc import Callable
from typing import Optional
import tvm_ffi
import tvm_tirx
-import tvm_tirx.runtime
-from tvm_tirx.ir import BaseFunc, Range, Scriptable, SeqStmt, Stmt, Var
-from tvm_tirx.ir.location import UNKNOWN_LOC, Location
+from tvm_tirx.ir import Expr, Range, Var
from tvm_tirx.runtime import Object
+from tvm_tirx.runtime._tensor import Tensor
-from ..runtime._tensor import Tensor
from . import _ffi_api
-from .expr import Expr
-
-
-@tvm_ffi.register_object("tirx.Function")
-class Function(BaseFunc, Scriptable):
- """A function declaration expression.
-
- Parameters
- ----------
- params: List[Union[tvm_tirx.tirx.Var, tvm_tirx.tirx.Var]]
- List of input parameters to the function.
-
- body: Stmt | Sequence[Stmt] | None
- The body of the function, or None for a declaration.
-
- ret_type: tvm_tirx.ir.Type
- The return type annotation of the function.
-
- attrs: Optional[tvm.Attrs]
- Attributes of the function, can be None
-
- loc : Location, optional
- The location of this itervar in the source code.
- """
-
- body: SeqStmt | None
-
- def __init__(
- self,
- params,
- body: Stmt | Sequence[Stmt] | None,
- ret_type=None,
- attrs=None,
- loc: Location = UNKNOWN_LOC,
- ):
- if ret_type is None:
- ret_type = tvm_tirx.ir.Type.missing()
- param_list = []
- for x in params:
- x = tvm_tirx.runtime.convert(x) if not isinstance(x, Object) else x
- if not isinstance(x, Var):
- raise TypeError("params can only contain Var or Var")
- param_list.append(x)
-
- if attrs is None:
- attrs = tvm_tirx.ir.make_node("ir.DictAttrs")
-
- self.__init_handle_by_constructor__(
- _ffi_api.Function,
- param_list,
- body,
- ret_type,
- attrs,
- loc,
- ) # type: ignore
-
- @property
- def is_tirx(self):
- """Whether this primitive function uses the TIRx dialect."""
- return not bool(self.attrs.get("s_tir", False))
-
- def with_body(self, new_body: Stmt | Sequence[Stmt] | None, loc: Location = UNKNOWN_LOC):
- """Create a new Function with the same set signatures but a new body.
-
- Parameters
- ----------
- new_body : Stmt | Sequence[Stmt] | None
- The new body, or None for a declaration.
-
- loc : Location, optional
- The location of this itervar in the source code.
-
- Returns
- -------
- new_func : Function
- The created new function.
- """
- return Function(
- self.params,
- new_body,
- ret_type=self.ret_type,
- attrs=self.attrs,
- loc=loc,
- )
-
- def specialize(self, param_map: Mapping[Var, Expr | Var]):
- """Specialize parameters of Function
-
- Parameters
- ----------
-
- param_map : Mapping[Var, Union[Expr, Var]]
- The mapping from function params to the instance
-
- Examples
- --------
- We can define a TIRX function with symbolic shape:
-
- .. code-block:: python
-
- from __future__ import annotations
-
- @T.function
- def mem_copy(
- A: T.Tensor((m, n), "float32"),
- B: T.Tensor((m, n), "float32"),
- m: T.int32,
- n: T.int32,
- ) -> None:
-
- for i, j in T.grid(m, n):
- B[i, j] = A[i, j]
-
- Then we can make it specialized with given shapes or tensors.
-
- .. code-block:: python
-
- a, _, m, n = mem_copy.params
- func = mem_copy.specialize({a: tirx.decl_tensor((16, 16))})
- # or
- func = mem_copy.specialize({n: 16, m: 16})
-
- The specialized function:
-
- .. code-block:: python
-
- @T.function
- def mem_copy_16_16(
- A: T.Tensor((16, 16), "float32"), B: T.Tensor((16, 16), "float32")
- ) -> None:
-
- for i, j in T.grid(16, 16):
- B[i, j] = A[i, j]
-
- Returns
- -------
- func : Function
- The new function with parameter specialized
- """
- return _ffi_api.Specialize(self, param_map) # type: ignore
-
-
-def renew_def(func: Function) -> Function:
- """Renew variable definitions and remap their uses in a function.
-
- Definition regions follow the registered structural hooks. Free variables
- and function attributes are preserved, and the function signature is rebuilt.
-
- Parameters
- ----------
- func : Function
- The function to renew.
-
- Returns
- -------
- Function
- The function with fresh variable definitions.
- """
- return _ffi_api.RenewDef(func)
@tvm_ffi.register_object("tirx.IndexMap")
diff --git a/tirx/python/tvm_tirx/tirx/op/__init__.py b/tirx/python/tvm_tirx/tirx/op/__init__.py
index a167f8cb62..9ba7b024e5 100644
--- a/tirx/python/tvm_tirx/tirx/op/__init__.py
+++ b/tirx/python/tvm_tirx/tirx/op/__init__.py
@@ -515,7 +515,7 @@ def call_llvm_intrin(name, *args, ty, loc: Location = UNKNOWN_LOC):
from tvm_tirx import codegen
if isinstance(name, str):
- llvm_id = codegen.llvm_lookup_intrinsic_id(name)
+ llvm_id = codegen.llvm.lookup_intrinsic_id(name)
elif isinstance(name, IntImm):
llvm_id = name.value
else:
@@ -559,7 +559,7 @@ def call_llvm_pure_intrin(name, *args, ty, loc: Location = UNKNOWN_LOC):
from tvm_tirx import codegen
if isinstance(name, str):
- llvm_id = codegen.llvm_lookup_intrinsic_id(name)
+ llvm_id = codegen.llvm.lookup_intrinsic_id(name)
elif isinstance(name, IntImm):
llvm_id = name.value
else:
diff --git a/tirx/python/tvm_tirx/tirx/script/ir_builder/op.py b/tirx/python/tvm_tirx/tirx/script/ir_builder/op.py
index fd6887e564..e788d7d90c 100644
--- a/tirx/python/tvm_tirx/tirx/script/ir_builder/op.py
+++ b/tirx/python/tvm_tirx/tirx/script/ir_builder/op.py
@@ -26,7 +26,7 @@ from tvm_tirx import tirx as _tir
from tvm_tirx import tirx as tir
# pylint: disable=unused-import
-from tvm_tirx.codegen import llvm_lookup_intrinsic_id
+from tvm_tirx.codegen.llvm import lookup_intrinsic_id as llvm_lookup_intrinsic_id
from tvm_tirx.ir import Call, CallEffectKind, Var
from tvm_tirx.ir.location import UNKNOWN_LOC, Location
from tvm_tirx.ir.prim import _ffi_api as _prim_ffi
diff --git a/tirx/python/tvm_tirx/tirx/script/ir_builder/parser_protocol.py b/tirx/python/tvm_tirx/tirx/script/ir_builder/parser_protocol.py
index a0fd6bcdbd..8ef324f802 100644
--- a/tirx/python/tvm_tirx/tirx/script/ir_builder/parser_protocol.py
+++ b/tirx/python/tvm_tirx/tirx/script/ir_builder/parser_protocol.py
@@ -203,7 +203,7 @@ def check_well_formed_(function: _tir.Function) -> None:
def _check_module_well_formed(module: _ir.IRModule) -> None:
"""Validate completed functions belonging to the TIRx dialect."""
for function in module.functions.values():
- if isinstance(function, _tir.Function) and function.is_tirx:
+ if isinstance(function, _tir.Function) and not function.attrs.get("s_tir", False):
check_well_formed_(function)
diff --git a/tirx/tests/python/backend/metal/codegen/test_basic.py b/tirx/tests/python/backend/metal/codegen/test_basic.py
index d582ef1cc0..dc8934d83c 100644
--- a/tirx/tests/python/backend/metal/codegen/test_basic.py
+++ b/tirx/tests/python/backend/metal/codegen/test_basic.py
@@ -316,7 +316,7 @@ def test_bound_symbolic_stack_allocation(bounded):
assert "thread float scratch[128]" in source
else:
with pytest.raises(
- tvm_tirx.error.InternalError,
+ RuntimeError,
match="Metal allocation extent requires a finite compile-time upper bound",
):
_build_metal(Module)
@@ -363,7 +363,7 @@ def test_allocation_bound_does_not_substitute_buffer_load(scope, bounded):
assert "scratch[31] =" in source
else:
with pytest.raises(
- tvm_tirx.error.InternalError,
+ RuntimeError,
match="Metal allocation extent requires a finite compile-time upper bound",
):
_build_metal(Module)
@@ -411,7 +411,7 @@ def test_unbounded_symbolic_stack_allocation_rejected():
T.evaluate(scratch[0])
with pytest.raises(
- tvm_tirx.error.InternalError,
+ RuntimeError,
match="Metal allocation extent requires a finite compile-time upper bound",
):
_build_metal(Module)
@@ -436,7 +436,7 @@ def test_unbounded_uint64_symbolic_stack_allocation_rejected():
T.evaluate(scratch[0])
with pytest.raises(
- tvm_tirx.error.InternalError,
+ RuntimeError,
match="Metal allocation extent requires a finite compile-time upper bound",
):
_build_metal(Module)
@@ -461,7 +461,7 @@ def test_nonpositive_stack_allocation_rejected(extent):
T.evaluate(scratch.data)
with pytest.raises(
- tvm_tirx.error.InternalError,
+ RuntimeError,
match="Metal allocation extent requires a positive compile-time upper bound",
):
_build_metal(Module)
@@ -493,7 +493,7 @@ def test_stack_allocation_element_count_overflow_rejected():
T.evaluate(scratch.data)
with pytest.raises(
- tvm_tirx.error.InternalError,
+ RuntimeError,
match="Metal allocation element count is too large to represent",
):
_build_metal(Module)
diff --git a/tirx/tests/python/backend/webgpu/codegen/test_basic.py b/tirx/tests/python/backend/webgpu/codegen/test_basic.py
index 6dc852436d..20bc5b7595 100644
--- a/tirx/tests/python/backend/webgpu/codegen/test_basic.py
+++ b/tirx/tests/python/backend/webgpu/codegen/test_basic.py
@@ -100,7 +100,7 @@ def test_bound_symbolic_allocation(scope, bounded):
assert len(re.findall(declaration + r"\s+\w+\s*:\s*array<f32,\s*128>;", source)) == 2
else:
with pytest.raises(
- tvm_tirx.error.InternalError,
+ RuntimeError,
match="WebGPU allocation extent requires a finite compile-time upper bound",
):
_build_webgpu(Module)
@@ -146,7 +146,7 @@ def test_allocation_bound_does_not_substitute_buffer_load(scope, bounded):
assert "scratch[31" in source
else:
with pytest.raises(
- tvm_tirx.error.InternalError,
+ RuntimeError,
match="WebGPU allocation extent requires a finite compile-time upper bound",
):
_build_webgpu(Module)
@@ -177,7 +177,7 @@ def test_bound_symbolic_workgroup_allocation_respects_target_limit(target_limit)
assert re.search(r"var<workgroup>\s+\w+\s*:\s*array<f32,\s*128>;", source)
else:
with pytest.raises(
- tvm_tirx.error.InternalError,
+ RuntimeError,
match=r"WebGPU workgroup allocations use 512 bytes, .* supports only 496 bytes",
):
_build_webgpu(Module, target)
@@ -201,7 +201,7 @@ def test_unbounded_symbolic_stack_allocation_rejected():
T.evaluate(scratch[0])
with pytest.raises(
- tvm_tirx.error.InternalError,
+ RuntimeError,
match="WebGPU allocation extent requires a finite compile-time upper bound",
):
_build_webgpu(Module)
@@ -225,7 +225,7 @@ def test_nonpositive_stack_allocation_rejected(extent):
T.evaluate(scratch.data)
with pytest.raises(
- tvm_tirx.error.InternalError,
+ RuntimeError,
match="WebGPU allocation extent requires a positive compile-time upper bound",
):
_build_webgpu(Module)
@@ -256,7 +256,7 @@ def test_stack_allocation_element_count_overflow_rejected():
T.evaluate(scratch.data)
with pytest.raises(
- tvm_tirx.error.InternalError,
+ RuntimeError,
match="WebGPU allocation element count is too large to represent",
):
_build_webgpu(Module)
@@ -282,9 +282,7 @@ def test_stack_allocation_byte_size_overflow_rejected():
)
T.evaluate(scratch.data)
- with pytest.raises(
- tvm_tirx.error.InternalError, match="WebGPU allocation byte size is too large to represent"
- ):
+ with pytest.raises(RuntimeError, match="WebGPU allocation byte size is too large to represent"):
_build_webgpu(Module)
@@ -327,7 +325,7 @@ def test_total_workgroup_allocation_above_target_limit_rejected():
second[0] = 2.0
with pytest.raises(
- tvm_tirx.error.InternalError,
+ RuntimeError,
match=r"WebGPU workgroup allocations use 32784 bytes, .* supports only 32768 bytes",
):
_build_webgpu(Module)
@@ -352,7 +350,7 @@ def test_workgroup_allocation_accounts_for_declaration_alignment():
second[0] = 2.0
with pytest.raises(
- tvm_tirx.error.InternalError,
+ RuntimeError,
match=r"WebGPU workgroup allocations use 32 bytes, .* supports only 16 bytes",
):
_build_webgpu(Module, {"kind": "webgpu", "max_shared_memory_per_block": 16})
diff --git a/tirx/tests/python/codegen/llvm/test_aarch64.py b/tirx/tests/python/codegen/llvm/test_aarch64.py
index 0e98e3e6a7..1db9d6540e 100644
--- a/tirx/tests/python/codegen/llvm/test_aarch64.py
+++ b/tirx/tests/python/codegen/llvm/test_aarch64.py
@@ -24,13 +24,13 @@ import re
import pytest
import tvm_tirx
-from tvm_tirx.codegen import llvm_version_major
+from tvm_tirx.codegen import llvm
from tvm_tirx.script import ir as I
from tvm_tirx.script import tirx as T
@pytest.mark.skipif(
- llvm_version_major() < 15, reason="Test requires an LLVM version of at least 15 to target SVE"
+ llvm.version_major() < 15, reason="Test requires an LLVM version of at least 15 to target SVE"
)
@pytest.mark.parametrize(
"dtype",
@@ -68,7 +68,7 @@ def test_mul(dtype):
@pytest.mark.skipif(
- llvm_version_major() < 15, reason="Test requires an LLVM version of at least 15 to target SVE"
+ llvm.version_major() < 15, reason="Test requires an LLVM version of at least 15 to target SVE"
)
@pytest.mark.parametrize(
"dtype",
@@ -106,7 +106,7 @@ def test_add(dtype):
@pytest.mark.skipif(
- llvm_version_major() < 15, reason="Test requires an LLVM version of at least 15 to target SVE"
+ llvm.version_major() < 15, reason="Test requires an LLVM version of at least 15 to target SVE"
)
@pytest.mark.parametrize(
"dtype",
@@ -144,7 +144,7 @@ def test_sub(dtype):
@pytest.mark.skipif(
- llvm_version_major() < 15, reason="Test requires an LLVM version of at least 15 to target SVE"
+ llvm.version_major() < 15, reason="Test requires an LLVM version of at least 15 to target SVE"
)
@pytest.mark.parametrize(
"dtype",
@@ -181,7 +181,7 @@ def test_muladd(dtype):
assembly,
)
- if llvm_version_major() >= 18 and dtype in ("float", "float16"):
+ if llvm.version_major() >= 18 and dtype in ("float", "float16"):
# Newer LLVM cost models (observed with LLVM 20) prefer a fixed-width
# NEON main loop over a scalable SVE loop for floating-point fmuladd
# on generic AArch64 targets, so also accept the NEON form.
@@ -193,7 +193,7 @@ def test_muladd(dtype):
@pytest.mark.skipif(
- llvm_version_major() < 15, reason="Test requires an LLVM version of at least 15 to target SVE"
+ llvm.version_major() < 15, reason="Test requires an LLVM version of at least 15 to target SVE"
)
@pytest.mark.parametrize(
"dtype",
@@ -235,7 +235,7 @@ def test_max(dtype):
@pytest.mark.skipif(
- llvm_version_major() < 15, reason="Test requires an LLVM version of at least 15 to target SVE"
+ llvm.version_major() < 15, reason="Test requires an LLVM version of at least 15 to target SVE"
)
@pytest.mark.parametrize(
"dtype",
@@ -277,7 +277,7 @@ def test_min(dtype):
@pytest.mark.skipif(
- llvm_version_major() < 15, reason="Test requires an LLVM version of at least 15 to target SVE"
+ llvm.version_major() < 15, reason="Test requires an LLVM version of at least 15 to target SVE"
)
@pytest.mark.parametrize(
"dtype",
@@ -315,7 +315,7 @@ def test_div(dtype):
@pytest.mark.skipif(
- llvm_version_major() < 15, reason="Test requires an LLVM version of at least 15 to target SVE"
+ llvm.version_major() < 15, reason="Test requires an LLVM version of at least 15 to target SVE"
)
@pytest.mark.parametrize(
"dtype", ["uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64"]
@@ -352,7 +352,7 @@ def test_mod(dtype):
@pytest.mark.skipif(
- llvm_version_major() < 15, reason="Test requires an LLVM version of at least 15 to target SVE"
+ llvm.version_major() < 15, reason="Test requires an LLVM version of at least 15 to target SVE"
)
@pytest.mark.parametrize(
"dtype",
@@ -393,7 +393,7 @@ def test_eq(dtype):
@pytest.mark.skipif(
- llvm_version_major() < 15, reason="Test requires an LLVM version of at least 15 to target SVE"
+ llvm.version_major() < 15, reason="Test requires an LLVM version of at least 15 to target SVE"
)
@pytest.mark.parametrize(
"dtype",
@@ -434,7 +434,7 @@ def test_neq(dtype):
@pytest.mark.skipif(
- llvm_version_major() < 15, reason="Test requires an LLVM version of at least 15 to target SVE"
+ llvm.version_major() < 15, reason="Test requires an LLVM version of at least 15 to target SVE"
)
@pytest.mark.parametrize(
"dtype", ["uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64"]
@@ -471,7 +471,7 @@ def test_or(dtype):
@pytest.mark.skipif(
- llvm_version_major() < 15, reason="Test requires an LLVM version of at least 15 to target SVE"
+ llvm.version_major() < 15, reason="Test requires an LLVM version of at least 15 to target SVE"
)
@pytest.mark.parametrize(
"dtype", ["uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64"]
@@ -508,7 +508,7 @@ def test_and(dtype):
@pytest.mark.skipif(
- llvm_version_major() < 15, reason="Test requires an LLVM version of at least 15 to target SVE"
+ llvm.version_major() < 15, reason="Test requires an LLVM version of at least 15 to target SVE"
)
@pytest.mark.parametrize(
"dtype", ["uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64"]
@@ -541,7 +541,7 @@ def test_not(dtype):
@pytest.mark.skipif(
- llvm_version_major() < 15, reason="Test requires an LLVM version of at least 15 to target SVE"
+ llvm.version_major() < 15, reason="Test requires an LLVM version of at least 15 to target SVE"
)
@pytest.mark.xfail(
reason="Awaiting llvm support for gathered loads",
@@ -578,7 +578,7 @@ def test_memcpy(dtype):
@pytest.mark.skipif(
- llvm_version_major() < 13,
+ llvm.version_major() < 13,
reason="Function attribute vscale_range() is not supported in earlier versions of LLVM",
)
@pytest.mark.parametrize(
@@ -589,7 +589,7 @@ def test_memcpy(dtype):
# Since LLVM 19, SVE/SVE2 are optional extensions of Armv9.0-A, so
# "+v9a" no longer implies "+sve" and no vscale_range() is added:
# https://releases.llvm.org/19.1.0/docs/ReleaseNotes.html#changes-to-the-aarch64-backend
- ("+v9a", llvm_version_major() < 19),
+ ("+v9a", llvm.version_major() < 19),
("+sme", True),
],
)
diff --git a/tirx/tests/python/codegen/llvm/test_basic.py b/tirx/tests/python/codegen/llvm/test_basic.py
index e786094d86..3d41c705b1 100644
--- a/tirx/tests/python/codegen/llvm/test_basic.py
+++ b/tirx/tests/python/codegen/llvm/test_basic.py
@@ -25,7 +25,7 @@ import pytest
import tvm_tirx
import tvm_tirx.testing
-from tvm_tirx.codegen import llvm_get_intrinsic_name, llvm_lookup_intrinsic_id
+from tvm_tirx.codegen import llvm
from tvm_tirx.script import ir as I
from tvm_tirx.script import tirx as T
from tvm_tirx.support import utils
@@ -46,9 +46,7 @@ def test_duplicate_function_global_symbol_diagnostic():
T.func_attr({"global_symbol": "dup_symbol", "tirx.noalias": True})
A[0] = T.float32(2)
- with pytest.raises(
- tvm_tirx.error.InternalError, match="Duplicate Function global_symbol 'dup_symbol'"
- ) as err:
+ with pytest.raises(RuntimeError, match="Duplicate Function global_symbol 'dup_symbol'") as err:
tvm_tirx.tirx.compile(Module, target="llvm")
assert "first_unique_key" in str(err.value)
assert "second_unique_key" in str(err.value)
@@ -98,8 +96,8 @@ def test_llvm_void_intrin():
@pytest.mark.skipif(not env.has_llvm(), reason="need llvm")
def test_llvm_intrinsic_id():
orig_name = "llvm.x86.sse2.pmadd.wd"
- intrin_id = llvm_lookup_intrinsic_id(orig_name)
- name = llvm_get_intrinsic_name(intrin_id)
+ intrin_id = llvm.lookup_intrinsic_id(orig_name)
+ name = llvm.get_intrinsic_name(intrin_id)
assert orig_name == name
@@ -107,7 +105,7 @@ def test_llvm_intrinsic_id():
def test_llvm_overloaded_intrin():
# Name lookup for overloaded intrinsics in LLVM 4- requires a name
# that includes the overloaded types.
- if tvm_tirx.codegen.llvm_version_major() < 5:
+ if tvm_tirx.codegen.llvm.version_major() < 5:
return
# int1 is the type for the is_zero_undef parameter
@@ -448,7 +446,7 @@ def test_alignment():
return True
return False
- if tvm_tirx.codegen.llvm_version_major() >= 5:
+ if tvm_tirx.codegen.llvm.version_major() >= 5:
assert has_param_alignment()
# Check for assume intrinsics. This isn't 100% accurate, since it just
@@ -681,9 +679,9 @@ def test_dwarf_debug_information():
C[i0_0 * 4 + i0_1] = A[i0_0 * 4 + i0_1] + B[i0_0 * 4 + i0_1]
def check_llvm_object():
- if tvm_tirx.codegen.llvm_version_major() < 5:
+ if tvm_tirx.codegen.llvm.version_major() < 5:
return
- if tvm_tirx.codegen.llvm_version_major() > 6:
+ if tvm_tirx.codegen.llvm.version_major() > 6:
return
# build two functions
mod = tvm_tirx.IRModule(
@@ -719,9 +717,9 @@ def test_dwarf_debug_information():
assert re.search(r"""DW_AT_name.*fadd2""", str(output))
def check_llvm_ir():
- if tvm_tirx.codegen.llvm_version_major() < 5:
+ if tvm_tirx.codegen.llvm.version_major() < 5:
return
- if tvm_tirx.codegen.llvm_version_major() > 6:
+ if tvm_tirx.codegen.llvm.version_major() > 6:
return
# build two functions
mod = tvm_tirx.IRModule(
diff --git a/tirx/tests/python/codegen/llvm/test_riscv.py b/tirx/tests/python/codegen/llvm/test_riscv.py
index 5ff26a28d0..4182e84925 100644
--- a/tirx/tests/python/codegen/llvm/test_riscv.py
+++ b/tirx/tests/python/codegen/llvm/test_riscv.py
@@ -118,7 +118,7 @@ def test_rvv_vscale_llvm_dbginfo(target):
redsum = T.call_llvm_intrin( 'llvm.riscv.vfredusum', T.Broadcast(T.float32(0.0), T.vscale() * 2), prod, zero, T.uint64(7), T.uint64(8), ty='float32xvscalex2')
# fmt: on
- # tvm.error.InternalError: Can't fetch the lanes of a scalable vector at a compile time.
+ # tvm.RuntimeError: Can't fetch the lanes of a scalable vector at a compile time.
with tvm_tirx.target.Target(target):
f = tvm_tirx.tirx.compile(rvv_with_vscale, target).mod
diff --git a/tirx/tests/python/codegen/llvm/test_scalable_vector.py b/tirx/tests/python/codegen/llvm/test_scalable_vector.py
index 8bb365a728..0e703fbc4a 100644
--- a/tirx/tests/python/codegen/llvm/test_scalable_vector.py
+++ b/tirx/tests/python/codegen/llvm/test_scalable_vector.py
@@ -25,12 +25,12 @@ import pytest
import tvm_tirx
import tvm_tirx.testing
-from tvm_tirx.codegen import llvm_version_major
+from tvm_tirx.codegen import llvm
from tvm_tirx.script import tirx as T
@pytest.mark.skipif(
- llvm_version_major() < 11, reason="Vscale is not supported in earlier versions of LLVM"
+ llvm.version_major() < 11, reason="Vscale is not supported in earlier versions of LLVM"
)
@pytest.mark.parametrize(
"target",
@@ -63,7 +63,7 @@ def test_codegen_vscale(target):
@pytest.mark.skipif(
- llvm_version_major() < 11, reason="Vscale is not supported in earlier versions of LLVM"
+ llvm.version_major() < 11, reason="Vscale is not supported in earlier versions of LLVM"
)
@pytest.mark.parametrize(
"target",
@@ -96,7 +96,7 @@ def test_scalable_buffer_load_store(target):
@pytest.mark.skipif(
- llvm_version_major() < 11, reason="Vscale is not supported in earlier versions of LLVM"
+ llvm.version_major() < 11, reason="Vscale is not supported in earlier versions of LLVM"
)
@pytest.mark.parametrize(
"target",
diff --git a/tirx/tests/python/codegen/llvm/test_x86.py b/tirx/tests/python/codegen/llvm/test_x86.py
index 4c92a3722c..ea32df9b35 100644
--- a/tirx/tests/python/codegen/llvm/test_x86.py
+++ b/tirx/tests/python/codegen/llvm/test_x86.py
@@ -25,7 +25,7 @@ from tvm_tirx.script import ir as I
from tvm_tirx.script import tirx as T
from tvm_tirx.testing import env
-llvm_version = tvm_tirx.codegen.llvm_version_major()
+llvm_version = tvm_tirx.codegen.llvm.version_major()
machine = platform.machine()
if machine not in ["x86_64", "AMD64", "amd64"]:
diff --git a/tirx/tests/python/all-platform-minimal-test/test_validate_runtime_library.py b/tirx/tests/python/runtime/test_validate_wheel_library.py
similarity index 96%
rename from tirx/tests/python/all-platform-minimal-test/test_validate_runtime_library.py
rename to tirx/tests/python/runtime/test_validate_wheel_library.py
index ea92272ea6..eb0a5cc52d 100644
--- a/tirx/tests/python/all-platform-minimal-test/test_validate_runtime_library.py
+++ b/tirx/tests/python/runtime/test_validate_wheel_library.py
@@ -14,9 +14,9 @@
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
-"""Post-install runtime and AOT checks.
+"""Post-install wheel library and AOT checks.
-These live in ``tests/python/all-platform-minimal-test`` so the standard suite and
+These live in ``tests/python/runtime`` so the standard suite and
the cibuildwheel ``test-command`` run a single pytest invocation. The assertions
for wheel packaging check things the rest of the suite cannot check -- that LLVM is
enabled (the other LLVM test merely *skips* when LLVM is absent) and that the CUDA
diff --git a/tirx/tests/python/script/test_basic_usage.py b/tirx/tests/python/script/test_basic_usage.py
index 458d6d2e2c..ecfdda3171 100644
--- a/tirx/tests/python/script/test_basic_usage.py
+++ b/tirx/tests/python/script/test_basic_usage.py
@@ -28,7 +28,7 @@ import pytest
from minilang import Value
import tvm_tirx
-from tvm_tirx import DataType, error, ir
+from tvm_tirx import DataType, ir
from tvm_tirx.ir import prim
from tvm_tirx.ir._overload_prim_expr import EqualOp
from tvm_tirx.script import ir as I
@@ -291,7 +291,7 @@ def test_loop_control_validation_preserves_valid_and_unchecked_ir():
invalid = tirx.Function(params=[], body=tvm_tirx.ir.Break())
ir.assert_structural_equal(invalid.body, tvm_tirx.ir.SeqStmt([tvm_tirx.ir.Break()]))
assert not tirx.analysis.verify_well_formed(invalid, assert_mode=False)
- with pytest.raises(error.InternalError, match="requires an enclosing loop"):
+ with pytest.raises(RuntimeError, match="requires an enclosing loop"):
tirx.analysis.verify_well_formed(invalid)
@T.function
diff --git a/tirx/tests/python/support/test_config.py b/tirx/tests/python/support/test_config.py
index 009847d985..f689b3bbaa 100644
--- a/tirx/tests/python/support/test_config.py
+++ b/tirx/tests/python/support/test_config.py
@@ -139,6 +139,7 @@ def test_cmake_targets_without_ffi(tmp_path):
libdir = _installation(tmp_path / "install")
cmake_dir = libdir / "cmake/tvm_tirx"
shutil.copy2(_CONFIG_PATH, cmake_dir / "config.py")
+ shutil.copy2(_CONFIG_PATH.with_name("libinfo.py"), cmake_dir / "libinfo.py")
shutil.copy2(
_CONFIG_PATH.parents[2] / "cmake/tvm_tirx-config.cmake",
cmake_dir / "tvm_tirx-config.cmake",
@@ -186,13 +187,13 @@ def _check_component_closure_and_artifacts(tmp_path, monkeypatch):
for filename in ("libtvm_runtime_cuda.so", "libtvm_runtime_metal.so", "libtvm_ffi.so"):
(libdir / filename).touch()
monkeypatch.setattr(
- config,
+ config.libinfo,
"_ffi_info",
lambda: SimpleNamespace(find_libtvm_ffi=lambda: str(libdir / "libtvm_ffi.so")),
)
def names(components):
- return [path.name for path in config._link_inputs(libdir, "linux", components)]
+ return [path.name for path in config.libinfo._link_inputs(libdir, "linux", components)]
assert names(["runtime", "cuda", "runtime", "ffi"]) == [
"libtvm_runtime_cuda.so",
@@ -214,7 +215,7 @@ def _check_cli_link_flags_and_raw_inputs(tmp_path, monkeypatch, capsys, platform
for name in ("tvm_runtime", "tvm_tirx_compiler", "tvm_ffi"):
(libdir / f"lib{name}.{suffix}").touch()
monkeypatch.setattr(
- config,
+ config.libinfo,
"_ffi_info",
lambda: SimpleNamespace(find_libtvm_ffi=lambda: str(libdir / f"libtvm_ffi.{suffix}")),
)
@@ -280,5 +281,5 @@ def _check_runtime_only_lib64_and_explicit_prefix_ignore_environment(tmp_path, m
(libdir / "libtvm_tirx_compiler.so").unlink()
unrelated = _installation(tmp_path / "unrelated")
monkeypatch.setenv("TVM_TIRX_LIBRARY_PATH", str(unrelated))
- assert config._paths(prefix, None) == (prefix, libdir)
- assert config._available(libdir, "linux") == ["runtime"]
+ assert config.libinfo._paths(prefix, None) == (prefix, libdir)
+ assert config.libinfo._available(libdir, "linux") == ["runtime"]
diff --git a/tirx/tests/python/target/test_llvm_features_info.py b/tirx/tests/python/target/test_llvm_features_info.py
index 4eb07fd99d..df2b9643d0 100644
--- a/tirx/tests/python/target/test_llvm_features_info.py
+++ b/tirx/tests/python/target/test_llvm_features_info.py
@@ -20,7 +20,7 @@ import tvm_tirx
from tvm_tirx import codegen
from tvm_tirx.target import Target
-LLVM_VERSION = codegen.llvm_version_major()
+LLVM_VERSION = codegen.llvm.version_major()
def test_llvm_targets(capfd):
@@ -29,27 +29,27 @@ def test_llvm_targets(capfd):
##
# check blank results
- assert len(codegen.llvm_get_targets())
- assert len(codegen.llvm_get_system_cpu())
- assert len(codegen.llvm_get_system_triple())
- assert len(codegen.llvm_get_system_x86_vendor())
+ assert len(codegen.llvm.get_targets())
+ assert len(codegen.llvm.get_system_cpu())
+ assert len(codegen.llvm.get_system_triple())
+ assert len(codegen.llvm.get_system_x86_vendor())
# check ffi vs python
assert (
- codegen.llvm_get_system_cpu() == tvm_tirx.get_global_func("codegen.llvm_get_system_cpu")()
+ codegen.llvm.get_system_cpu() == tvm_tirx.get_global_func("codegen.llvm_get_system_cpu")()
)
assert (
- codegen.llvm_get_system_triple()
+ codegen.llvm.get_system_triple()
== tvm_tirx.get_global_func("codegen.llvm_get_system_triple")()
)
assert (
- codegen.llvm_get_system_x86_vendor()
+ codegen.llvm.get_system_x86_vendor()
== tvm_tirx.get_global_func("codegen.llvm_get_system_x86_vendor")()
)
- assert str(codegen.llvm_get_targets()) == str(
+ assert str(codegen.llvm.get_targets()) == str(
tvm_tirx.get_global_func("codegen.llvm_get_targets")()
)
- tvm_tirx.codegen.llvm_get_cpu_features(
+ tvm_tirx.codegen.llvm.get_cpu_features(
tvm_tirx.target.Target({"kind": "llvm", "mtriple": "x86_64-linux-gnu", "mcpu": "dummy"})
)
expected_str = (
@@ -86,7 +86,7 @@ def test_target_features(min_llvm_version, llvm_target, cpu_arch, cpu_features,
## legalize llvm_target
##
- assert llvm_target in codegen.llvm_get_targets()
+ assert llvm_target in codegen.llvm.get_targets()
##
## legalize cpu_arch
@@ -94,11 +94,11 @@ def test_target_features(min_llvm_version, llvm_target, cpu_arch, cpu_features,
### with context
with target:
- assert cpu_arch in codegen.llvm_get_cpu_archlist()
+ assert cpu_arch in codegen.llvm.get_cpu_archlist()
### no context but with expicit target
- assert cpu_arch in codegen.llvm_get_cpu_archlist(target)
+ assert cpu_arch in codegen.llvm.get_cpu_archlist(target)
# check ffi vs python
- assert str(codegen.llvm_get_cpu_archlist(target)) == str(
+ assert str(codegen.llvm.get_cpu_archlist(target)) == str(
tvm_tirx.get_global_func("codegen.llvm_get_cpu_archlist")(target)
)
@@ -108,11 +108,11 @@ def test_target_features(min_llvm_version, llvm_target, cpu_arch, cpu_features,
### with context
with target:
- assert codegen.llvm_cpu_has_features(cpu_features) == is_supported
+ assert codegen.llvm.cpu_has_features(cpu_features) == is_supported
### no context but with expicit target
- assert codegen.llvm_cpu_has_features(cpu_features, target) == is_supported
+ assert codegen.llvm.cpu_has_features(cpu_features, target) == is_supported
# check ffi vs python
for feat in cpu_features:
- assert str(codegen.llvm_cpu_has_features(feat, target)) == str(
+ assert str(codegen.llvm.cpu_has_features(feat, target)) == str(
tvm_tirx.get_global_func("codegen.llvm_cpu_has_feature")(feat, target)
)
diff --git a/tirx/tests/python/target/test_riscv_features.py b/tirx/tests/python/target/test_riscv_features.py
index 3a805c4270..c81ca2e4c4 100644
--- a/tirx/tests/python/target/test_riscv_features.py
+++ b/tirx/tests/python/target/test_riscv_features.py
@@ -19,10 +19,10 @@ import pytest
import tvm_tirx
from tvm_tirx import codegen
-from tvm_tirx.codegen import llvm_get_vector_width, target_has_features
+from tvm_tirx.codegen import llvm, target_has_features
from tvm_tirx.target import Target
-LLVM_VERSION = codegen.llvm_version_major()
+LLVM_VERSION = codegen.llvm.version_major()
# fmt: off
@@ -63,4 +63,4 @@ def test_riscv_rvv_features(min_llvm_version, tvm_target, vec_width):
return
with Target(tvm_target):
- assert llvm_get_vector_width() == vec_width
+ assert llvm.get_vector_width() == vec_width
diff --git a/tirx/tests/python/target/test_x86_features.py b/tirx/tests/python/target/test_x86_features.py
index d638d202c6..59da3b2015 100644
--- a/tirx/tests/python/target/test_x86_features.py
+++ b/tirx/tests/python/target/test_x86_features.py
@@ -22,7 +22,7 @@ from tvm_tirx import codegen
from tvm_tirx.codegen import target_has_features
from tvm_tirx.target import Target
-LLVM_VERSION = codegen.llvm_version_major()
+LLVM_VERSION = codegen.llvm.version_major()
# Some x86 features have been removed from upstream LLVM. Tests for these
# features only meaningfully run on LLVM versions that still recognise them.
@@ -197,7 +197,7 @@ def test_x86_target_features(min_llvm_version, tvm_target, x86_feature, is_suppo
try:
assert target_has_features(x86_feature) == is_supported
assert False
- except tvm_tirx.error.InternalError as e:
+ except RuntimeError as e:
msg = str(e)
assert msg.find("Check failed: (allow_not_defined) is false: Target context required") != -1
@@ -209,7 +209,7 @@ def test_x86_target_features(min_llvm_version, tvm_target, x86_feature, is_suppo
== is_supported
)
assert False
- except tvm_tirx.error.InternalError as e:
+ except RuntimeError as e:
msg = str(e)
assert (
msg.find("Check failed: (allow_not_defined) is false: Target context required")
@@ -253,4 +253,4 @@ def test_x86_target_features(min_llvm_version, tvm_target, x86_feature, is_suppo
) == is_supported
# check for feature in target's llvm full x86 CPU feature list
if (not list(Target(tvm_target).attrs.get("mattr", []))) and isinstance(x86_feature, str):
- assert (x86_feature in codegen.llvm_get_cpu_features()) == is_supported
+ assert (x86_feature in codegen.llvm.get_cpu_features()) == is_supported
diff --git a/tirx/tests/python/testing/test_env.py b/tirx/tests/python/testing/test_env.py
deleted file mode 100644
index 2f7105b6be..0000000000
--- a/tirx/tests/python/testing/test_env.py
+++ /dev/null
@@ -1,332 +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.
-"""Tests for the thin ``tvm_tirx.testing.env`` capability probes."""
-
-import subprocess
-import sys
-import textwrap
-from types import SimpleNamespace
-
-import pytest
-
-import tvm_tirx
-import tvm_tirx.testing
-from tvm_tirx.testing import env
-
-# Probes that take no arguments and must return a plain bool without raising.
-_BOOL_PROBES = [
- # runtime device
- env.has_cuda,
- env.has_rocm,
- env.has_vulkan,
- env.has_metal,
- env.has_opencl,
- env.has_nvptx,
- env.has_llvm,
- env.has_gpu,
- # build support
- env.has_cudnn,
- env.has_cublas,
- env.has_nccl,
- env.has_hipblas,
- env.has_nvshmem,
- # version / capability
- env.has_matrixcore,
- env.has_cudagraph,
- # toolchain / environment
- env.has_hexagon,
- env.has_hexagon_toolchain,
- env.has_adreno_opencl,
- # cpu features
- env.has_x86_vnni,
- env.has_x86_avx512,
- # host architecture
-]
-
-
-@pytest.mark.parametrize("probe", _BOOL_PROBES, ids=lambda p: p.__name__)
-def test_probe_returns_bool(probe):
- """Every probe returns a real bool and never raises during collection/run."""
- assert isinstance(probe(), bool)
-
-
-def test_has_cuda_implies_device():
- """has_cuda() requires a device (it also requires the kind to be enabled)."""
- if env.has_cuda():
- assert tvm_tirx.cuda().exist
-
-
-def test_has_gpu_is_raw_any_device():
- """has_gpu() is the disjunction of the raw device checks (no target gating)."""
- any_device = (
- env._device_exists("cuda") # pylint: disable=protected-access
- or env._device_exists("rocm") # pylint: disable=protected-access
- or env._device_exists("opencl") # pylint: disable=protected-access
- or env._device_exists("metal") # pylint: disable=protected-access
- or env._device_exists("vulkan") # pylint: disable=protected-access
- )
- assert env.has_gpu() == any_device
-
-
-def test_target_enabled_respects_tvm_test_targets(monkeypatch):
- """A device kind excluded from TVM_TEST_TARGETS is reported as not enabled."""
- env._target_enabled.cache_clear() # pylint: disable=protected-access
- monkeypatch.setenv("TVM_TEST_TARGETS", "cuda;llvm")
- try:
- assert env._target_enabled("cuda") # pylint: disable=protected-access
- assert env._target_enabled("llvm") # pylint: disable=protected-access
- assert not env._target_enabled("opencl") # pylint: disable=protected-access
- assert not env._target_enabled("metal") # pylint: disable=protected-access
- finally:
- env._target_enabled.cache_clear() # pylint: disable=protected-access
-
-
-def test_cuda_compute_is_monotonic():
- """has_cuda_compute is monotone in the requested version."""
- if not env.has_cuda():
- # Without a CUDA device every query is False, including the (0, 0) floor.
- assert not env.has_cuda_compute(1, 0)
- assert not env.has_cuda_compute(0, 0)
- return
- # A device that satisfies (major, minor) also satisfies anything lower.
- assert env.has_cuda_compute(1, 0)
- assert env.has_cuda_compute(0, 0)
-
-
-@pytest.mark.parametrize(
- ("compute_version", "expected"),
- [
- ("8.0", "sm_80"),
- ("9.0", "sm_90a"),
- ("10.0", "sm_100a"),
- ("10.3", "sm_103a"),
- ("invalid", None),
- ],
-)
-def test_cuda_arch_from_compute_version(compute_version, expected):
- assert env._cuda_arch_from_compute_version(compute_version) == expected
-
-
-def test_has_cuda_arch_matches_detected_device():
- actual = env.cuda_arch()
- if actual is None:
- assert not env.has_cuda_arch("sm_100a")
- else:
- assert env.has_cuda_arch(actual)
-
-
-def test_cuda_arch_uses_requested_device(monkeypatch):
- class Device:
- exist = True
- compute_version = "10.3"
-
- requested = []
-
- def cuda(device_id):
- requested.append(device_id)
- return Device()
-
- env.cuda_arch.cache_clear()
- monkeypatch.setattr(tvm_tirx, "cuda", cuda)
- try:
- assert env.cuda_arch(7) == "sm_103a"
- assert requested == [7]
- finally:
- env.cuda_arch.cache_clear()
-
-
-def test_has_multi_gpu_is_bool():
- assert isinstance(env.has_multi_gpu(), bool)
- assert isinstance(env.has_multi_gpu(1), bool)
- # Requiring a single device is at least as permissive as requiring two.
- assert env.has_multi_gpu(1) or not env.has_multi_gpu(2)
-
-
-def test_llvm_min_version_is_monotone():
- if not env.has_llvm():
- assert not env.has_llvm_min_version(1)
- return
- # An LLVM that satisfies a higher floor also satisfies a lower one.
- assert env.has_llvm_min_version(1)
-
-
-def test_probes_are_memoized():
- """Probes are cached so the driver/subprocess is hit once per process."""
- env.has_cuda()
- info = env._device_exists.cache_info() # pylint: disable=protected-access
- assert info.hits + info.misses >= 1
-
-
-@pytest.fixture
-def clear_env_cache():
- probes = (
- env._target_enabled,
- env._runtime_enabled,
- env._device_exists,
- env.build_flag_enabled,
- env._llvm_version_major,
- env.has_hexagon_toolchain,
- env.has_hexagon,
- )
- for probe in probes:
- probe.cache_clear()
- yield
- for probe in probes:
- probe.cache_clear()
-
-
-def test_unavailable_selected_target_does_not_enable_llvm(monkeypatch, clear_env_cache):
- monkeypatch.setenv("TVM_TEST_TARGETS", "cuda")
- monkeypatch.setattr(tvm_tirx.runtime, "enabled", lambda kind: kind == "llvm")
-
- def unexpected_device_lookup(target):
- pytest.fail(f"Excluded or unavailable target was probed: {target}")
-
- monkeypatch.setattr(tvm_tirx, "device_from_target", unexpected_device_lookup)
- assert not tvm_tirx.testing.device_enabled("cuda")
- assert not tvm_tirx.testing.device_enabled("llvm")
-
-
-@pytest.mark.parametrize("target_form", ["string", "dict", "target"])
-def test_device_enabled_accepts_target_forms(monkeypatch, clear_env_cache, target_form):
- monkeypatch.setenv("TVM_TEST_TARGETS", '{"kind": "llvm"};cuda')
- monkeypatch.setattr(tvm_tirx.runtime, "enabled", lambda kind: kind == "llvm")
- monkeypatch.setattr(tvm_tirx, "device_from_target", lambda target: SimpleNamespace(exist=True))
- target = {
- "string": "llvm -num-cores=2",
- "dict": {"kind": "llvm", "num-cores": 2},
- "target": tvm_tirx.target.Target({"kind": "llvm", "num-cores": 2}),
- }[target_form]
- assert tvm_tirx.testing.device_enabled(target)
-
-
-@pytest.mark.parametrize("kind", ["llvm", "cuda"])
-@pytest.mark.parametrize(
- ("runtime_enabled", "device_exists", "expected"),
- [(False, True, False), (True, False, False), (True, True, True)],
-)
-def test_device_enabled_requires_runtime_and_device(
- monkeypatch, clear_env_cache, kind, runtime_enabled, device_exists, expected
-):
- # In particular, the CPU can exist even when LLVM was not built.
- monkeypatch.setenv("TVM_TEST_TARGETS", kind)
- monkeypatch.setattr(tvm_tirx.runtime, "enabled", lambda target: runtime_enabled)
- monkeypatch.setattr(
- tvm_tirx, "device_from_target", lambda target: SimpleNamespace(exist=device_exists)
- )
- assert tvm_tirx.testing.device_enabled(kind) is expected
-
-
-@pytest.mark.parametrize("cudnn_available", [None, False, True])
-def test_device_enabled_cudnn_runtime_probe(monkeypatch, clear_env_cache, cudnn_available):
- monkeypatch.setenv("TVM_TEST_TARGETS", '{"kind": "cuda", "libs": ["cudnn"]}')
- monkeypatch.setattr(tvm_tirx.runtime, "enabled", lambda kind: True)
- monkeypatch.setattr(tvm_tirx, "device", lambda *args: SimpleNamespace(exist=True))
- monkeypatch.setattr(tvm_tirx.support, "libinfo", lambda: {"USE_CUDNN": "ON"})
- exists = None if cudnn_available is None else lambda: cudnn_available
- monkeypatch.setattr(tvm_tirx, "get_global_func", lambda name, allow_missing: exists)
- assert tvm_tirx.testing.device_enabled("cuda") is (cudnn_available is True)
-
-
-@pytest.mark.parametrize(
- ("runtime", "toolchain", "llvm_target", "serial", "can_compile", "can_run"),
- [
- (False, True, True, True, True, False),
- (True, False, True, True, False, False),
- (True, True, False, True, False, False),
- (True, True, True, False, True, False),
- (True, True, True, True, True, True),
- (True, True, None, True, False, False),
- ],
-)
-def test_hexagon_environment_requirements(
- monkeypatch, clear_env_cache, runtime, toolchain, llvm_target, serial, can_compile, can_run
-):
- monkeypatch.setenv("TVM_TEST_TARGETS", "hexagon")
- for variable, present in (
- ("HEXAGON_TOOLCHAIN", toolchain),
- ("ANDROID_SERIAL_NUMBER", serial),
- ):
- if present:
- monkeypatch.setenv(variable, "test-value")
- else:
- monkeypatch.delenv(variable, raising=False)
- monkeypatch.setattr(
- tvm_tirx.runtime,
- "enabled",
- lambda kind: runtime if kind == "hexagon" else llvm_target is not None,
- )
- monkeypatch.setattr(
- tvm_tirx.codegen, "llvm_get_targets", lambda: ["hexagon"] if llvm_target else []
- )
- assert env.has_hexagon_toolchain() is can_compile
- assert env.has_hexagon() is can_run
-
-
-def test_core_testing_imports_without_domain_modules():
- # Let TVM finish its own startup, then make the domain modules unavailable to testing.
- code = textwrap.dedent(
- """
- import os
- import sys
- import tvm_tirx
-
- for module in list(sys.modules):
- if module == "tvm_tirx.testing" or module.startswith("tvm_tirx.testing."):
- del sys.modules[module]
- if hasattr(tvm_tirx, "testing"):
- del tvm_tirx.testing
-
- for name in ("te", "contrib", "s_tir"):
- prefix = "tvm_tirx." + name
- for module in list(sys.modules):
- if module == prefix or module.startswith(prefix + "."):
- sys.modules[module] = None
- sys.modules[prefix] = None
- if hasattr(tvm_tirx, name):
- delattr(tvm_tirx, name)
-
- import tvm_tirx.testing
- from tvm_tirx.testing import env
-
- tvm_tirx.testing.assert_allclose([1], [1])
- tvm_tirx.runtime.enabled = lambda kind: True
- tvm_tirx.codegen.llvm_get_targets = lambda: ["hexagon"]
- os.environ["HEXAGON_TOOLCHAIN"] = "test-toolchain"
- os.environ["ANDROID_SERIAL_NUMBER"] = "test-device"
- assert env.has_hexagon_toolchain()
- assert env.has_hexagon()
- """
- )
- subprocess.run([sys.executable, "-c", code], check=True, capture_output=True, text=True)
-
-
-# --- demonstration of the target idiom -------------------------------------
-#
-# The standard gating idiom: a plain registered pytest marker (for ``-m``
-# selection) plus a skipif backed by a thin env probe (for runtime gating).
-
-
-@pytest.mark.gpu
-@pytest.mark.skipif(not env.has_cuda(), reason="need cuda")
-def test_thin_cuda_idiom():
- dev = tvm_tirx.cuda()
- assert dev.exist
-
-
-if __name__ == "__main__":
- tvm_tirx.testing.main()
diff --git a/tirx/tests/python/tirx/analysis/test_check_well_defined.py b/tirx/tests/python/tirx/analysis/test_check_well_defined.py
index 6545216b5d..5e35f9ff2e 100644
--- a/tirx/tests/python/tirx/analysis/test_check_well_defined.py
+++ b/tirx/tests/python/tirx/analysis/test_check_well_defined.py
@@ -66,7 +66,7 @@ def test_error_for_out_of_scope_usage():
func = tvm_tirx.tirx.Function([], body)
with pytest.raises(
- (ValueError, tvm_tirx.error.InternalError),
+ (ValueError, RuntimeError),
match="Invalid use of undefined variable i at .* no longer in-scope.",
):
tvm_tirx.tirx.analysis.verify_well_formed(func)
@@ -84,7 +84,7 @@ def test_error_for_nested_rebind_usage():
T.evaluate(i)
with pytest.raises(
- (ValueError, tvm_tirx.error.InternalError),
+ (ValueError, RuntimeError),
match="ill-formed, due to multiple nested definitions of variable i",
):
tvm_tirx.tirx.analysis.verify_well_formed(func)
@@ -108,7 +108,7 @@ def test_error_for_repeated_binding():
T.evaluate(i)
with pytest.raises(
- (ValueError, tvm_tirx.error.InternalError),
+ (ValueError, RuntimeError),
match="multiple nested definitions of variable i",
):
tvm_tirx.tirx.analysis.verify_well_formed(func)
@@ -131,9 +131,7 @@ def test_error_for_cross_function_reuse():
T.bind(42, var=i)
T.evaluate(i)
- with pytest.raises(
- (ValueError, tvm_tirx.error.InternalError), match="multiple definitions of variable i"
- ):
+ with pytest.raises((ValueError, RuntimeError), match="multiple definitions of variable i"):
tvm_tirx.tirx.analysis.verify_well_formed(mod)
@@ -177,7 +175,7 @@ def test_reuse_of_region_parameter_across_functions_is_ill_formed():
A[threadIdx_x] = A[threadIdx_x] + T.float32(1)
with pytest.raises(
- (ValueError, tvm_tirx.error.InternalError),
+ (ValueError, RuntimeError),
match="multiple definitions of variable threadIdx_x",
):
tvm_tirx.tirx.analysis.verify_well_formed(mod)
@@ -222,7 +220,7 @@ def test_error_message_without_previous_definition_location():
T.bind(99, var=x) # This should trigger the error
T.evaluate(x)
- with pytest.raises((ValueError, tvm_tirx.error.InternalError)) as exc_info:
+ with pytest.raises((ValueError, RuntimeError)) as exc_info:
tvm_tirx.tirx.analysis.verify_well_formed(func, assert_mode=True)
error_msg = str(exc_info.value)
@@ -247,7 +245,7 @@ def test_error_message_with_previous_definition_location():
T.bind(99, var=x) # This should trigger the error
T.evaluate(x)
- with pytest.raises((ValueError, tvm_tirx.error.InternalError)) as exc_info:
+ with pytest.raises((ValueError, RuntimeError)) as exc_info:
tvm_tirx.tirx.analysis.verify_well_formed(func, assert_mode=True)
error_msg = str(exc_info.value)
@@ -278,7 +276,7 @@ def test_sequential_redefinition_with_location():
T.bind(2, var=x) # This should trigger the error
T.evaluate(x)
- with pytest.raises((ValueError, tvm_tirx.error.InternalError)) as exc_info:
+ with pytest.raises((ValueError, RuntimeError)) as exc_info:
tvm_tirx.tirx.analysis.verify_well_formed(func, assert_mode=True)
error_msg = str(exc_info.value)
@@ -349,7 +347,7 @@ def test_tensor_load_asserted_type_matches_source_and_indices():
malformed = tvm_tirx.ir.load_json(json.dumps(graph))
assert not tvm_tirx.tirx.analysis.verify_well_formed(malformed, assert_mode=False)
- with pytest.raises(tvm_tirx.error.InternalError, match="asserts result type"):
+ with pytest.raises(RuntimeError, match="asserts result type"):
tvm_tirx.tirx.analysis.verify_well_formed(malformed)
@@ -368,13 +366,13 @@ def test_tensor_load_malformed_indices_return_false_without_asserting():
rank_mismatch_indices.pop()
rank_mismatch = tvm_tirx.ir.load_json(json.dumps(rank_mismatch_graph))
assert not tvm_tirx.tirx.analysis.verify_well_formed(rank_mismatch, assert_mode=False)
- with pytest.raises(tvm_tirx.error.InternalError, match="indexes 2-dimensional tensor"):
+ with pytest.raises(RuntimeError, match="indexes 2-dimensional tensor"):
tvm_tirx.tirx.analysis.verify_well_formed(rank_mismatch)
indices[0], indices[1] = indices[1], indices[0]
non_final_vector = tvm_tirx.ir.load_json(json.dumps(graph))
assert not tvm_tirx.tirx.analysis.verify_well_formed(non_final_vector, assert_mode=False)
- with pytest.raises(tvm_tirx.error.InternalError, match="only the final index"):
+ with pytest.raises(RuntimeError, match="only the final index"):
tvm_tirx.tirx.analysis.verify_well_formed(non_final_vector)
diff --git a/tirx/tests/python/tirx/base/test_imm_values.py b/tirx/tests/python/tirx/base/test_imm_values.py
index f267b63bce..1eb03c33cd 100644
--- a/tirx/tests/python/tirx/base/test_imm_values.py
+++ b/tirx/tests/python/tirx/base/test_imm_values.py
@@ -59,8 +59,8 @@ def test_tir_invalid_intimm(dtype, literals):
for l in literals:
# Out-of-range positive literals raise a builtin ValueError from
# the IntImm range check; negative-into-unsigned raises an
- # InternalError ("cannot make uint from negative value") which is a
- # RuntimeError subclass. Accept either.
+ # InternalError ("cannot make uint from negative value") mapped to
+ # RuntimeError. Accept either.
with pytest.raises((RuntimeError, ValueError)):
tirx.const(l, dtype)
diff --git a/tirx/tests/python/tirx/base/test_scalable_datatype.py b/tirx/tests/python/tirx/base/test_scalable_datatype.py
index 45bb8f4553..a5a11a9759 100644
--- a/tirx/tests/python/tirx/base/test_scalable_datatype.py
+++ b/tirx/tests/python/tirx/base/test_scalable_datatype.py
@@ -19,7 +19,7 @@ import pytest
import tvm_tirx
from tvm_tirx import tirx
-from tvm_tirx.codegen import llvm_version_major
+from tvm_tirx.codegen import llvm
from tvm_tirx.script import tirx as T
"""
@@ -36,11 +36,11 @@ def test_create_scalable_data_type_python_api():
# the old name from the intrinsic table:
# https://releases.llvm.org/20.1.0/docs/ReleaseNotes.html
_STEPVECTOR_NAME = (
- "llvm.stepvector" if llvm_version_major() >= 20 else "llvm.experimental.stepvector"
+ "llvm.stepvector" if llvm.version_major() >= 20 else "llvm.experimental.stepvector"
)
-@pytest.mark.skipif(llvm_version_major() < 13, reason="Stepvector intrinsic was added in LLVM 13.")
+@pytest.mark.skipif(llvm.version_major() < 13, reason="Stepvector intrinsic was added in LLVM 13.")
def test_create_scalable_tir_intrin():
intrin = tirx.call_llvm_intrin(_STEPVECTOR_NAME, ty="int32xvscalex4")
assert intrin.ty.dtype == "int32xvscalex4"
@@ -49,7 +49,7 @@ def test_create_scalable_tir_intrin():
)
-@pytest.mark.skipif(llvm_version_major() < 13, reason="Stepvector intrinsic was added in LLVM 13.")
+@pytest.mark.skipif(llvm.version_major() < 13, reason="Stepvector intrinsic was added in LLVM 13.")
def test_tvm_script_create_scalable_tir_intrin():
@T.function
def my_func():
diff --git a/tirx/tests/python/tirx/codegen/test_cuda.py b/tirx/tests/python/tirx/codegen/test_cuda.py
index 3918130d40..1bb95ed34e 100644
--- a/tirx/tests/python/tirx/codegen/test_cuda.py
+++ b/tirx/tests/python/tirx/codegen/test_cuda.py
@@ -187,9 +187,7 @@ def test_legacy_tensorcore_ops_require_downstream_codegen(op_name):
"global_symbol", "main"
)
target = tvm_tirx.target.Target({"kind": "cuda", "arch": "sm_80"})
- with pytest.raises(
- tvm_tirx.error.InternalError, match="Unresolved call.*" + re.escape(call.op.name)
- ):
+ with pytest.raises(RuntimeError, match="Unresolved call.*" + re.escape(call.op.name)):
tvm_tirx.get_global_func("target.build.cuda")(tvm_tirx.IRModule.from_expr(func), target)
@@ -204,7 +202,7 @@ def test_warp_storage_requires_explicit_local_layout(target_kind):
output[0] = fragment[0]
target = tvm_tirx.target.Target(target_kind)
- with pytest.raises(tvm_tirx.error.InternalError, match="warp storage is unsupported"):
+ with pytest.raises(RuntimeError, match="warp storage is unsupported"):
tvm_tirx.get_global_func("target.build." + target_kind)(
tvm_tirx.IRModule.from_expr(main), target
)
diff --git a/tirx/tests/python/tirx/codegen/test_hopper.py b/tirx/tests/python/tirx/codegen/test_hopper.py
index 23cbff0d9c..fad00405a7 100644
--- a/tirx/tests/python/tirx/codegen/test_hopper.py
+++ b/tirx/tests/python/tirx/codegen/test_hopper.py
@@ -608,7 +608,7 @@ def test_cp_async_bulk_tensor_global_to_shared_unicast(dtype, inputs):
],
)
def test_tensormap_encode_tiled_runtime_validation(shape, dtype, encode_args, error_msg):
- with pytest.raises(tvm_tirx.error.InternalError, match=error_msg):
+ with pytest.raises(RuntimeError, match=error_msg):
_run_tensormap_encode(shape, dtype, encode_args)
diff --git a/tirx/tests/python/tirx/codegen/test_ptx_addr.py b/tirx/tests/python/tirx/codegen/test_ptx_addr.py
index 5d9cf124ee..e4bf18de4b 100644
--- a/tirx/tests/python/tirx/codegen/test_ptx_addr.py
+++ b/tirx/tests/python/tirx/codegen/test_ptx_addr.py
@@ -225,9 +225,7 @@ def test_ptx_addr_unrolled_expression_and_dynamic_rejection():
T.ptx.ld.global_.b32(value, T.ptx.addr(src.data, i * 4))
for func in (thread_dynamic, loop_dynamic):
- with pytest.raises(
- (ValueError, tvm_tirx.error.InternalError), match="must become a compile-time"
- ):
+ with pytest.raises((ValueError, RuntimeError), match="must become a compile-time"):
_cuda_source(func)
diff --git a/tirx/tests/python/tirx/codegen/test_ptx_dialect.py b/tirx/tests/python/tirx/codegen/test_ptx_dialect.py
index df7c3438ba..a30a0e516a 100644
--- a/tirx/tests/python/tirx/codegen/test_ptx_dialect.py
+++ b/tirx/tests/python/tirx/codegen/test_ptx_dialect.py
@@ -1842,7 +1842,7 @@ def test_ptx_logic_shift_dispatch():
d = T.local_scalar("uint32")
T.ptx.lop3.b32(d, A[0], A[0], A[0], A[0])
- with pytest.raises((ValueError, tvm_tirx.error.InternalError), match="compile-time constants"):
+ with pytest.raises((ValueError, RuntimeError), match="compile-time constants"):
_cuda_source(lut_runtime)
@T.function
diff --git a/tirx/tests/python/tirx/script/test_basic_usage.py b/tirx/tests/python/tirx/script/test_basic_usage.py
index 7d8dce025f..b2c048f047 100644
--- a/tirx/tests/python/tirx/script/test_basic_usage.py
+++ b/tirx/tests/python/tirx/script/test_basic_usage.py
@@ -229,7 +229,7 @@ from tvm_tirx.script import tirx as T
def func():
x: T.handle = T.int64(0)
"""
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
from_source(src_handle)
# 3. Banned: non-PrimType annotation without T.let
@@ -240,7 +240,7 @@ from tvm_tirx.ir import PtrType, PrimType
def func():
x: T.Var(name="x", ty=PtrType(PrimType("float16"))) = T.int64(0)
"""
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
from_source(src_ptr)
# 4. An explicit mutable scalar declaration retains updates — round-trip
@@ -571,14 +571,14 @@ def test_thread_return_is_distinct_from_function_return():
def test_loop_control_validation_preserves_valid_and_unchecked_ir():
# Invalid loop placement must be rejected, while disabled checks preserve the original IR.
- from tvm_tirx import error, ir, tirx
+ from tvm_tirx import ir, tirx
invalid = tirx.Function(params=[], body=tvm_tirx.ir.Break())
# Direct construction retains the native statement for an explicit verifier pass.
ir.assert_structural_equal(invalid.body, tvm_tirx.ir.SeqStmt([tvm_tirx.ir.Break()]))
assert not tirx.analysis.verify_well_formed(invalid, assert_mode=False)
- with pytest.raises(error.InternalError, match="requires an enclosing loop"):
+ with pytest.raises(RuntimeError, match="requires an enclosing loop"):
tirx.analysis.verify_well_formed(invalid)
@T.function
diff --git a/tirx/tests/python/tirx/test_cuda_backend_config.py b/tirx/tests/python/tirx/test_cuda_backend_config.py
index 1eaba7425a..b8b044eee9 100644
--- a/tirx/tests/python/tirx/test_cuda_backend_config.py
+++ b/tirx/tests/python/tirx/test_cuda_backend_config.py
@@ -599,7 +599,7 @@ def test_legacy_payloads():
current = old_binary + string(snapshot.encode())
assert load(current).inspect_source("backend_config") == snapshot
for malformed in (old_binary + b"x", current[:-1], current + b"x"):
- with pytest.raises(tvm_tirx.error.InternalError):
+ with pytest.raises(RuntimeError):
load(malformed)
diff --git a/tirx/tests/python/tirx/tile/test_dispatcher.py b/tirx/tests/python/tirx/tile/test_dispatcher.py
index c4c0ce11d6..eeb9000aec 100644
--- a/tirx/tests/python/tirx/tile/test_dispatcher.py
+++ b/tirx/tests/python/tirx/tile/test_dispatcher.py
@@ -158,7 +158,7 @@ def test_residual_tile_call_is_rejected():
call.op.name, "FTileOpDispatch", lambda call, context: Function([], Evaluate(0))
)
# Dispatch expands statement-boundary Calls; other positions must be rejected.
- with pytest.raises(tvm_tirx.error.InternalError, match="Failed to lower the TIRx program"):
+ with pytest.raises(RuntimeError, match="Failed to lower the TIRx program"):
_lower(Return(call))
diff --git a/tirx/tests/python/tirx/transform/test_lower_tirx.py b/tirx/tests/python/tirx/transform/test_lower_tirx.py
index 51335b0bab..d27649f222 100644
--- a/tirx/tests/python/tirx/transform/test_lower_tirx.py
+++ b/tirx/tests/python/tirx/transform/test_lower_tirx.py
@@ -897,7 +897,7 @@ def test_lower_layout():
@pytest.mark.parametrize(
"target,error,message",
[
- (None, tvm_tirx.error.InternalError, "Target context required"),
+ (None, RuntimeError, "Target context required"),
("cuda", RuntimeError, "An explicit layout is required for shared tensors"),
],
ids=["missing-target", "missing-shared-layout"],
diff --git a/tirx/tests/python/tirx/transform/test_make_packed_api.py b/tirx/tests/python/tirx/transform/test_make_packed_api.py
index 19367b4014..b7d807a8f7 100644
--- a/tirx/tests/python/tirx/transform/test_make_packed_api.py
+++ b/tirx/tests/python/tirx/transform/test_make_packed_api.py
@@ -692,9 +692,7 @@ def test_return_from_parallel_scope_is_rejected():
for i in T.parallel(2):
return i
- with pytest.raises(
- tvm_tirx.error.InternalError, match="Return cannot be used in parallel scope"
- ):
+ with pytest.raises(RuntimeError, match="Return cannot be used in parallel scope"):
tvm_tirx.tirx.transform.MakePackedAPI()(Before)
diff --git a/tirx/tests/python/tirx/transform/test_split_host_device.py b/tirx/tests/python/tirx/transform/test_split_host_device.py
index c08edbc037..0fb2059989 100644
--- a/tirx/tests/python/tirx/transform/test_split_host_device.py
+++ b/tirx/tests/python/tirx/transform/test_split_host_device.py
@@ -169,7 +169,7 @@ def test_device_kernel_nonzero_return_is_rejected():
)
return 1
- with pytest.raises(tvm_tirx.error.InternalError, match="successful return"):
+ with pytest.raises(RuntimeError, match="successful return"):
tvm_tirx.tirx.transform.SplitHostDevice()(Before)
diff --git a/tirx/tests/python/tirx/transform/test_vectorize.py b/tirx/tests/python/tirx/transform/test_vectorize.py
index d1f42b8b77..7093fbe203 100644
--- a/tirx/tests/python/tirx/transform/test_vectorize.py
+++ b/tirx/tests/python/tirx/transform/test_vectorize.py
@@ -18,7 +18,7 @@ import pytest
import tvm_tirx
import tvm_tirx.testing
-from tvm_tirx.codegen import llvm_version_major
+from tvm_tirx.codegen import llvm
from tvm_tirx.script import ir as I
from tvm_tirx.script import tirx as T
@@ -84,7 +84,7 @@ def test_vectorize_vector_scalable_error():
A[T.ramp(j * 4, 1, 4)] = T.Broadcast(T.float32(1), 4)
error_msg = "Creating scalable vectors from existing vectors is not supported."
- with pytest.raises(tvm_tirx.error.InternalError, match=error_msg):
+ with pytest.raises(RuntimeError, match=error_msg):
tvm_tirx.tirx.transform.VectorizeLoop()(Module)
@@ -97,7 +97,7 @@ def test_vectorize_vector_scalable_error2():
A[j] = T.Broadcast(T.float32(1), T.vscale() * 4)
error_msg = "Vectorizing over scalable tensor elements is not supported in vectorizer."
- with pytest.raises(tvm_tirx.error.InternalError, match=error_msg):
+ with pytest.raises(RuntimeError, match=error_msg):
tvm_tirx.tirx.transform.VectorizeLoop()(Module)
@@ -113,7 +113,7 @@ def test_vectorize_vector_scalable_error3():
)
error_msg = "Vectorizing over existing scalable vectors is not supported."
- with pytest.raises(tvm_tirx.error.InternalError, match=error_msg):
+ with pytest.raises(RuntimeError, match=error_msg):
tvm_tirx.tirx.transform.VectorizeLoop()(Module)
@@ -129,7 +129,7 @@ def test_vectorize_vector_scalable_error4():
)
error_msg = "Creating scalable vectors from existing vectors is not supported."
- with pytest.raises(tvm_tirx.error.InternalError, match=error_msg):
+ with pytest.raises(RuntimeError, match=error_msg):
tvm_tirx.tirx.transform.VectorizeLoop()(Module)
@@ -509,7 +509,7 @@ def test_illegal_extent():
A[j] = 3
error_msg = r"Failed to vectorize loop with extent n for target None"
- with pytest.raises(tvm_tirx.error.InternalError, match=error_msg):
+ with pytest.raises(RuntimeError, match=error_msg):
tvm_tirx.tirx.transform.VectorizeLoop()(Mod)
@@ -523,7 +523,7 @@ def test_illegal_vscale_in_non_sve_compilation():
A[j] = 13
msg = "Failed to vectorize loop with extent T.vscale\\(\\) \\* 4 for target"
- with pytest.raises(tvm_tirx.error.InternalError, match=msg):
+ with pytest.raises(RuntimeError, match=msg):
tvm_tirx.tirx.transform.VectorizeLoop()(Mod)
@@ -877,7 +877,7 @@ def test_vectorize_llvm_pure_intrin_fail(extent, vec_str, target):
# LLVM 20 added vector support for llvm.lround/llvm.llround. The IR Verifier's
# "Intrinsic does not support vectors" check was removed in release/20.x, so
# compilation only fails on LLVM <= 19.
- if llvm_version_major() >= 20:
+ if llvm.version_major() >= 20:
tvm_tirx.tirx.compile(mod, target=target)
else:
with pytest.raises(Exception, match="Intrinsic does not support vectors"):