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/06/26 11:18:11 UTC
(tvm) branch main updated: [REFACTOR][Relax] Phase out PrimValue and Relax expression wrappers (#19891)
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 120812e9ac [REFACTOR][Relax] Phase out PrimValue and Relax expression wrappers (#19891)
120812e9ac is described below
commit 120812e9ac1a644fdf8186392dfd9e19adad11e3
Author: Tianqi Chen <tq...@users.noreply.github.com>
AuthorDate: Fri Jun 26 07:18:04 2026 -0400
[REFACTOR][Relax] Phase out PrimValue and Relax expression wrappers (#19891)
This PR lets Relax expressions directly take `PrimExpr` values without
requiring the explicit `PrimValue` wrapper, continuing the Relax IR
unification work by removing Relax-specific leaf/base expression layers.
Summary:
- Remove `LeafExpr` / `LeafExprNode` and use direct expression-node
checks where needed.
- Converge Relax expression typing onto the shared IR `Expr` base.
- Remove the `PrimValue` node wrapper while keeping `relax.prim_value` /
`R.prim_value` as conversion helpers that return existing `PrimExpr`
values unchanged.
- Register direct `PrimExpr` handling through exact concrete node
dispatch, aligned with the `tirx` expression visitor list and excluding
arith iter-map intermediate nodes.
- Inline the private Python primitive conversion helper into public
`relax.prim_value`.
- Handle direct `PrimExpr` values in frontend scalar paths without
assuming a `.value` field on non-immediate expressions.
---
docs/how_to/tutorials/cross_compilation_and_rpc.py | 4 +-
docs/how_to/tutorials/optimize_llm.py | 2 +-
docs/reference/api/python/ir.rst | 1 +
docs/reference/api/python/relax/op.rst | 10 ++
include/tvm/ir/base_expr.h | 18 ++--
include/tvm/ir/expr.h | 57 +++--------
include/tvm/ir/function.h | 8 +-
include/tvm/ir/module.h | 2 +-
include/tvm/ir/op.h | 14 +--
include/tvm/relax/attrs/manipulate.h | 6 +-
include/tvm/relax/expr.h | 109 +++++----------------
include/tvm/relax/expr_functor.h | 51 ++++++++--
include/tvm/relax/type.h | 4 +-
include/tvm/tirx/expr.h | 6 +-
python/tvm/backend/cuda/op.py | 7 +-
python/tvm/ir/__init__.py | 2 +-
python/tvm/ir/expr.py | 28 +++---
python/tvm/ir/function.py | 4 +-
python/tvm/ir/module.py | 5 +-
python/tvm/ir/op.py | 4 +-
python/tvm/relax/__init__.py | 2 +-
python/tvm/relax/backend/metal/coreml.py | 5 +-
python/tvm/relax/expr.py | 57 +++++++----
python/tvm/relax/expr_functor.py | 40 ++++----
python/tvm/relax/frontend/nn/extern.py | 6 +-
python/tvm/relax/frontend/nn/llm/kv_cache.py | 48 ++++-----
python/tvm/relax/frontend/nn/modules.py | 4 +-
python/tvm/relax/frontend/nn/op.py | 12 +--
python/tvm/relax/frontend/onnx/onnx_frontend.py | 61 ++++++------
.../tvm/relax/frontend/tflite/tflite_frontend.py | 12 +--
.../frontend/torch/base_fx_graph_translator.py | 26 +++--
.../frontend/torch/exported_program_translator.py | 4 +-
python/tvm/relax/frontend/torch/fx_translator.py | 4 +-
python/tvm/relax/op/base.py | 2 +-
python/tvm/relax/op/builtin/builtin.py | 4 +-
python/tvm/relax/op/create.py | 73 +++++++-------
python/tvm/relax/op/manipulate.py | 34 ++++---
python/tvm/relax/op/memory/memory.py | 8 +-
python/tvm/relax/op/memory/view.py | 9 +-
python/tvm/relax/op/set.py | 12 +--
python/tvm/relax/op/vm/vm.py | 8 +-
python/tvm/relax/relax_to_pyfunc_converter.py | 8 +-
python/tvm/relax/script/builder/ir.py | 18 ++--
python/tvm/relax/script/parser/parser.py | 27 ++++-
python/tvm/relax/testing/ast_printer.py | 3 -
.../fold_batch_norm_to_conv2d_for_inference.py | 2 +-
.../tvm/relax/transform/ipc_allreduce_rewrite.py | 2 +-
.../tvm/relax/transform/lazy_transform_params.py | 6 +-
python/tvm/relax/transform/legalize_ops/binary.py | 10 +-
python/tvm/relax/transform/legalize_ops/common.py | 6 +-
python/tvm/relax/transform/legalize_ops/create.py | 18 ++--
.../tvm/relax/transform/legalize_ops/datatype.py | 4 +-
python/tvm/relax/transform/legalize_ops/index.py | 6 +-
.../tvm/relax/transform/legalize_ops/manipulate.py | 5 +-
.../relax/transform/lower_gpu_ipc_alloc_storage.py | 2 +-
python/tvm/relax/utils.py | 28 +++---
src/arith/canonical_simplify.cc | 12 +--
src/arith/const_fold.h | 4 +-
src/arith/iter_affine_map.cc | 8 +-
src/backend/trn/transform/lower_trainium_layout.cc | 2 +-
src/ir/expr.cc | 7 +-
src/ir/module.cc | 4 +-
src/relax/analysis/type_analysis.cc | 14 +--
src/relax/backend/contrib/tensorrt/codegen.cc | 11 ++-
src/relax/backend/vm/codegen_vm.cc | 15 +--
src/relax/backend/vm/codegen_vm_tir.cc | 10 +-
src/relax/backend/vm/lower_runtime_builtin.cc | 10 +-
src/relax/backend/vm/vm_shape_lower.cc | 59 ++++++-----
src/relax/ir/block_builder.cc | 2 +-
src/relax/ir/dataflow_expr_rewriter.cc | 4 +-
src/relax/ir/expr.cc | 19 ----
src/relax/ir/expr_functor.cc | 21 ++--
src/relax/ir/py_expr_functor.cc | 26 ++---
src/relax/op/memory/view.cc | 8 +-
src/relax/op/op.cc | 58 ++++++-----
src/relax/op/op_common.h | 8 +-
src/relax/op/tensor/create.cc | 56 +++++------
src/relax/op/tensor/create.h | 8 +-
src/relax/op/tensor/index.cc | 37 +++----
src/relax/op/tensor/inspect.cc | 22 ++---
src/relax/op/tensor/manipulate.cc | 40 ++++----
src/relax/op/tensor/manipulate.h | 6 +-
src/relax/op/tensor/set.cc | 37 ++++---
src/relax/op/tensor/set.h | 4 +-
src/relax/op/tensor/unary.cc | 12 +--
src/relax/script/printer/expr.cc | 8 --
src/relax/transform/allocate_workspace.cc | 2 +-
src/relax/transform/call_tir_rewrite.cc | 4 +-
src/relax/transform/compute_prim_value.cc | 19 ++--
src/relax/transform/dataflow_inplace.cc | 2 +-
src/relax/transform/fuse_ops.cc | 10 +-
src/relax/transform/fuse_tir.cc | 8 +-
src/relax/transform/lazy_transform_params.cc | 6 +-
src/relax/transform/lift_transform_params.cc | 2 +-
src/relax/transform/lower_alloc_tensor.cc | 8 +-
src/relax/transform/merge_composite_functions.cc | 2 +-
src/relax/transform/remove_unused_outputs.cc | 3 +-
src/relax/transform/remove_unused_parameters.cc | 2 +-
src/relax/transform/rewrite_cuda_graph.cc | 10 +-
src/relax/transform/static_plan_block_memory.cc | 14 +--
src/relax/utils.cc | 4 +-
src/runtime/extra/contrib/tensorrt/tensorrt_ops.cc | 2 +-
src/runtime/vm/builtin.cc | 8 +-
src/s_tir/transform/inject_virtual_thread.cc | 2 +-
src/tirx/ir/expr.cc | 68 ++++++-------
src/tirx/ir/expr_functor.cc | 4 +-
src/tirx/op/op.cc | 4 +-
src/tirx/transform/flatten_buffer.cc | 2 +-
src/tirx/transform/lower_tirx_cleanup.cc | 2 +-
tests/python/relax/test_analysis_type_analysis.py | 2 +-
tests/python/relax/test_ast_printer.py | 11 +--
tests/python/relax/test_bind_params.py | 2 +-
tests/python/relax/test_blockbuilder_core.py | 4 +-
tests/python/relax/test_codegen_tensorrt.py | 2 +-
tests/python/relax/test_dataflow_pattern.py | 13 ++-
tests/python/relax/test_dataflow_rewriter.py | 4 +-
tests/python/relax/test_expr.py | 48 +++++----
tests/python/relax/test_expr_functor.py | 16 ++-
tests/python/relax/test_frontend_nn_op.py | 2 +-
tests/python/relax/test_op_manipulate.py | 23 +++--
tests/python/relax/test_relax_operators.py | 2 +-
.../python/relax/test_relax_to_pyfunc_converter.py | 4 +-
.../relax/test_transform_adjust_matmul_order.py | 104 +++++++++-----------
.../relax/test_transform_lazy_transform_params.py | 2 +-
tests/python/relax/test_tvmscript_parser.py | 24 +++--
tests/python/relax/test_tvmscript_printer_relax.py | 29 +++++-
tests/python/relax/test_utils.py | 1 -
tests/python/relax/test_vm_build.py | 4 +-
tests/python/relax/test_vm_codegen_only.py | 4 +-
129 files changed, 993 insertions(+), 946 deletions(-)
diff --git a/docs/how_to/tutorials/cross_compilation_and_rpc.py b/docs/how_to/tutorials/cross_compilation_and_rpc.py
index 3a725791a2..cefa023152 100644
--- a/docs/how_to/tutorials/cross_compilation_and_rpc.py
+++ b/docs/how_to/tutorials/cross_compilation_and_rpc.py
@@ -84,7 +84,6 @@ and the Firefly-RK3399 for an OpenCL example.
#
# INFO:root:RPCServer: bind to 0.0.0.0:9090
#
-######################################################################
# Declare and Cross Compile Kernel on Local Machine
# -------------------------------------------------
#
@@ -388,7 +387,6 @@ print(f"{cost:g} secs/op")
# the device's ``site-packages`` directory. It is a pure Python package, so it
# usually does not need cross-compilation.
#
-#########################################################################
# Run OpenCL Kernel Remotely by RPC
# ---------------------------------
# For remote OpenCL devices, the workflow is almost the same as above.
@@ -446,7 +444,7 @@ def run_opencl():
print("OpenCL test passed!")
-#########################################################################
+######################################################################
# Deploy PyTorch Models to Remote Devices with RPC
# ------------------------------------------------
# The above examples demonstrate cross compilation and RPC using low-level
diff --git a/docs/how_to/tutorials/optimize_llm.py b/docs/how_to/tutorials/optimize_llm.py
index 0c20f30e40..941b67dedd 100644
--- a/docs/how_to/tutorials/optimize_llm.py
+++ b/docs/how_to/tutorials/optimize_llm.py
@@ -306,7 +306,7 @@ class LlamaForCausalLM(nn.Module):
rope_scale=1,
rope_theta=self.rope_theta,
rope_scaling={},
- rope_ext_factors=relax.PrimValue(0),
+ rope_ext_factors=tirx.IntImm("int64", 0),
rotary_dim=self.head_dim,
dtype=self.dtype,
target=target,
diff --git a/docs/reference/api/python/ir.rst b/docs/reference/api/python/ir.rst
index 1f0dc0c5e2..1747dee7be 100644
--- a/docs/reference/api/python/ir.rst
+++ b/docs/reference/api/python/ir.rst
@@ -20,4 +20,5 @@ tvm.ir
.. automodule:: tvm.ir
:members:
:imported-members:
+ :exclude-members: Expr
:autosummary:
diff --git a/docs/reference/api/python/relax/op.rst b/docs/reference/api/python/relax/op.rst
index 2f4ebe2a49..f6a115d1fd 100644
--- a/docs/reference/api/python/relax/op.rst
+++ b/docs/reference/api/python/relax/op.rst
@@ -23,60 +23,70 @@ tvm.relax.op
.. automodule:: tvm.relax.op
:members:
:imported-members:
+ :exclude-members: Expr
tvm.relax.op.nn
***************
.. automodule:: tvm.relax.op.nn
:members:
:imported-members:
+ :exclude-members: Expr
tvm.relax.op.builtin
********************
.. automodule:: tvm.relax.op.builtin
:members:
:imported-members:
+ :exclude-members: Expr
tvm.relax.op.ccl
****************
.. automodule:: tvm.relax.op.ccl
:members:
:imported-members:
+ :exclude-members: Expr
tvm.relax.op.distributed
************************
.. automodule:: tvm.relax.op.distributed
:members:
:imported-members:
+ :exclude-members: Expr
tvm.relax.op.grad
*****************
.. automodule:: tvm.relax.op.grad
:members:
:imported-members:
+ :exclude-members: Expr
tvm.relax.op.image
******************
.. automodule:: tvm.relax.op.image
:members:
:imported-members:
+ :exclude-members: Expr
tvm.relax.op.memory
*******************
.. automodule:: tvm.relax.op.memory
:members:
:imported-members:
+ :exclude-members: Expr
tvm.relax.op.vision
*******************
.. automodule:: tvm.relax.op.vision
:members:
:imported-members:
+ :exclude-members: Expr
tvm.relax.op.vm
***************
.. automodule:: tvm.relax.op.vm
:members:
:imported-members:
+ :exclude-members: Expr
tvm.relax.op.op_attrs
*********************
diff --git a/include/tvm/ir/base_expr.h b/include/tvm/ir/base_expr.h
index f1176955c7..678acf4c9b 100644
--- a/include/tvm/ir/base_expr.h
+++ b/include/tvm/ir/base_expr.h
@@ -272,7 +272,7 @@ inline bool operator!=(const PrimType& lhs, const PrimType& rhs) { return !(lhs
* \brief Base type of all the expressions.
* \sa Expr
*/
-class BaseExprNode : public ffi::Object {
+class ExprNode : public ffi::Object {
public:
/*!
* \brief Span that points to the original source code.
@@ -292,26 +292,26 @@ class BaseExprNode : public ffi::Object {
static void RegisterReflection() {
namespace refl = tvm::ffi::reflection;
// span and ty do not participate in structural equal and hash.
- refl::ObjectDef<BaseExprNode>()
- .def_ro("span", &BaseExprNode::span, refl::DefaultValue(Span()),
+ refl::ObjectDef<ExprNode>()
+ .def_ro("span", &ExprNode::span, refl::DefaultValue(Span()),
refl::AttachFieldFlag::SEqHashIgnore())
- .def_ro("ty", &BaseExprNode::ty, refl::DefaultValue(Type()),
+ .def_ro("ty", &ExprNode::ty, refl::DefaultValue(Type()),
refl::AttachFieldFlag::SEqHashIgnore());
}
static constexpr TVMFFISEqHashKind _type_s_eq_hash_kind = kTVMFFISEqHashKindTreeNode;
static constexpr const uint32_t _type_child_slots = 64;
- TVM_FFI_DECLARE_OBJECT_INFO("ir.BaseExpr", BaseExprNode, ffi::Object);
+ TVM_FFI_DECLARE_OBJECT_INFO("ir.Expr", ExprNode, ffi::Object);
};
/*!
- * \brief Managed reference to BaseExprNode.
- * \sa BaseExprNode
+ * \brief Managed reference to ExprNode.
+ * \sa ExprNode
*/
-class BaseExpr : public ffi::ObjectRef {
+class Expr : public ffi::ObjectRef {
public:
- TVM_FFI_DEFINE_OBJECT_REF_METHODS_NULLABLE(BaseExpr, ffi::ObjectRef, BaseExprNode);
+ TVM_FFI_DEFINE_OBJECT_REF_METHODS_NULLABLE(Expr, ffi::ObjectRef, ExprNode);
};
namespace ffi {
diff --git a/include/tvm/ir/expr.h b/include/tvm/ir/expr.h
index 70e1ffeb48..c66ebe725c 100644
--- a/include/tvm/ir/expr.h
+++ b/include/tvm/ir/expr.h
@@ -67,13 +67,13 @@ class VirtualDevice;
*
* \sa PrimExpr
*/
-class PrimExprNode : public BaseExprNode {
+class PrimExprNode : public ExprNode {
public:
/*! \return the primitive type of this expression node. */
PrimType ty() const {
- TVM_FFI_DCHECK(this->BaseExprNode::ty.defined());
- TVM_FFI_DCHECK(this->BaseExprNode::ty->IsInstance<PrimTypeNode>());
- return ffi::GetRef<PrimType>(static_cast<const PrimTypeNode*>(this->BaseExprNode::ty.get()));
+ TVM_FFI_DCHECK(this->ExprNode::ty.defined());
+ TVM_FFI_DCHECK(this->ExprNode::ty->IsInstance<PrimTypeNode>());
+ return ffi::GetRef<PrimType>(static_cast<const PrimTypeNode*>(this->ExprNode::ty.get()));
}
static void RegisterReflection() {
@@ -82,14 +82,14 @@ class PrimExprNode : public BaseExprNode {
}
static constexpr const uint32_t _type_child_slots = 40;
- TVM_FFI_DECLARE_OBJECT_INFO("ir.PrimExpr", PrimExprNode, BaseExprNode);
+ TVM_FFI_DECLARE_OBJECT_INFO("ir.PrimExpr", PrimExprNode, ExprNode);
};
/*!
* \brief Reference to PrimExprNode.
* \sa PrimExprNode
*/
-class PrimExpr : public BaseExpr {
+class PrimExpr : public Expr {
public:
/*!
* \brief construct from integer.
@@ -105,12 +105,12 @@ class PrimExpr : public BaseExpr {
/*! \return the primitive type of this expression. */
PrimType ty() const {
const auto* node = static_cast<const PrimExprNode*>(get());
- TVM_FFI_DCHECK(node->BaseExprNode::ty.defined());
- TVM_FFI_DCHECK(node->BaseExprNode::ty->IsInstance<PrimTypeNode>());
- return ffi::GetRef<PrimType>(static_cast<const PrimTypeNode*>(node->BaseExprNode::ty.get()));
+ TVM_FFI_DCHECK(node->ExprNode::ty.defined());
+ TVM_FFI_DCHECK(node->ExprNode::ty->IsInstance<PrimTypeNode>());
+ return ffi::GetRef<PrimType>(static_cast<const PrimTypeNode*>(node->ExprNode::ty.get()));
}
- TVM_FFI_DEFINE_OBJECT_REF_METHODS_NULLABLE(PrimExpr, BaseExpr, PrimExprNode);
+ TVM_FFI_DEFINE_OBJECT_REF_METHODS_NULLABLE(PrimExpr, Expr, PrimExprNode);
/*!
* \brief construct from string to form a StringImm.
@@ -377,35 +377,6 @@ TVM_DLL PrimExpr operator^(PrimExpr a, PrimExpr b);
*/
TVM_DLL PrimExpr operator~(PrimExpr a);
-/*!
- * \brief Base node of all non-primitive expressions.
- *
- * RelaxExpr supports tensor and functions as first class citizen.
- * The life-cycle of the corresponding
- * objects are implicitly managed by the language.
- *
- * \sa RelaxExpr
- */
-class RelaxExprNode : public BaseExprNode {
- public:
- static void RegisterReflection() {
- namespace refl = tvm::ffi::reflection;
- refl::ObjectDef<RelaxExprNode>();
- }
-
- static constexpr const uint32_t _type_child_slots = 22;
- TVM_FFI_DECLARE_OBJECT_INFO("ir.RelaxExpr", RelaxExprNode, BaseExprNode);
-};
-
-/*!
- * \brief Managed reference to RelaxExprNode.
- * \sa RelaxExprNode
- */
-class RelaxExpr : public BaseExpr {
- public:
- TVM_FFI_DEFINE_OBJECT_REF_METHODS_NULLABLE(RelaxExpr, BaseExpr, RelaxExprNode);
-};
-
class GlobalVar;
/*!
* \brief Global variable that lives in the top-level module.
@@ -415,7 +386,7 @@ class GlobalVar;
*
* \sa GlobalVarNode
*/
-class GlobalVarNode : public RelaxExprNode {
+class GlobalVarNode : public ExprNode {
public:
/*! \brief The name of the variable, this only acts as a hint. */
ffi::String name_hint;
@@ -435,18 +406,18 @@ class GlobalVarNode : public RelaxExprNode {
}
static constexpr TVMFFISEqHashKind _type_s_eq_hash_kind = kTVMFFISEqHashKindFreeVar;
- TVM_FFI_DECLARE_OBJECT_INFO_FINAL("ir.GlobalVar", GlobalVarNode, RelaxExprNode);
+ TVM_FFI_DECLARE_OBJECT_INFO_FINAL("ir.GlobalVar", GlobalVarNode, ExprNode);
};
/*!
* \brief Managed reference to GlobalVarNode.
* \sa GlobalVarNode
*/
-class GlobalVar : public RelaxExpr {
+class GlobalVar : public Expr {
public:
TVM_DLL explicit GlobalVar(ffi::String name_hint, Span span = {});
- TVM_FFI_DEFINE_OBJECT_REF_METHODS_NULLABLE(GlobalVar, RelaxExpr, GlobalVarNode);
+ TVM_FFI_DEFINE_OBJECT_REF_METHODS_NULLABLE(GlobalVar, Expr, GlobalVarNode);
TVM_DEFINE_OBJECT_REF_COW_METHOD(GlobalVarNode);
};
diff --git a/include/tvm/ir/function.h b/include/tvm/ir/function.h
index b0b9d06b59..2f56653bb8 100644
--- a/include/tvm/ir/function.h
+++ b/include/tvm/ir/function.h
@@ -153,7 +153,7 @@ constexpr const char* kNumInputs = "num_inputs";
*
* \sa BaseFunc
*/
-class BaseFuncNode : public RelaxExprNode {
+class BaseFuncNode : public ExprNode {
public:
/*! \brief Additional attributes storing the meta-data */
DictAttrs attrs;
@@ -240,16 +240,16 @@ class BaseFuncNode : public RelaxExprNode {
}
static constexpr const uint32_t _type_child_slots = 2;
- TVM_FFI_DECLARE_OBJECT_INFO("ir.BaseFunc", BaseFuncNode, RelaxExprNode);
+ TVM_FFI_DECLARE_OBJECT_INFO("ir.BaseFunc", BaseFuncNode, ExprNode);
};
/*!
* \brief Managed reference to BaseFuncNode.
* \sa BaseFuncNode
*/
-class BaseFunc : public RelaxExpr {
+class BaseFunc : public Expr {
public:
- TVM_FFI_DEFINE_OBJECT_REF_METHODS_NULLABLE(BaseFunc, RelaxExpr, BaseFuncNode);
+ TVM_FFI_DEFINE_OBJECT_REF_METHODS_NULLABLE(BaseFunc, Expr, BaseFuncNode);
};
} // namespace tvm
diff --git a/include/tvm/ir/module.h b/include/tvm/ir/module.h
index 34a451be08..eac72d33f7 100644
--- a/include/tvm/ir/module.h
+++ b/include/tvm/ir/module.h
@@ -287,7 +287,7 @@ class IRModule : public ffi::ObjectRef {
* \brief As for \p FromExprInContext, but assuming \p expr is bound to 'main' and no
* imports.
*/
- TVM_DLL static IRModule FromExpr(const RelaxExpr& expr,
+ TVM_DLL static IRModule FromExpr(const Expr& expr,
const ffi::Map<GlobalVar, BaseFunc>& global_funcs = {});
/*!
diff --git a/include/tvm/ir/op.h b/include/tvm/ir/op.h
index 573805bbc0..02568266df 100644
--- a/include/tvm/ir/op.h
+++ b/include/tvm/ir/op.h
@@ -91,7 +91,7 @@ class ArgumentInfo : public ffi::ObjectRef {
*
* \sa Op
*/
-class OpNode : public RelaxExprNode {
+class OpNode : public ExprNode {
public:
/*! \brief name of the operator */
ffi::String name;
@@ -136,7 +136,7 @@ class OpNode : public RelaxExprNode {
}
static constexpr TVMFFISEqHashKind _type_s_eq_hash_kind = kTVMFFISEqHashKindUniqueInstance;
- TVM_FFI_DECLARE_OBJECT_INFO_FINAL("ir.Op", OpNode, RelaxExprNode);
+ TVM_FFI_DECLARE_OBJECT_INFO_FINAL("ir.Op", OpNode, ExprNode);
private:
/*! \return the internal attr registry index. */
@@ -160,9 +160,9 @@ class OpNode : public RelaxExprNode {
* \brief Managed reference class to OpNode.
* \sa OpNode
*/
-class Op : public RelaxExpr {
+class Op : public Expr {
public:
- explicit Op(ffi::ObjectPtr<OpNode> n) : RelaxExpr(std::move(n)) {
+ explicit Op(ffi::ObjectPtr<OpNode> n) : Expr(std::move(n)) {
TVM_FFI_CHECK(defined(), ValueError) << "Op expects a defined OpNode";
}
@@ -189,7 +189,7 @@ class Op : public RelaxExpr {
*/
TVM_DLL static const Op& Get(const ffi::String& op_name);
- TVM_FFI_DEFINE_OBJECT_REF_METHODS_NOTNULLABLE(Op, RelaxExpr, OpNode);
+ TVM_FFI_DEFINE_OBJECT_REF_METHODS_NOTNULLABLE(Op, Expr, OpNode);
private:
/*!
@@ -317,7 +317,7 @@ class OpAttrMap : public AttrRegistryMap<Op, ValueType> {
* or if expr is not an Op.
* \return the const reference to the content value.
*/
- inline ValueType get(const RelaxExpr& expr, ValueType def_value) const;
+ inline ValueType get(const Expr& expr, ValueType def_value) const;
using TParent = AttrRegistryMap<Op, ValueType>;
using TParent::count;
@@ -410,7 +410,7 @@ inline OpRegEntry& OpRegEntry::set_attr( // NOLINT(*)
// member functions of OpAttrMap
template <typename ValueType>
-inline ValueType OpAttrMap<ValueType>::get(const RelaxExpr& expr, ValueType def_value) const {
+inline ValueType OpAttrMap<ValueType>::get(const Expr& expr, ValueType def_value) const {
TVM_FFI_ICHECK(expr.defined());
if (const OpNode* op = expr.as<OpNode>()) {
return this->map_.get(ffi::GetRef<Op>(op), def_value);
diff --git a/include/tvm/relax/attrs/manipulate.h b/include/tvm/relax/attrs/manipulate.h
index cb538ea867..f916e8244a 100644
--- a/include/tvm/relax/attrs/manipulate.h
+++ b/include/tvm/relax/attrs/manipulate.h
@@ -61,9 +61,9 @@ struct ExpandDimsAttrs : public AttrsNode {
/*! \brief Attributes used in layout_transform operator */
struct LayoutTransformAttrs : public AttrsNode {
tirx::IndexMap index_map;
- // pad_value is chosen to be of PrimValue type, as it represents constant TIR POD expression. This
- // needs to be revisited in case PrimValue is evolved to represent symbolic expression in future.
- ffi::Optional<PrimValue> pad_value;
+ // pad_value is chosen to be of PrimExpr type, as it represents constant TIR POD expression. This
+ // needs to be revisited in case PrimExpr is evolved to represent symbolic expression in future.
+ ffi::Optional<PrimExpr> pad_value;
/*!
* axis_separators between input axes when generating flattened output axes. For buffers
* representing flat 1-d memory (e.g. any buffer in RAM), this should be an empty array.
diff --git a/include/tvm/relax/expr.h b/include/tvm/relax/expr.h
index 0b75bf27a7..4eeaad3816 100644
--- a/include/tvm/relax/expr.h
+++ b/include/tvm/relax/expr.h
@@ -175,15 +175,15 @@ class Tuple : public Expr {
* into an array of base type. This constructor handles the
* conversion to the base `ffi::Array<relax::Expr>`.
*
- * \tparam RelaxExpr The type of relax expression passed in as an argument.
+ * \tparam ExprType The type of relax expression passed in as an argument.
*
* \param fields The fields of a tuple.
*
* \param span The source span of the expression.
*/
- template <typename RelaxExpr, typename = std::enable_if_t<std::is_base_of_v<Expr, RelaxExpr>>>
- TVM_DLL explicit Tuple(tvm::ffi::Array<RelaxExpr> fields, Span span = Span())
- : Tuple(fields.Map([](const RelaxExpr& expr) -> Expr { return expr; }), span) {}
+ template <typename ExprType, typename = std::enable_if_t<std::is_base_of_v<Expr, ExprType>>>
+ TVM_DLL explicit Tuple(tvm::ffi::Array<ExprType> fields, Span span = Span())
+ : Tuple(fields.Map([](const ExprType& expr) -> Expr { return expr; }), span) {}
TVM_FFI_DEFINE_OBJECT_REF_METHODS_NULLABLE(Tuple, Expr, TupleNode);
TVM_DEFINE_OBJECT_REF_COW_METHOD(TupleNode);
@@ -239,28 +239,9 @@ TupleGetItem WithFields(TupleGetItem tuple_get_item,
ffi::Optional<int64_t> opt_index = ffi::Optional<int64_t>(),
ffi::Optional<Span> opt_span = ffi::Optional<Span>());
-/*!
- * \brief Base type of all (non-function) leaf Exprs.
- * \sa Expr
- */
-class LeafExprNode : public ExprNode {
- public:
- static constexpr const uint32_t _type_child_slots = 7;
- TVM_FFI_DECLARE_OBJECT_INFO("relax.expr.LeafExpr", LeafExprNode, ExprNode);
-};
-
-/*!
- * \brief Managed reference to BaseExprNode.
- * \sa LeafExprNode
- */
-class LeafExpr : public Expr {
- public:
- TVM_FFI_DEFINE_OBJECT_REF_METHODS_NULLABLE(LeafExpr, Expr, LeafExprNode);
-};
-
/*! \brief A shape expression which allows users to construct a shape containing PrimExpr.
*/
-class ShapeExprNode : public LeafExprNode {
+class ShapeExprNode : public ExprNode {
public:
/*! The values of the shape expression. */
ffi::Array<PrimExpr> values;
@@ -269,18 +250,18 @@ class ShapeExprNode : public LeafExprNode {
namespace refl = tvm::ffi::reflection;
refl::ObjectDef<ShapeExprNode>().def_ro("values", &ShapeExprNode::values);
}
- TVM_FFI_DECLARE_OBJECT_INFO_FINAL("relax.expr.ShapeExpr", ShapeExprNode, LeafExprNode);
+ TVM_FFI_DECLARE_OBJECT_INFO_FINAL("relax.expr.ShapeExpr", ShapeExprNode, ExprNode);
};
-class ShapeExpr : public LeafExpr {
+class ShapeExpr : public Expr {
public:
TVM_DLL explicit ShapeExpr(ffi::Array<PrimExpr> values, Span span = Span());
- TVM_FFI_DEFINE_OBJECT_REF_METHODS_NULLABLE(ShapeExpr, LeafExpr, ShapeExprNode);
+ TVM_FFI_DEFINE_OBJECT_REF_METHODS_NULLABLE(ShapeExpr, Expr, ShapeExprNode);
TVM_DEFINE_OBJECT_REF_COW_METHOD(ShapeExprNode);
};
/*! \brief The variable class for all Relax bindings. */
-class VarNode : public LeafExprNode {
+class VarNode : public ExprNode {
public:
/*! \brief The identifier of the variable, which is used for comparing stable equality across
* transformations. */
@@ -312,16 +293,16 @@ class VarNode : public LeafExprNode {
static constexpr TVMFFISEqHashKind _type_s_eq_hash_kind = kTVMFFISEqHashKindDAGNode;
static constexpr const uint32_t _type_child_slots = 1;
- TVM_FFI_DECLARE_OBJECT_INFO("relax.expr.Var", VarNode, LeafExprNode);
+ TVM_FFI_DECLARE_OBJECT_INFO("relax.expr.Var", VarNode, ExprNode);
};
-class Var : public LeafExpr {
+class Var : public Expr {
public:
TVM_DLL explicit Var(ffi::String name_hint, ffi::Optional<Type> ty_annotation, Span span = Span())
: Var(Id(name_hint), ty_annotation, span) {}
TVM_DLL explicit Var(Id vid, ffi::Optional<Type> ty_annotation, Span span = Span());
- TVM_FFI_DEFINE_OBJECT_REF_METHODS_NULLABLE(Var, LeafExpr, VarNode);
+ TVM_FFI_DEFINE_OBJECT_REF_METHODS_NULLABLE(Var, Expr, VarNode);
VarNode* CopyOnWrite();
};
@@ -357,7 +338,7 @@ class DataflowVar : public Var {
*
* \note Scalar constants are represented by ndim-0 constant tensors.
*/
-class ConstantNode : public LeafExprNode {
+class ConstantNode : public ExprNode {
public:
/*! \brief The data of the tensor */
runtime::Tensor data;
@@ -372,10 +353,10 @@ class ConstantNode : public LeafExprNode {
namespace refl = tvm::ffi::reflection;
refl::ObjectDef<ConstantNode>().def_ro("data", &ConstantNode::data);
}
- TVM_FFI_DECLARE_OBJECT_INFO_FINAL("relax.expr.Constant", ConstantNode, LeafExprNode);
+ TVM_FFI_DECLARE_OBJECT_INFO_FINAL("relax.expr.Constant", ConstantNode, ExprNode);
};
-class Constant : public LeafExpr {
+class Constant : public Expr {
public:
/*!
* \brief The constructor
@@ -387,56 +368,14 @@ class Constant : public LeafExpr {
TVM_DLL explicit Constant(runtime::Tensor data, ffi::Optional<Type> ty_annotation = std::nullopt,
Span span = Span());
- TVM_FFI_DEFINE_OBJECT_REF_METHODS_NULLABLE(Constant, LeafExpr, ConstantNode);
+ TVM_FFI_DEFINE_OBJECT_REF_METHODS_NULLABLE(Constant, Expr, ConstantNode);
TVM_DEFINE_OBJECT_REF_COW_METHOD(ConstantNode);
};
-/*!
- * \brief PrimValue.
- *
- * Expression representing a TIR POD expression.
- */
-class PrimValueNode : public LeafExprNode {
- public:
- /*! \brief The prim expr representing the value */
- PrimExpr value;
-
- static void RegisterReflection() {
- namespace refl = tvm::ffi::reflection;
- refl::ObjectDef<PrimValueNode>().def_ro("value", &PrimValueNode::value);
- }
- TVM_FFI_DECLARE_OBJECT_INFO_FINAL("relax.expr.PrimValue", PrimValueNode, LeafExprNode);
-};
-
-/*!
- * \brief Managed reference to PrimValueNode
- * \sa PrimValeNode
- */
-class PrimValue : public LeafExpr {
- public:
- /*!
- * \brief The constructor
- * \param value The value input.
- * \param span The source span of the expression.
- */
- TVM_DLL explicit PrimValue(PrimExpr value, Span span = Span());
-
- /*!
- * \brief Create a int64 prim value.
- * \param value The input value.
- * \param span The source span of the expression.
- * \return The created prim value.
- */
- TVM_DLL static PrimValue Int64(int64_t value, Span span = Span());
-
- TVM_FFI_DEFINE_OBJECT_REF_METHODS_NULLABLE(PrimValue, LeafExpr, PrimValueNode);
- TVM_DEFINE_OBJECT_REF_COW_METHOD(PrimValueNode);
-};
-
/*!
* \brief Represent a string literal constant.
*/
-class StringImmNode : public LeafExprNode {
+class StringImmNode : public ExprNode {
public:
/*! \brief The data value. */
ffi::String value;
@@ -445,14 +384,14 @@ class StringImmNode : public LeafExprNode {
namespace refl = tvm::ffi::reflection;
refl::ObjectDef<StringImmNode>().def_ro("value", &StringImmNode::value);
}
- TVM_FFI_DECLARE_OBJECT_INFO_FINAL("relax.expr.StringImm", StringImmNode, LeafExprNode);
+ TVM_FFI_DECLARE_OBJECT_INFO_FINAL("relax.expr.StringImm", StringImmNode, ExprNode);
};
/*!
* \brief Managed reference to StringImm
* \sa StringImmNode
*/
-class StringImm : public LeafExpr {
+class StringImm : public Expr {
public:
/*!
* \brief The constructor
@@ -461,14 +400,14 @@ class StringImm : public LeafExpr {
*/
TVM_DLL explicit StringImm(ffi::String value, Span span = Span());
- TVM_FFI_DEFINE_OBJECT_REF_METHODS_NULLABLE(StringImm, LeafExpr, StringImmNode);
+ TVM_FFI_DEFINE_OBJECT_REF_METHODS_NULLABLE(StringImm, Expr, StringImmNode);
TVM_DEFINE_OBJECT_REF_COW_METHOD(StringImmNode);
};
/*!
* \brief Represent a data type constant.
*/
-class DataTypeImmNode : public LeafExprNode {
+class DataTypeImmNode : public ExprNode {
public:
/*! \brief The data value. */
DLDataType value;
@@ -477,14 +416,14 @@ class DataTypeImmNode : public LeafExprNode {
namespace refl = tvm::ffi::reflection;
refl::ObjectDef<DataTypeImmNode>().def_ro("value", &DataTypeImmNode::value);
}
- TVM_FFI_DECLARE_OBJECT_INFO_FINAL("relax.expr.DataTypeImm", DataTypeImmNode, LeafExprNode);
+ TVM_FFI_DECLARE_OBJECT_INFO_FINAL("relax.expr.DataTypeImm", DataTypeImmNode, ExprNode);
};
/*!
* \brief Managed reference to DataTypeImm
* \sa DataTypeImmNode
*/
-class DataTypeImm : public LeafExpr {
+class DataTypeImm : public Expr {
public:
/*!
* \brief The constructor
@@ -493,7 +432,7 @@ class DataTypeImm : public LeafExpr {
*/
TVM_DLL explicit DataTypeImm(DLDataType value, Span span = Span());
- TVM_FFI_DEFINE_OBJECT_REF_METHODS_NULLABLE(DataTypeImm, LeafExpr, DataTypeImmNode);
+ TVM_FFI_DEFINE_OBJECT_REF_METHODS_NULLABLE(DataTypeImm, Expr, DataTypeImmNode);
TVM_DEFINE_OBJECT_REF_COW_METHOD(DataTypeImmNode);
};
diff --git a/include/tvm/relax/expr_functor.h b/include/tvm/relax/expr_functor.h
index eb00f3bbdd..92885e344b 100644
--- a/include/tvm/relax/expr_functor.h
+++ b/include/tvm/relax/expr_functor.h
@@ -62,6 +62,41 @@ class ExprFunctor;
return self->VisitExpr_(static_cast<const OP*>(n.get()), std::forward<Args>(args)...); \
});
+#define RELAX_PRIM_EXPR_NODE_DISPATCH_LIST(V) \
+ V(::tvm::IntImmNode) \
+ V(::tvm::FloatImmNode) \
+ V(::tvm::tirx::VarNode) \
+ V(::tvm::tirx::SizeVarNode) \
+ V(::tvm::tirx::StringImmNode) \
+ V(::tvm::tirx::CastNode) \
+ V(::tvm::tirx::AddNode) \
+ V(::tvm::tirx::SubNode) \
+ V(::tvm::tirx::MulNode) \
+ V(::tvm::tirx::DivNode) \
+ V(::tvm::tirx::ModNode) \
+ V(::tvm::tirx::FloorDivNode) \
+ V(::tvm::tirx::FloorModNode) \
+ V(::tvm::tirx::MinNode) \
+ V(::tvm::tirx::MaxNode) \
+ V(::tvm::tirx::EQNode) \
+ V(::tvm::tirx::NENode) \
+ V(::tvm::tirx::LTNode) \
+ V(::tvm::tirx::LENode) \
+ V(::tvm::tirx::GTNode) \
+ V(::tvm::tirx::GENode) \
+ V(::tvm::tirx::AndNode) \
+ V(::tvm::tirx::OrNode) \
+ V(::tvm::tirx::NotNode) \
+ V(::tvm::tirx::SelectNode) \
+ V(::tvm::tirx::BufferLoadNode) \
+ V(::tvm::tirx::ProducerLoadNode) \
+ V(::tvm::tirx::RampNode) \
+ V(::tvm::tirx::BroadcastNode) \
+ V(::tvm::tirx::LetNode) \
+ V(::tvm::tirx::CallNode) \
+ V(::tvm::tirx::ShuffleNode) \
+ V(::tvm::tirx::ReduceNode)
+
#define PY_EXPR_VISITOR_DEFAULT(N, PY_FUNC, DEFAULT_FUNC) \
{ \
if (PY_FUNC != nullptr) \
@@ -88,6 +123,8 @@ class ExprFunctor;
self->VisitExpr_(static_cast<const OP*>(n.get())); \
});
+#define PY_EXPR_VISITOR_DISPATCH_PRIM_EXPR(OP) PY_EXPR_VISITOR_DISPATCH(OP, f_visit_prim_expr_)
+
#define PY_EXPR_MUTATOR_DISPATCH(OP, PY_FUNC) \
vtable.template set_dispatch<OP>([](const ffi::ObjectRef& n, TSelf* self) { \
if (self->PY_FUNC != nullptr) { \
@@ -98,6 +135,8 @@ class ExprFunctor;
} \
});
+#define PY_EXPR_MUTATOR_DISPATCH_PRIM_EXPR(OP) PY_EXPR_MUTATOR_DISPATCH(OP, f_visit_prim_expr_)
+
#define PY_EXPR_MUTATOR_VISIT_EXPR_POST_ORDER_DISPATCH(OP) \
post_order_vtable.template set_dispatch<OP>([](const ffi::ObjectRef& n, TSelf* self) { \
return self->VisitExprPostOrder_(static_cast<const OP*>(n.get())); \
@@ -150,7 +189,7 @@ class ExprFunctor<R(const Expr& n, Args...)> {
virtual R VisitExpr_(const IfNode* op, Args... args) EXPR_FUNCTOR_DEFAULT;
virtual R VisitExpr_(const OpNode* op, Args... args) EXPR_FUNCTOR_DEFAULT;
virtual R VisitExpr_(const TupleGetItemNode* op, Args... args) EXPR_FUNCTOR_DEFAULT;
- virtual R VisitExpr_(const PrimValueNode* op, Args... args) EXPR_FUNCTOR_DEFAULT;
+ virtual R VisitExpr_(const PrimExprNode* op, Args... args) EXPR_FUNCTOR_DEFAULT;
virtual R VisitExpr_(const StringImmNode* op, Args... args) EXPR_FUNCTOR_DEFAULT;
virtual R VisitExpr_(const DataTypeImmNode* op, Args... args) EXPR_FUNCTOR_DEFAULT;
virtual R VisitExprDefault_(const ffi::Object* op, Args...) {
@@ -176,7 +215,7 @@ class ExprFunctor<R(const Expr& n, Args...)> {
RELAX_EXPR_FUNCTOR_DISPATCH(IfNode);
RELAX_EXPR_FUNCTOR_DISPATCH(OpNode);
RELAX_EXPR_FUNCTOR_DISPATCH(TupleGetItemNode);
- RELAX_EXPR_FUNCTOR_DISPATCH(PrimValueNode);
+ RELAX_PRIM_EXPR_NODE_DISPATCH_LIST(RELAX_EXPR_FUNCTOR_DISPATCH);
RELAX_EXPR_FUNCTOR_DISPATCH(StringImmNode);
RELAX_EXPR_FUNCTOR_DISPATCH(DataTypeImmNode);
vtable.Finalize();
@@ -209,7 +248,7 @@ class ExprVisitor : public ExprFunctor<void(const Expr&)> {
void VisitExpr_(const IfNode* op) override;
void VisitExpr_(const OpNode* op) override;
void VisitExpr_(const TupleGetItemNode* op) override;
- void VisitExpr_(const PrimValueNode* op) override;
+ void VisitExpr_(const PrimExprNode* op) override;
void VisitExpr_(const StringImmNode* op) override;
void VisitExpr_(const DataTypeImmNode* op) override;
@@ -236,7 +275,7 @@ class ExprVisitor : public ExprFunctor<void(const Expr&)> {
virtual void VisitBinding_(const VarBindingNode* binding, const IfNode* val);
virtual void VisitBinding_(const VarBindingNode* binding, const OpNode* val);
virtual void VisitBinding_(const VarBindingNode* binding, const TupleGetItemNode* val);
- virtual void VisitBinding_(const VarBindingNode* binding, const PrimValueNode* val);
+ virtual void VisitBinding_(const VarBindingNode* binding, const PrimExprNode* val);
virtual void VisitBinding_(const VarBindingNode* binding, const StringImmNode* val);
virtual void VisitBinding_(const VarBindingNode* binding, const DataTypeImmNode* val);
/*!
@@ -336,7 +375,7 @@ class ExprMutatorBase : public ExprFunctor<Expr(const Expr&)> {
Expr VisitExpr_(const IfNode* op) override;
Expr VisitExpr_(const OpNode* op) override;
Expr VisitExpr_(const TupleGetItemNode* op) override;
- Expr VisitExpr_(const PrimValueNode* op) override;
+ Expr VisitExpr_(const PrimExprNode* op) override;
Expr VisitExpr_(const StringImmNode* op) override;
Expr VisitExpr_(const DataTypeImmNode* op) override;
@@ -455,7 +494,7 @@ class ExprMutator : public ExprMutatorBase {
virtual void VisitBinding_(const VarBindingNode* binding, const IfNode* val);
virtual void VisitBinding_(const VarBindingNode* binding, const OpNode* val);
virtual void VisitBinding_(const VarBindingNode* binding, const TupleGetItemNode* val);
- virtual void VisitBinding_(const VarBindingNode* binding, const PrimValueNode* val);
+ virtual void VisitBinding_(const VarBindingNode* binding, const PrimExprNode* val);
virtual void VisitBinding_(const VarBindingNode* binding, const StringImmNode* val);
virtual void VisitBinding_(const VarBindingNode* binding, const DataTypeImmNode* val);
/*!
diff --git a/include/tvm/relax/type.h b/include/tvm/relax/type.h
index c5f21e404b..0423264182 100644
--- a/include/tvm/relax/type.h
+++ b/include/tvm/relax/type.h
@@ -38,8 +38,8 @@
namespace tvm {
namespace relax {
-using Expr = RelaxExpr;
-using ExprNode = RelaxExprNode;
+using Expr = tvm::Expr;
+using ExprNode = tvm::ExprNode;
class BlockBuilder;
class Call;
diff --git a/include/tvm/tirx/expr.h b/include/tvm/tirx/expr.h
index bf4c9004e8..86704c4d2b 100644
--- a/include/tvm/tirx/expr.h
+++ b/include/tvm/tirx/expr.h
@@ -728,7 +728,7 @@ class CallNode : public PrimExprNode {
* - It can be tvm::Op which corresponds to the primitive operators(intrinsics).
* - It can also be another function in the IRModule (GlobalVar).
*/
- RelaxExpr op;
+ tvm::Expr op;
/*! \brief The arguments. */
ffi::Array<PrimExpr> args;
@@ -752,9 +752,9 @@ class CallNode : public PrimExprNode {
*/
class Call : public PrimExpr {
public:
- TVM_DLL Call(PrimType ret_ty, RelaxExpr op, ffi::Array<PrimExpr> args, Attrs attrs = Attrs(),
+ TVM_DLL Call(PrimType ret_ty, tvm::Expr op, ffi::Array<PrimExpr> args, Attrs attrs = Attrs(),
Span span = Span());
- TVM_DLL Call(PrimType ret_ty, RelaxExpr op, ffi::Array<PrimExpr> args, Span span);
+ TVM_DLL Call(PrimType ret_ty, tvm::Expr op, ffi::Array<PrimExpr> args, Span span);
TVM_FFI_DEFINE_OBJECT_REF_METHODS_NULLABLE(Call, PrimExpr, CallNode);
TVM_DEFINE_OBJECT_REF_COW_METHOD(CallNode);
};
diff --git a/python/tvm/backend/cuda/op.py b/python/tvm/backend/cuda/op.py
index c1e9fdcef1..5755644d64 100644
--- a/python/tvm/backend/cuda/op.py
+++ b/python/tvm/backend/cuda/op.py
@@ -965,9 +965,10 @@ def ptx_cp_async_bulk_tensor_global_to_cluster(
cta_group : int
Must be either 1 or 2.
- If set to 1, mbarrier must be in the shared memory of the same CTA as the shared memory destination
- If set to 2, mbarrier can be in shared memory of either the same CTA as the shared memory destination
- or the shared memory of the peer CTA.
+ If set to 1, mbarrier must be in the shared memory of the same CTA
+ as the shared memory destination. If set to 2, mbarrier can be in
+ shared memory of either the same CTA as the shared memory destination
+ or the shared memory of the peer CTA.
cache_hint : str
The cache hint.
diff --git a/python/tvm/ir/__init__.py b/python/tvm/ir/__init__.py
index 8bdafc5899..2984df5ea0 100644
--- a/python/tvm/ir/__init__.py
+++ b/python/tvm/ir/__init__.py
@@ -30,7 +30,7 @@ from .base import (
load_json,
save_json,
)
-from .expr import BaseExpr, GlobalVar, PrimExpr, Range, RelaxExpr
+from .expr import Expr, GlobalVar, PrimExpr, Range
from .function import BaseFunc, CallingConv
from .global_info import GlobalInfo, DummyGlobalInfo, VDevice
from .module import IRModule
diff --git a/python/tvm/ir/expr.py b/python/tvm/ir/expr.py
index 3de8f3755d..9ff58a5c90 100644
--- a/python/tvm/ir/expr.py
+++ b/python/tvm/ir/expr.py
@@ -27,8 +27,8 @@ from . import _ffi_api
from .base import Node, Span
-@tvm_ffi.register_object("ir.BaseExpr")
-class BaseExpr(Node):
+@tvm_ffi.register_object("ir.Expr")
+class Expr(Node):
"""Base class of all the expressions."""
span: Span | None
@@ -36,7 +36,7 @@ class BaseExpr(Node):
@tvm_ffi.register_object("ir.PrimExpr")
-class PrimExpr(BaseExpr):
+class PrimExpr(Expr):
"""Base class of all primitive expressions.
PrimExpr is used in the low-level code
@@ -44,13 +44,8 @@ class PrimExpr(BaseExpr):
"""
-@tvm_ffi.register_object("ir.RelaxExpr")
-class RelaxExpr(BaseExpr):
- """Base class of all non-primitive expressions."""
-
-
@tvm_ffi.register_object("ir.GlobalVar")
-class GlobalVar(RelaxExpr):
+class GlobalVar(Expr):
"""A global variable in the IR.
GlobalVar is used to refer to the global functions
@@ -67,30 +62,29 @@ class GlobalVar(RelaxExpr):
def __init__(self, name_hint: str):
self.__init_handle_by_constructor__(_ffi_api.GlobalVar, name_hint)
- def __call__(self, *args: RelaxExpr) -> BaseExpr:
+ def __call__(self, *args: Expr) -> Expr:
"""Call the global variable.
Parameters
----------
- args: List[RelaxExpr]
+ args: List[Expr]
The arguments to the call.
Returns
-------
- call: BaseExpr
+ call: Expr
A call taking the variable as a function.
"""
# pylint: disable=import-outside-toplevel
- # TODO(@relax-team): replace with Relax base class after it's introduced
- if all(isinstance(x, RelaxExpr) for x in args):
+ if args and all(isinstance(x, Number | PrimExpr) for x in args):
+ return tvm.tirx.call_tir(self, *args)
+
+ if all(isinstance(x, Expr) for x in args):
from tvm import relax
return relax.Call(self, args)
- elif all(isinstance(x, Number | PrimExpr) for x in args):
- return tvm.tirx.call_tir(self, *args)
-
arg_types = [type(x) for x in args]
raise RuntimeError(f"Do not know how to handle GlobalVar.__call__ for types {arg_types}")
diff --git a/python/tvm/ir/function.py b/python/tvm/ir/function.py
index c5f4a262bd..76699dcab3 100644
--- a/python/tvm/ir/function.py
+++ b/python/tvm/ir/function.py
@@ -26,7 +26,7 @@ from tvm.runtime import Object
from . import _ffi_api
from .attrs import DictAttrs
-from .expr import RelaxExpr
+from .expr import Expr
class CallingConv(IntEnum):
@@ -38,7 +38,7 @@ class CallingConv(IntEnum):
@tvm_ffi.register_object("ir.BaseFunc")
-class BaseFunc(RelaxExpr):
+class BaseFunc(Expr):
"""Base class of all functions."""
@property
diff --git a/python/tvm/ir/module.py b/python/tvm/ir/module.py
index a883158d35..1ce93e3700 100644
--- a/python/tvm/ir/module.py
+++ b/python/tvm/ir/module.py
@@ -25,6 +25,7 @@ from . import _ffi_api
from . import expr as _expr
from .attrs import DictAttrs
from .base import Node
+from .function import BaseFunc
@tvm_ffi.register_object("ir.IRModule")
@@ -94,7 +95,7 @@ class IRModule(Node, Scriptable):
return self._add(var, val, True)
def _add(self, var, val, update=True):
- if isinstance(val, _expr.RelaxExpr):
+ if isinstance(val, BaseFunc):
if isinstance(var, str):
if _ffi_api.Module_ContainGlobalVar(self, var):
var = _ffi_api.Module_GetGlobalVar(self, var)
@@ -201,7 +202,7 @@ class IRModule(Node, Scriptable):
Parameters
----------
- expr: RelaxExpr
+ expr: Expr
The starting expression
global_funcs: Optional[dict]
diff --git a/python/tvm/ir/op.py b/python/tvm/ir/op.py
index 6c0912f864..02034fdf99 100644
--- a/python/tvm/ir/op.py
+++ b/python/tvm/ir/op.py
@@ -20,11 +20,11 @@
import tvm_ffi
from . import _ffi_api
-from .expr import RelaxExpr
+from .expr import Expr
@tvm_ffi.register_object("ir.Op")
-class Op(RelaxExpr):
+class Op(Expr):
"""Primitive operator in the IR."""
def __init__(self):
diff --git a/python/tvm/relax/__init__.py b/python/tvm/relax/__init__.py
index 5a752c87c1..dd2e293f16 100644
--- a/python/tvm/relax/__init__.py
+++ b/python/tvm/relax/__init__.py
@@ -43,9 +43,9 @@ from .expr import (
Call,
If,
Constant,
- PrimValue,
DataTypeImm,
StringImm,
+ prim_value,
)
from .expr import const, extern, get_shape_of
diff --git a/python/tvm/relax/backend/metal/coreml.py b/python/tvm/relax/backend/metal/coreml.py
index 0152e965b9..a248b5bc9a 100644
--- a/python/tvm/relax/backend/metal/coreml.py
+++ b/python/tvm/relax/backend/metal/coreml.py
@@ -32,7 +32,6 @@ from tvm.relax.expr import (
Call,
Constant,
Function,
- PrimValue,
SeqExpr,
Var,
VarBinding,
@@ -283,7 +282,7 @@ _convert_map = {
@visitor
class CallNodeInfoCollector(PyExprVisitor):
"""
- Collect PrimValue, Constant and attributes in the inner function
+ Collect PrimExpr, Constant and attributes in the inner function
"""
def __init__(self, op_name):
@@ -295,7 +294,7 @@ class CallNodeInfoCollector(PyExprVisitor):
def visit_call_(self, call: Call) -> None:
self.attrs.append(call.attrs)
for arg in call.args:
- if isinstance(arg, PrimValue):
+ if isinstance(arg, tvm.tirx.PrimExpr):
self.primvals.append(arg)
if isinstance(arg, Constant):
self.consts.append(arg)
diff --git a/python/tvm/relax/expr.py b/python/tvm/relax/expr.py
index 75b2319f32..e6edf4901d 100644
--- a/python/tvm/relax/expr.py
+++ b/python/tvm/relax/expr.py
@@ -19,7 +19,7 @@
import typing
from collections.abc import Callable, Mapping
-from numbers import Number
+from numbers import Integral, Number, Real
from typing import Any, Optional, Union
import numpy as _np # type: ignore
@@ -40,11 +40,42 @@ from . import _ffi_api
# It is a workaround for mypy: https://github.com/python/mypy/issues/7866#issuecomment-549454370
# This feature is not supported until python 3.10:
# https://docs.python.org/3.10/whatsnew/3.10.html#pep-613-typealias
-Expr = tvm.ir.RelaxExpr
+Expr = tvm.ir.Expr
Type = tvm.ir.Type # pylint: disable=invalid-name
GlobalVar = tvm.ir.GlobalVar
+def prim_value(value: PrimExpr | int | float, dtype: str | None = None) -> PrimExpr:
+ """Convert a Python scalar or primitive expression to ``PrimExpr``.
+
+ Parameters
+ ----------
+ value : PrimExpr | int | float
+ The value to convert.
+
+ dtype : Optional[str]
+ The dtype to use when converting Python numeric values.
+
+ Returns
+ -------
+ result : PrimExpr
+ The converted primitive expression. Existing ``PrimExpr`` inputs are
+ returned unchanged.
+ """
+ if isinstance(value, PrimExpr):
+ return value
+ if isinstance(value, bool | _np.bool_):
+ return tvm.tirx.IntImm(dtype or "bool", int(value))
+ if isinstance(value, Integral):
+ return tvm.tirx.IntImm(dtype or "int64", int(value))
+ if isinstance(value, Real):
+ return tvm.tirx.FloatImm(dtype or "float64", float(value))
+ tvm_value = tvm_ffi.convert(value)
+ if isinstance(tvm_value, PrimExpr):
+ return tvm_value
+ raise TypeError(f"Cannot convert {value} with type {type(value)} to `PrimExpr`")
+
+
@tvm_ffi.register_object("relax.Id")
class Id(Object):
"""Unique identifier(name) used in Var.
@@ -290,7 +321,7 @@ class _DLTensorDTypeProxy(tvm.runtime.ObjectConvertible):
will produce `relax.Call` expressions, representing the field's
runtime value. If the datatype of the tensor is known at
compile-time, the `relax.Call` will be normalized into a
- `relax.PrimValue`, with no runtime cost.
+ `PrimExpr`, with no runtime cost.
Parameters
----------
@@ -369,7 +400,7 @@ class _DLTensorShapeProxy(tvm.runtime.ObjectConvertible):
these fields will produce `relax.Call` expressions, representing
the field's runtime value. If the datatype of the tensor is known
at compile-time, the `relax.Call` will be normalized into a
- `relax.PrimValue`, with no runtime cost.
+ `PrimExpr`, with no runtime cost.
Parameters
----------
@@ -417,7 +448,7 @@ class _DLTensorShapeProxy(tvm.runtime.ObjectConvertible):
"""
if not isinstance(axis, tvm.relax.Expr):
- axis = tvm.relax.PrimValue(axis)
+ axis = tvm.tirx.IntImm("int64", axis)
if axis.ty is not None and not isinstance(axis.ty, tvm.ir.PrimType):
raise TypeError(
@@ -437,7 +468,7 @@ class _DLTensorStrideProxy(tvm.runtime.ObjectConvertible):
these fields will produce `relax.Call` expressions, representing
the field's runtime value. If the datatype of the tensor is known
at compile-time, the `relax.Call` will be normalized into a
- `relax.PrimValue`, with no runtime cost.
+ `PrimExpr`, with no runtime cost.
Parameters
----------
@@ -485,7 +516,7 @@ class _DLTensorStrideProxy(tvm.runtime.ObjectConvertible):
"""
if not isinstance(axis, tvm.relax.Expr):
- axis = tvm.relax.PrimValue(axis)
+ axis = tvm.tirx.IntImm("int64", axis)
if axis.ty is not None and not isinstance(axis.ty, tvm.ir.PrimType):
raise TypeError(
@@ -822,18 +853,6 @@ class DataflowVar(Var):
)
-@tvm_ffi.register_object("relax.expr.PrimValue")
-class PrimValue(Expr, Scriptable):
- """The prim expr representing the value."""
-
- value: PrimExpr
-
- def __init__(self, value: PrimExpr | int, span: Span | None = None) -> None:
- if isinstance(value, int):
- value = tvm.tirx.IntImm("int64", value)
- self.__init_handle_by_constructor__(_ffi_api.PrimValue, value, span) # type: ignore
-
-
@tvm_ffi.register_object("relax.expr.StringImm")
class StringImm(Expr, Scriptable):
"""Represent a string literal constant."""
diff --git a/python/tvm/relax/expr_functor.py b/python/tvm/relax/expr_functor.py
index e84e37b02a..026a285aae 100644
--- a/python/tvm/relax/expr_functor.py
+++ b/python/tvm/relax/expr_functor.py
@@ -44,7 +44,7 @@ from .expr import (
Id,
If,
MatchCast,
- PrimValue,
+ PrimExpr,
SeqExpr,
ShapeExpr,
Span,
@@ -162,8 +162,8 @@ class ExprFunctor:
ret = self.visit_op_(expr)
elif isinstance(expr, TupleGetItem):
ret = self.visit_tuple_getitem_(expr)
- elif isinstance(expr, PrimValue):
- ret = self.visit_prim_value_(expr)
+ elif isinstance(expr, PrimExpr):
+ ret = self.visit_prim_expr_(expr)
elif isinstance(expr, StringImm):
ret = self.visit_string_imm_(expr)
elif isinstance(expr, DataTypeImm):
@@ -212,7 +212,7 @@ class ExprFunctor:
def visit_tuple_getitem_(self, op: TupleGetItem):
raise NotImplementedError()
- def visit_prim_value_(self, op: PrimValue):
+ def visit_prim_expr_(self, op: PrimExpr):
raise NotImplementedError()
def visit_string_imm_(self, op: StringImm):
@@ -291,7 +291,7 @@ class _PyExprVisitor(tvm_ffi.core.Object):
f_visit_if_: Callable | None = None,
f_visit_op_: Callable | None = None,
f_visit_tuple_getitem_: Callable | None = None,
- f_visit_prim_value_: Callable | None = None,
+ f_visit_prim_expr_: Callable | None = None,
f_visit_string_imm_: Callable | None = None,
f_visit_data_type_imm_: Callable | None = None,
f_visit_binding: Callable | None = None,
@@ -323,7 +323,7 @@ class _PyExprVisitor(tvm_ffi.core.Object):
f_visit_if_,
f_visit_op_,
f_visit_tuple_getitem_,
- f_visit_prim_value_,
+ f_visit_prim_expr_,
f_visit_string_imm_,
f_visit_data_type_imm_,
f_visit_binding,
@@ -418,7 +418,7 @@ class PyExprVisitor:
"visit_if_",
"visit_op_",
"visit_tuple_getitem_",
- "visit_prim_value_",
+ "visit_prim_expr_",
"visit_string_imm_",
"visit_data_type_imm_",
"visit_binding",
@@ -654,15 +654,15 @@ class PyExprVisitor:
# Using self._outer() to ref _PyExprVisitor
return _ffi_api.ExprVisitorVisitExpr(self._outer(), op) # type: ignore
- def visit_prim_value_(self, op: PrimValue) -> None:
- """Visit PrimValue.
- Users can customized this function to overwrite VisitExpr_(const PrimValueNode* op)
+ def visit_prim_expr_(self, op: PrimExpr) -> None:
+ """Visit PrimExpr.
+ Users can customized this function to overwrite VisitExpr_(const PrimExprNode* op)
on the C++ side.
Parameters
----------
- op : PrimValue
- The PrimValue to be visited.
+ op : PrimExpr
+ The PrimExpr to be visited.
"""
# Using self._outer() to ref _PyExprVisitor
return _ffi_api.ExprVisitorVisitExpr(self._outer(), op) # type: ignore
@@ -812,7 +812,7 @@ class _PyExprMutator(Object):
f_visit_if_: Callable | None = None,
f_visit_op_: Callable | None = None,
f_visit_tuple_getitem_: Callable | None = None,
- f_visit_prim_value_: Callable | None = None,
+ f_visit_prim_expr_: Callable | None = None,
f_visit_string_imm_: Callable | None = None,
f_visit_data_type_imm_: Callable | None = None,
f_visit_binding: Callable | None = None,
@@ -845,7 +845,7 @@ class _PyExprMutator(Object):
f_visit_if_,
f_visit_op_,
f_visit_tuple_getitem_,
- f_visit_prim_value_,
+ f_visit_prim_expr_,
f_visit_string_imm_,
f_visit_data_type_imm_,
f_visit_binding,
@@ -956,7 +956,7 @@ class PyExprMutator:
"visit_if_",
"visit_op_",
"visit_tuple_getitem_",
- "visit_prim_value_",
+ "visit_prim_expr_",
"visit_string_imm_",
"visit_data_type_imm_",
"visit_binding",
@@ -1276,15 +1276,15 @@ class PyExprMutator:
# Using self._outer() to ref _PyExprMutator
return _ffi_api.ExprMutatorVisitExpr(self._outer(), op) # type: ignore
- def visit_prim_value_(self, op: PrimValue) -> Expr:
- """Visit PrimValue.
- Users can customized this function to overwrite VisitExpr_(const PrimValueNode* op)
+ def visit_prim_expr_(self, op: PrimExpr) -> Expr:
+ """Visit PrimExpr.
+ Users can customized this function to overwrite VisitExpr_(const PrimExprNode* op)
on the C++ side.
Parameters
----------
- op : PrimValue
- The PrimValue to be visited.
+ op : PrimExpr
+ The PrimExpr to be visited.
Returns
-------
diff --git a/python/tvm/relax/frontend/nn/extern.py b/python/tvm/relax/frontend/nn/extern.py
index 6c7f3dc72c..8756e2acbb 100644
--- a/python/tvm/relax/frontend/nn/extern.py
+++ b/python/tvm/relax/frontend/nn/extern.py
@@ -55,13 +55,13 @@ class ExternModule:
if isinstance(arg, core.Tensor):
return arg._expr # pylint: disable=protected-access
if isinstance(arg, int):
- return rx.PrimValue(tirx.IntImm("int64", arg))
+ return rx.prim_value(tirx.IntImm("int64", arg))
if isinstance(arg, float):
- return rx.PrimValue(tirx.FloatImm("float64", arg))
+ return rx.prim_value(tirx.FloatImm("float64", arg))
if isinstance(arg, str):
return rx.StringImm(arg)
if isinstance(arg, tirx.PrimExpr):
- return rx.PrimValue(arg)
+ return rx.prim_value(arg)
if isinstance(arg, tuple | list):
return rx.Tuple([_convert(e, f"{name}_{i}") for i, e in enumerate(arg)])
raise TypeError(f"Unsupported input type: {type(arg)}")
diff --git a/python/tvm/relax/frontend/nn/llm/kv_cache.py b/python/tvm/relax/frontend/nn/llm/kv_cache.py
index 6536fdceac..bbfb9f0b64 100644
--- a/python/tvm/relax/frontend/nn/llm/kv_cache.py
+++ b/python/tvm/relax/frontend/nn/llm/kv_cache.py
@@ -149,8 +149,8 @@ class PagedKVCache(Object): # pylint: disable=too-few-public-methods
"vm.builtin.attention_kv_cache_attention_with_fused_qkv",
[
self._expr,
- rx.PrimValue(layer_id), # type: ignore[arg-type]
- rx.PrimValue(sm_scale),
+ rx.prim_value(layer_id), # type: ignore[arg-type]
+ rx.prim_value(sm_scale),
qkv._expr,
],
out_ty=rx.TensorType((b * s, num_qo_heads, d), qkv.dtype),
@@ -179,8 +179,8 @@ class PagedKVCache(Object): # pylint: disable=too-few-public-methods
"vm.builtin.attention_kv_cache_self_attention",
[
self._expr,
- rx.PrimValue(layer_id), # type: ignore[arg-type]
- rx.PrimValue(sm_scale),
+ rx.prim_value(layer_id), # type: ignore[arg-type]
+ rx.prim_value(sm_scale),
q._expr,
k._expr,
v._expr,
@@ -214,8 +214,8 @@ class PagedKVCache(Object): # pylint: disable=too-few-public-methods
"vm.builtin.attention_kv_cache_cross_attention",
[
self._expr,
- rx.PrimValue(layer_id), # type: ignore[arg-type]
- rx.PrimValue(sm_scale),
+ rx.prim_value(layer_id), # type: ignore[arg-type]
+ rx.prim_value(sm_scale),
q._expr,
],
out_ty=[
@@ -239,7 +239,7 @@ class PagedKVCache(Object): # pylint: disable=too-few-public-methods
_expr=rx.call_pure_packed(
"vm.builtin.attention_kv_cache_append_mla_kv",
self._expr,
- rx.PrimValue(layer_id), # type: ignore[arg-type]
+ rx.prim_value(layer_id), # type: ignore[arg-type]
kv._expr,
ty_args=rx.AnyType(),
),
@@ -455,7 +455,7 @@ class FlashInferPagedKVCache(PagedKVCache): # pylint: disable=too-few-public-me
if attn_kind_single == "mha"
else [rx.Tuple([]) for _ in range(6)]
)
- ragged_prefill_function = rx.Tuple([rx.StringImm("flashinfer"), rx.ExternFunc("batch_prefill_ragged_run"), rx.ExternFunc("batch_prefill_plan")]) if attn_kind_single == "mha" else rx.Tuple([rx.StringImm("flashinfer"), rx.ExternFunc("batch_prefill_ragged_run"), rx.ExternFunc("batch_prefill_plan"), rx.PrimValue(mla_original_qk_head_dim), rx.PrimValue(mla_original_v_head_dim)])
+ ragged_prefill_function = rx.Tuple([rx.StringImm("flashinfer"), rx.ExternFunc("batch_prefill_ragged_run"), rx.ExternFunc("batch_prefill_plan")]) if attn_kind_single == "mha" else rx.Tuple([rx.StringImm("flashinfer"), rx.ExternFunc("batch_prefill_ragged_run"), rx.ExternFunc("batch_prefill_plan"), rx.prim_value(mla_original_qk_head_dim), rx.prim_value(mla_original_v_head_dim)])
mla_function = rx.Tuple([rx.StringImm("flashinfer"), rx.ExternFunc("batch_mla_run"), rx.ExternFunc("batch_mla_plan")] if attn_kind_single == "mla" else [])
attn_merge_functions = [
bb.add_func(_merge_state_inplace(num_attention_heads, v_head_dim, dtype, target, "tir_attention_merge_state"), "tir_attention_merge_state"),
@@ -479,15 +479,15 @@ class FlashInferPagedKVCache(PagedKVCache): # pylint: disable=too-few-public-me
]
),
layer_partition,
- rx.PrimValue(num_attention_heads),
- rx.PrimValue(num_key_value_heads),
- rx.PrimValue(qk_head_dim),
- rx.PrimValue(v_head_dim),
+ rx.prim_value(num_attention_heads),
+ rx.prim_value(num_key_value_heads),
+ rx.prim_value(qk_head_dim),
+ rx.prim_value(v_head_dim),
rx.ShapeExpr(attn_kind),
- rx.PrimValue(enable_disaggregation),
- rx.PrimValue(rope_mode),
- rx.PrimValue(rope_scale),
- rx.PrimValue(rope_theta),
+ rx.prim_value(enable_disaggregation),
+ rx.prim_value(rope_mode),
+ rx.prim_value(rope_scale),
+ rx.prim_value(rope_theta),
rope_ext_factors,
rx.op.zeros((), dtype),
bb.add_func(_kv_cache_transpose_append(num_key_value_heads, qk_head_dim, dtype), "kv_cache_transpose_append"),
@@ -607,15 +607,15 @@ class TIRPagedKVCache(PagedKVCache): # pylint: disable=too-few-public-methods
]
),
layer_partition,
- rx.PrimValue(num_attention_heads),
- rx.PrimValue(num_key_value_heads),
- rx.PrimValue(qk_head_dim),
- rx.PrimValue(v_head_dim),
+ rx.prim_value(num_attention_heads),
+ rx.prim_value(num_key_value_heads),
+ rx.prim_value(qk_head_dim),
+ rx.prim_value(v_head_dim),
rx.ShapeExpr(attn_kind),
- rx.PrimValue(enable_disaggregation),
- rx.PrimValue(rope_mode),
- rx.PrimValue(rope_scale),
- rx.PrimValue(rope_theta),
+ rx.prim_value(enable_disaggregation),
+ rx.prim_value(rope_mode),
+ rx.prim_value(rope_scale),
+ rx.prim_value(rope_theta),
rope_ext_factors,
rx.op.zeros((), dtype),
bb.add_func(_kv_cache_transpose_append(num_key_value_heads, qk_head_dim, dtype), "kv_cache_transpose_append"),
diff --git a/python/tvm/relax/frontend/nn/modules.py b/python/tvm/relax/frontend/nn/modules.py
index 77a1457ea9..1204cdf20e 100644
--- a/python/tvm/relax/frontend/nn/modules.py
+++ b/python/tvm/relax/frontend/nn/modules.py
@@ -811,8 +811,8 @@ class KVCache(Effect):
"vm.builtin.attention_kv_cache_create",
rx.op.zeros(init_shape, self.dtype),
init_shape,
- rx.PrimValue(0),
- ty_args=rx.AnyType(),
+ rx.prim_value(0),
+ ty_args=rx.ObjectType(),
),
name_hint=name_hint,
)
diff --git a/python/tvm/relax/frontend/nn/op.py b/python/tvm/relax/frontend/nn/op.py
index 3fbac41117..bf14d3c3db 100644
--- a/python/tvm/relax/frontend/nn/op.py
+++ b/python/tvm/relax/frontend/nn/op.py
@@ -2197,13 +2197,13 @@ def extern(
if isinstance(arg, Tensor):
return arg._expr # pylint: disable=protected-access
if isinstance(arg, int):
- return rx.PrimValue(_tir.IntImm("int64", arg))
+ return rx.prim_value(_tir.IntImm("int64", arg))
if isinstance(arg, float):
- return rx.PrimValue(_tir.FloatImm("float64", arg))
+ return rx.prim_value(_tir.FloatImm("float64", arg))
if isinstance(arg, str):
return rx.StringImm(arg)
if isinstance(arg, _tir.PrimExpr):
- return rx.PrimValue(arg)
+ return rx.prim_value(arg)
if isinstance(arg, tuple | list):
return rx.Tuple([_convert(e, f"{name}_{i}") for i, e in enumerate(arg)])
raise TypeError(f"Unsupported input type: {type(arg)}")
@@ -2263,11 +2263,11 @@ def debug_func(
if isinstance(arg, Tensor):
converted_args.append(arg._expr) # pylint: disable=protected-access
elif isinstance(arg, int):
- converted_args.append(rx.PrimValue(_tir.IntImm("int64", arg)))
+ converted_args.append(rx.prim_value(_tir.IntImm("int64", arg)))
elif isinstance(arg, float):
- converted_args.append(rx.PrimValue(_tir.FloatImm("float32", arg)))
+ converted_args.append(rx.prim_value(_tir.FloatImm("float32", arg)))
elif isinstance(arg, _tir.PrimExpr):
- converted_args.append(rx.PrimValue(arg))
+ converted_args.append(rx.prim_value(arg))
elif isinstance(arg, str):
converted_args.append(rx.StringImm(arg))
else:
diff --git a/python/tvm/relax/frontend/onnx/onnx_frontend.py b/python/tvm/relax/frontend/onnx/onnx_frontend.py
index 02e0f125b0..87675a3f9c 100644
--- a/python/tvm/relax/frontend/onnx/onnx_frontend.py
+++ b/python/tvm/relax/frontend/onnx/onnx_frontend.py
@@ -265,7 +265,7 @@ def get_prim_expr_list(
Parameters
----------
- inputs : Union[relax.Constant, relax.ShapeExpr, relax.PrimValue]
+ inputs : Union[relax.Constant, relax.ShapeExpr, tvm.tirx.PrimExpr]
The input value to try to convert to a list of PrimExpr.
Returns
@@ -280,8 +280,8 @@ def get_prim_expr_list(
return np_value.tolist()
elif isinstance(inputs, relax.ShapeExpr):
return inputs.values
- elif isinstance(inputs, relax.PrimValue):
- return [inputs.value.value]
+ elif isinstance(inputs, tvm.tirx.PrimExpr):
+ return [inputs]
else:
raise ValueError(f"Cannot cast {type(inputs)} to list of PrimExpr")
@@ -441,11 +441,10 @@ class MatMulInteger16(OnnxOpConverter):
def _to_numpy(x):
- if isinstance(x, relax.PrimValue):
- x = x.value
+ if isinstance(x, tvm.tirx.PrimExpr):
if isinstance(x, tirx.IntImm | tirx.FloatImm):
- x = x.value
- return _np.array(x)
+ return _np.array(x.value)
+ return x
else:
return x.data.numpy()
@@ -475,18 +474,19 @@ class BinaryBase(OnnxOpConverter):
if cls.numpy_op is None or cls.relax_op is None:
raise ValueError("Numpy and Relax operators must be defined for BinaryBase.")
if all([not isinstance(inp, relax.expr.Call | relax.Var) for inp in inputs]):
+ has_prim_expr = any([isinstance(inp, tvm.tirx.PrimExpr) for inp in inputs])
x = _to_numpy(inputs[0])
y = _to_numpy(inputs[1])
output = cls.numpy_op(x, y) # pylint: disable=not-callable
- if isinstance(x, relax.PrimValue) and isinstance(y, relax.PrimValue):
- return relax.PrimValue(output.item())
+ if has_prim_expr:
+ if hasattr(output, "item"):
+ output = output.item()
+ return relax.prim_value(output)
if x.dtype == y.dtype:
# no numpy precision widening
output = output.astype(x.dtype)
if all([isinstance(inp, relax.Constant) for inp in inputs]):
return relax.const(output, output.dtype) # pylint: disable=not-callable
- if any([isinstance(inp, relax.PrimValue) for inp in inputs]):
- return relax.PrimValue(output.item()) # pylint: disable=not-callable
return cls.relax_op(inputs[0], inputs[1]) # pylint: disable=not-callable
@@ -906,8 +906,8 @@ class Hardmax(OnnxOpConverter):
normalized_axis, axis_extent = _get_axis_extent(data, axis, "Hardmax")
dtype = data.ty.dtype
argmax = relax.op.argmax(data, axis=normalized_axis)
- on_value = relax.PrimValue(tvm.tirx.const(1.0, dtype))
- off_value = relax.PrimValue(tvm.tirx.const(0.0, dtype))
+ on_value = relax.prim_value(tvm.tirx.const(1.0, dtype))
+ off_value = relax.prim_value(tvm.tirx.const(0.0, dtype))
return relax.op.one_hot(argmax, on_value, off_value, axis_extent, normalized_axis)
@classmethod
@@ -987,12 +987,12 @@ class Unsqueeze(OnnxOpConverter):
axes = get_constant(inputs[1], params)
data_ndim = _get_known_tensor_rank(data)
- if isinstance(data, relax.PrimValue) and isinstance(axes, relax.Constant):
+ if isinstance(data, tvm.tirx.PrimExpr) and isinstance(axes, relax.Constant):
constant_axes = _normalize_constant_axes(
list(map(int, axes.data.numpy().tolist())), 1, "Unsqueeze"
)
if constant_axes == [0]:
- return relax.ShapeExpr([data.value])
+ return relax.ShapeExpr([data])
raise NotImplementedError("Unsqueeze with symbolic scalar inputs only supports axis 0.")
if isinstance(data, relax.Constant) and isinstance(axes, relax.Constant):
constant_axes = _normalize_constant_axes(
@@ -1106,8 +1106,10 @@ class Cast(OnnxOpConverter):
if isinstance(inputs[0], relax.Constant):
output = inputs[0].data.numpy().astype(to_type)
return relax.const(output, to_type)
- if isinstance(inputs[0], relax.PrimValue):
- return relax.PrimValue(inputs[0].value.astype(to_type))
+ if isinstance(inputs[0], tvm.tirx.PrimExpr):
+ if isinstance(inputs[0], tirx.IntImm | tirx.FloatImm):
+ return tvm.tirx.const(inputs[0].value, to_type)
+ return inputs[0].astype(to_type)
try:
np_dst = _np.dtype(str(to_type))
@@ -1193,7 +1195,7 @@ class Gather(OnnxOpConverter):
np_index = np_index[0]
np_index = int(np_index)
shape_val = data[np_index]
- return relax.PrimValue(shape_val)
+ return relax.prim_value(shape_val)
indices_dtype = indices.ty.dtype.dtype
if not indices_dtype.startswith("uint"):
@@ -1957,11 +1959,11 @@ class Squeeze(OnnxOpConverter):
shape_tensor_ndim = 1
if axis is None:
if len(data) == 1:
- return relax.PrimValue(data[0])
+ return relax.prim_value(data[0])
return data
normalized_axes = _normalize_constant_axes(list(axis), shape_tensor_ndim, "Squeeze")
if normalized_axes == [0] and len(data) == 1:
- return relax.PrimValue(data[0])
+ return relax.prim_value(data[0])
raise NotImplementedError(
"Squeeze on symbolic shape tensors only supports removing the sole axis."
)
@@ -2141,8 +2143,8 @@ class Neg(OnnxOpConverter):
if isinstance(inputs[0], relax.Constant):
data_np = inputs[0].data.numpy()
return relax.const(_np.negative(data_np), inputs[0].ty.dtype)
- if isinstance(inputs[0], relax.PrimValue):
- return relax.PrimValue(-inputs[0].value)
+ if isinstance(inputs[0], tvm.tirx.PrimExpr):
+ return -inputs[0]
return relax.op.negative(inputs[0])
@@ -2378,7 +2380,7 @@ def get_prim_value_list(values):
new_values = []
for v in list(values):
if isinstance(v, relax.expr.PrimExpr):
- new_values.append(relax.PrimValue(v))
+ new_values.append(relax.prim_value(v))
else:
new_values.append(v)
return new_values
@@ -2391,7 +2393,7 @@ def _get_known_tensor_rank(expr: relax.Expr) -> int | None:
return len(expr.data.numpy().shape)
if isinstance(expr, relax.ShapeExpr):
return 1
- if isinstance(expr, relax.PrimValue):
+ if isinstance(expr, tvm.tirx.PrimExpr):
return 0
ty = expr.ty
if isinstance(ty, relax.TensorType):
@@ -2411,7 +2413,7 @@ def _get_known_tensor_length(expr: relax.Expr | None) -> int | None:
return int(np_value.shape[0])
if isinstance(expr, relax.ShapeExpr):
return len(expr.values)
- if isinstance(expr, relax.PrimValue):
+ if isinstance(expr, tvm.tirx.PrimExpr):
return 1
ty = expr.ty
if not isinstance(ty, relax.TensorType):
@@ -2450,7 +2452,7 @@ def _as_int64_tensor(bb: relax.BlockBuilder, expr: relax.Expr) -> relax.Expr:
if isinstance(expr, relax.ShapeExpr):
return bb.normalize(relax.op.shape_to_tensor(expr))
- if isinstance(expr, relax.PrimValue):
+ if isinstance(expr, tvm.tirx.PrimExpr):
return bb.normalize(relax.op.full((1,), expr, dtype="int64"))
if isinstance(expr, relax.Constant):
if expr.ty.dtype == "int64":
@@ -2556,7 +2558,7 @@ class Slice(OnnxOpConverter):
axes = get_constant(inputs[3], params)
steps = get_constant(inputs[4], params)
all_constant_params = all(
- isinstance(param, relax.Constant | relax.ShapeExpr | relax.PrimValue) or param is None
+ isinstance(param, relax.Constant | relax.ShapeExpr | tvm.tirx.PrimExpr) or param is None
for param in [starts, ends, axes, steps]
)
if all_constant_params:
@@ -4451,7 +4453,10 @@ class OneHot(OnnxOpConverter):
assert isinstance(values, relax.Constant), "Only constant values currently supported."
values = values.data.numpy().tolist()
off_value, on_value = values
- off_value, on_value = relax.PrimValue(off_value), relax.PrimValue(on_value)
+ off_value, on_value = (
+ relax.prim_value(off_value),
+ relax.prim_value(on_value),
+ )
return relax.op.one_hot(indices, on_value, off_value, depth, axis)
diff --git a/python/tvm/relax/frontend/tflite/tflite_frontend.py b/python/tvm/relax/frontend/tflite/tflite_frontend.py
index e2ab3a7b27..893aac882a 100644
--- a/python/tvm/relax/frontend/tflite/tflite_frontend.py
+++ b/python/tvm/relax/frontend/tflite/tflite_frontend.py
@@ -3135,7 +3135,7 @@ class OperatorConverter:
StableHLO clamp(min, operand, max) → R.minimum(R.maximum(operand, min), max).
"""
- # NOTE: R.clip is not used here because it only accepts scalar PrimValue
+ # NOTE: R.clip is not used here because it only accepts scalar PrimExpr
# min/max, not tensor inputs.
input_tensors = self.get_input_tensors(op)
assert len(input_tensors) == 3, "input tensors length should be 3"
@@ -7838,16 +7838,16 @@ class OperatorConverter:
one_hot_options.Init(op_options.Bytes, op_options.Pos)
axis = one_hot_options.Axis()
- # Extract scalar values for on_value and off_value and wrap as PrimValue
+ # Extract scalar values for on_value and off_value as PrimExpr
dtype = self.get_tensor_type_str(on_value.tensor.Type())
on_val = self.get_tensor_value(on_value).item()
off_val = self.get_tensor_value(off_value).item()
if "float" in dtype:
- on_prim = relax.PrimValue(tvm.tirx.FloatImm(dtype, float(on_val)))
- off_prim = relax.PrimValue(tvm.tirx.FloatImm(dtype, float(off_val)))
+ on_prim = relax.prim_value(tvm.tirx.FloatImm(dtype, float(on_val)))
+ off_prim = relax.prim_value(tvm.tirx.FloatImm(dtype, float(off_val)))
else:
- on_prim = relax.PrimValue(tvm.tirx.IntImm(dtype, int(on_val)))
- off_prim = relax.PrimValue(tvm.tirx.IntImm(dtype, int(off_val)))
+ on_prim = relax.prim_value(tvm.tirx.IntImm(dtype, int(on_val)))
+ off_prim = relax.prim_value(tvm.tirx.IntImm(dtype, int(off_val)))
out = relax.op.one_hot(indices_expr, on_prim, off_prim, depth, axis)
diff --git a/python/tvm/relax/frontend/torch/base_fx_graph_translator.py b/python/tvm/relax/frontend/torch/base_fx_graph_translator.py
index 8570080926..4eca18f23d 100644
--- a/python/tvm/relax/frontend/torch/base_fx_graph_translator.py
+++ b/python/tvm/relax/frontend/torch/base_fx_graph_translator.py
@@ -1990,7 +1990,10 @@ class BaseFXGraphImporter(metaclass=abc.ABCMeta):
# Replace None with arange for full dimension indexing
arange_idx = self.block_builder.emit(
relax.op.arange(
- relax.PrimValue(0), data_shape[i], relax.PrimValue(1), "int64"
+ relax.prim_value(0),
+ data_shape[i],
+ relax.prim_value(1),
+ "int64",
)
)
# Reshape to [dim_size, 1, 1, ...] for broadcasting
@@ -2080,7 +2083,12 @@ class BaseFXGraphImporter(metaclass=abc.ABCMeta):
for i, idx in enumerate(indices):
if idx is None:
arange_idx = self.block_builder.emit(
- relax.op.arange(relax.PrimValue(0), data_shape[i], relax.PrimValue(1), "int64")
+ relax.op.arange(
+ relax.prim_value(0),
+ data_shape[i],
+ relax.prim_value(1),
+ "int64",
+ )
)
# Reshape to [dim_size, 1, 1, ...] for broadcasting
arange_idx = self.block_builder.emit(
@@ -2142,19 +2150,19 @@ class BaseFXGraphImporter(metaclass=abc.ABCMeta):
return input_shape[axis]
return val
- if isinstance(bound, relax.PrimValue):
- value = _adjust(bound.value)
- return relax.PrimValue(value)
+ if isinstance(bound, tirx.PrimExpr):
+ value = _adjust(bound)
+ return relax.prim_value(value)
bound = _adjust(bound)
- if not isinstance(bound, relax.PrimValue):
- bound = relax.PrimValue(bound)
+ if not isinstance(bound, tirx.PrimExpr):
+ bound = relax.prim_value(bound)
return bound
start = _normalize_bound(start)
end = _normalize_bound(end)
- if not isinstance(step, relax.PrimValue):
- step = relax.PrimValue(step)
+ if not isinstance(step, tirx.PrimExpr):
+ step = relax.prim_value(step)
return self.block_builder.emit(
relax.op.slice_scatter(input_tensor, src, start, end, step, axis=dim)
diff --git a/python/tvm/relax/frontend/torch/exported_program_translator.py b/python/tvm/relax/frontend/torch/exported_program_translator.py
index 337e4c14e8..0ff4410941 100644
--- a/python/tvm/relax/frontend/torch/exported_program_translator.py
+++ b/python/tvm/relax/frontend/torch/exported_program_translator.py
@@ -1011,8 +1011,8 @@ class ExportedProgramImporter(BaseFXGraphImporter):
off_value = node.args[3] if len(node.args) > 3 else node.kwargs.get("off_value", 0)
axis = node.args[4] if len(node.args) > 4 else node.kwargs.get("axis", -1)
- on_value = relax.PrimValue(on_value)
- off_value = relax.PrimValue(off_value)
+ on_value = relax.prim_value(on_value)
+ off_value = relax.prim_value(off_value)
return self.block_builder.emit(relax.op.one_hot(x, on_value, off_value, num_classes, axis))
diff --git a/python/tvm/relax/frontend/torch/fx_translator.py b/python/tvm/relax/frontend/torch/fx_translator.py
index e1e0facc78..6f40f51f28 100644
--- a/python/tvm/relax/frontend/torch/fx_translator.py
+++ b/python/tvm/relax/frontend/torch/fx_translator.py
@@ -727,8 +727,8 @@ class TorchFXImporter(BaseFXGraphImporter):
on_value = node.args[2] if len(node.args) > 2 else node.kwargs.get("on_value", 1)
off_value = node.args[3] if len(node.args) > 3 else node.kwargs.get("off_value", 0)
axis = node.args[4] if len(node.args) > 4 else node.kwargs.get("axis", -1)
- on_value = relax.PrimValue(on_value)
- off_value = relax.PrimValue(off_value)
+ on_value = relax.prim_value(on_value)
+ off_value = relax.prim_value(off_value)
return self.block_builder.emit(relax.op.one_hot(x, on_value, off_value, num_classes, axis))
def _tensor(self, node: fx.Node) -> relax.Var:
diff --git a/python/tvm/relax/op/base.py b/python/tvm/relax/op/base.py
index 4534c3efc4..fc337a6f95 100644
--- a/python/tvm/relax/op/base.py
+++ b/python/tvm/relax/op/base.py
@@ -601,7 +601,7 @@ def assert_op(
A Call to the Relax assert operation.
"""
if not isinstance(condition, Expr):
- condition = tvm.relax.PrimValue(condition)
+ condition = tvm.relax.prim_value(condition)
if format_args is None:
format_args = []
diff --git a/python/tvm/relax/op/builtin/builtin.py b/python/tvm/relax/op/builtin/builtin.py
index 328d63f3cc..411b76ca28 100644
--- a/python/tvm/relax/op/builtin/builtin.py
+++ b/python/tvm/relax/op/builtin/builtin.py
@@ -15,7 +15,7 @@
# specific language governing permissions and limitations
"""The builtin Relax operators."""
-from ...expr import Call, DataTypeImm, Expr, PrimValue, StringImm
+from ...expr import Call, DataTypeImm, Expr, StringImm, prim_value
from ...utils import convert_to_expr
from . import _ffi_api
@@ -53,7 +53,7 @@ def alloc_tensor(
if isinstance(dtype, str):
dtype = DataTypeImm(dtype)
if isinstance(runtime_device_index, int):
- runtime_device_index = PrimValue(runtime_device_index)
+ runtime_device_index = prim_value(runtime_device_index)
if isinstance(storage_scope, str):
storage_scope = StringImm(storage_scope)
if not isinstance(storage_scope, StringImm):
diff --git a/python/tvm/relax/op/create.py b/python/tvm/relax/op/create.py
index 3130d44336..506ec21711 100644
--- a/python/tvm/relax/op/create.py
+++ b/python/tvm/relax/op/create.py
@@ -20,7 +20,7 @@ from tvm import DataType, DataTypeCode
from tvm.ir import PrimType
from tvm.ir.expr import PrimExpr
-from ..expr import Expr, PrimValue, ShapeExpr
+from ..expr import Expr, ShapeExpr, prim_value
from . import _ffi_api
PrimExprLike = int | PrimExpr
@@ -30,6 +30,14 @@ def _raw_dtype(dtype):
return dtype.dtype if isinstance(dtype, PrimType) else dtype
+def _normalize_shape(shape):
+ if isinstance(shape, tuple | list):
+ return ShapeExpr(shape)
+ if isinstance(shape, PrimExpr):
+ raise TypeError("shape must be a tuple/list or a Relax shape expression")
+ return shape
+
+
def full(
shape: tuple[PrimExprLike] | Expr,
fill_value: Expr,
@@ -54,6 +62,7 @@ def full(
result : relax.Expr
The result tensor.
"""
+ shape = _normalize_shape(shape)
return _ffi_api.full(shape, fill_value, _raw_dtype(dtype)) # type: ignore
@@ -99,8 +108,7 @@ def ones(shape: tuple[PrimExprLike] | Expr, dtype: str | DataType) -> Expr:
result : relax.Expr
The result tensor.
"""
- if isinstance(shape, tuple | list):
- shape = ShapeExpr(shape)
+ shape = _normalize_shape(shape)
return _ffi_api.ones(shape, _raw_dtype(dtype)) # type: ignore
@@ -141,8 +149,7 @@ def zeros(shape: tuple[PrimExprLike] | Expr, dtype: str | DataType) -> Expr:
result : relax.Expr
The result tensor.
"""
- if isinstance(shape, tuple | list):
- shape = ShapeExpr(shape)
+ shape = _normalize_shape(shape)
return _ffi_api.zeros(shape, _raw_dtype(dtype)) # type: ignore
@@ -168,22 +175,22 @@ def zeros_like(x: Expr, dtype: str | DataType | None = None) -> Expr:
def eye(
- n: PrimExprLike | PrimValue,
- m: PrimExprLike | PrimValue | None = None,
- k: PrimExprLike | PrimValue = 0,
+ n: PrimExprLike,
+ m: PrimExprLike | None = None,
+ k: PrimExprLike = 0,
dtype: str | DataType = "float32",
) -> Expr:
"""Construct a 2-D tensor with ones on the diagonal and zeros elsewhere.
Parameters
----------
- n : PrimExprLike | PrimValue
+ n : PrimExprLike
Number of rows in the output.
- m : Optional[PrimExprLike | PrimValue]
+ m : Optional[PrimExprLike]
Number of columns in the output. If None, defaults to n.
- k : PrimExprLike | PrimValue
+ k : PrimExprLike
Index of the diagonal: 0 (the default) refers to the main diagonal,
a positive value refers to an upper diagonal, and a negative value
to a lower diagonal.
@@ -197,15 +204,15 @@ def eye(
The result tensor.
"""
m = n if m is None else m
- n = n if isinstance(n, PrimValue) else PrimValue(n)
- m = m if isinstance(m, PrimValue) else PrimValue(m)
- k = k if isinstance(k, PrimValue) else PrimValue(k)
+ n = prim_value(n)
+ m = prim_value(m)
+ k = prim_value(k)
return _ffi_api.eye(n, m, k, _raw_dtype(dtype)) # type: ignore
def eye_like(
x: Expr,
- k: PrimExprLike | PrimValue = 0,
+ k: PrimExprLike = 0,
dtype: str | DataType | None = None,
) -> Expr:
"""Return a 2-D tensor with ones on the diagonal and zeros elsewhere,
@@ -217,7 +224,7 @@ def eye_like(
The input tensor, which provides the shape, and dtype
when the `dtype` field is not specified.
- k : PrimExprLike | PrimValue
+ k : PrimExprLike
Index of the diagonal: 0 (the default) refers to the main diagonal,
a positive value refers to an upper diagonal, and a negative value
to a lower diagonal.
@@ -231,28 +238,28 @@ def eye_like(
result : relax.Expr
The result tensor.
"""
- k = k if isinstance(k, PrimValue) else PrimValue(k)
+ k = prim_value(k)
return _ffi_api.eye_like(x, k, _raw_dtype(dtype)) # type: ignore
def arange(
- start: PrimExprLike | PrimValue,
- end: PrimExprLike | PrimValue | None = None,
- step: PrimExprLike | PrimValue = 1,
+ start: PrimExprLike,
+ end: PrimExprLike | None = None,
+ step: PrimExprLike = 1,
dtype: str | DataType | None = None,
) -> Expr:
"""Construct a tensor with evenly spaced elements.
Parameters
----------
- start : PrimExprLike | PrimValue
+ start : PrimExprLike
The start of the interval.
- end : Optional[PrimExprLike | PrimValue]
+ end : Optional[PrimExprLike]
The end of the interval. If not given, it will be set to start,
and start will be set to 0.
- step : PrimExprLike | PrimValue
+ step : PrimExprLike
The step size.
dtype : Optional[str | DataType]
@@ -270,8 +277,6 @@ def arange(
def is_int(expr):
if isinstance(expr, int):
return True
- if isinstance(expr, PrimValue):
- expr = expr.value
if isinstance(expr, PrimExpr):
return expr.ty.matches_code(DataTypeCode.INT)
return False
@@ -281,9 +286,9 @@ def arange(
integer_args = all(is_int(arg) for arg in args)
dtype = "int64" if integer_args else "float32"
- start = start if isinstance(start, PrimValue) else PrimValue(start)
- end = end if isinstance(end, PrimValue) else PrimValue(end)
- step = step if isinstance(step, PrimValue) else PrimValue(step)
+ start = prim_value(start)
+ end = prim_value(end)
+ step = prim_value(step)
return _ffi_api.arange(start, end, step, dtype) # type: ignore
@@ -311,13 +316,13 @@ def hamming_window(window_size, periodic, alpha, beta, dtype):
The result tensor.
"""
if not isinstance(window_size, Expr):
- window_size = PrimValue(window_size)
+ window_size = prim_value(window_size)
if not isinstance(periodic, Expr):
- periodic = PrimValue(periodic)
+ periodic = prim_value(periodic)
if not isinstance(alpha, Expr):
- alpha = PrimValue(alpha)
+ alpha = prim_value(alpha)
if not isinstance(beta, Expr):
- beta = PrimValue(beta)
+ beta = prim_value(beta)
return _ffi_api.hamming_window(window_size, periodic, alpha, beta, dtype)
@@ -343,7 +348,7 @@ def tril(x: Expr, k: int | PrimExpr | Expr = 0) -> Expr:
The result tensor.
"""
if not isinstance(k, Expr):
- k = PrimValue(k)
+ k = prim_value(k)
return _ffi_api.tril(x, k) # type: ignore
@@ -369,6 +374,6 @@ def triu(x: Expr, k: int | PrimExpr | Expr = 0) -> Expr:
The result tensor.
"""
if not isinstance(k, Expr):
- k = PrimValue(k)
+ k = prim_value(k)
return _ffi_api.triu(x, k) # type: ignore
diff --git a/python/tvm/relax/op/manipulate.py b/python/tvm/relax/op/manipulate.py
index 43a2bd4003..b96c2926b0 100644
--- a/python/tvm/relax/op/manipulate.py
+++ b/python/tvm/relax/op/manipulate.py
@@ -22,7 +22,7 @@ from tvm.ir.expr import PrimExpr
from tvm.runtime import DataTypeCode
from tvm.tirx import FloatImm, IndexMap, IntImm
-from ..expr import Expr, PrimValue, ShapeExpr
+from ..expr import Expr, ShapeExpr, prim_value
from ..expr import Tuple as RxTuple
from . import _ffi_api
@@ -115,7 +115,7 @@ def flatten(x: Expr) -> Expr:
def layout_transform(
x: Expr,
index_map: Callable | IndexMap,
- pad_value: int | float | PrimValue | None = None,
+ pad_value: int | float | PrimExpr | None = None,
axis_separators: int | str | None = None, # str for IndexMap.AXIS_SEPARATOR
input_axis_separators: int | str | None = None, # str for IndexMap.AXIS_SEPARATOR
):
@@ -129,7 +129,7 @@ def layout_transform(
index_map : Callable | IndexMap
The transformation to apply.
- pad_value : Optional[int | float | PrimValue]
+ pad_value : Optional[int | float | PrimExpr]
The value used for padding if the transformation results in implicit padding.
If not specified, any value can be used.
@@ -151,14 +151,14 @@ def layout_transform(
# is applied, it would be converted to int32/float32, which may not match the x's type.
if pad_value is None:
pass
- elif not isinstance(pad_value, PrimValue):
+ elif not isinstance(pad_value, PrimExpr):
if x_dtype.matches_code(DataTypeCode.INT, DataTypeCode.UINT) and isinstance(pad_value, int):
pad_value = IntImm(x_dtype.dtype, pad_value)
elif x_dtype.matches_code(DataTypeCode.FLOAT, DataTypeCode.BFLOAT) and (
isinstance(pad_value, int | float)
):
pad_value = FloatImm(x_dtype.dtype, float(pad_value))
- pad_value = PrimValue(pad_value)
+ pad_value = prim_value(pad_value)
if axis_separators is None:
axis_separators = []
@@ -845,17 +845,21 @@ def slice_scatter(input_tensor: Expr, src: Expr, start, end, step, axis=0):
The computed result tensor with the same shape as `data`.
"""
- if not isinstance(start, PrimValue):
- start = PrimValue(start)
- if not isinstance(end, PrimValue):
- end = PrimValue(end)
- if not isinstance(step, PrimValue):
- step = PrimValue(step)
+ if not isinstance(start, PrimExpr):
+ start = prim_value(start)
+ if not isinstance(end, PrimExpr):
+ end = prim_value(end)
+ if not isinstance(step, PrimExpr):
+ step = prim_value(step)
return _ffi_api.slice_scatter(input_tensor, src, axis, start, end, step)
def one_hot(
- indices: Expr, on_value: PrimValue, off_value: PrimValue, depth: int, axis: int = -1
+ indices: Expr,
+ on_value: int | float | PrimExpr,
+ off_value: int | float | PrimExpr,
+ depth: int,
+ axis: int = -1,
) -> Expr:
"""Returns a one-hot tensor.
@@ -864,10 +868,10 @@ def one_hot(
indices : relax.Expr
The indices to set to `on_value`.
- on_value : relax.PrimValue
+ on_value : int | float | PrimExpr
The value to fill at `indices`.
- off_value : relax.PrimValue
+ off_value : int | float | PrimExpr
The value to fill at other locations.
depth : int
@@ -895,4 +899,6 @@ def one_hot(
[0, 1, 0],
[0, 0, 1]]
"""
+ on_value = prim_value(on_value)
+ off_value = prim_value(off_value)
return _ffi_api.one_hot(indices, on_value, off_value, depth, axis) # type: ignore
diff --git a/python/tvm/relax/op/memory/memory.py b/python/tvm/relax/op/memory/memory.py
index ba54eea9ef..2ec2fd04e3 100644
--- a/python/tvm/relax/op/memory/memory.py
+++ b/python/tvm/relax/op/memory/memory.py
@@ -15,7 +15,7 @@
# specific language governing permissions and limitations
"""Relax memory primitives."""
-from ...expr import Call, DataTypeImm, Expr, PrimValue, StringImm
+from ...expr import Call, DataTypeImm, Expr, StringImm, prim_value
from ...utils import convert_to_expr
from . import _ffi_api
@@ -55,7 +55,7 @@ def alloc_storage(
if isinstance(storage_scope, str):
storage_scope = StringImm(storage_scope)
if isinstance(virtual_device_index, int):
- virtual_device_index = PrimValue(virtual_device_index)
+ virtual_device_index = prim_value(virtual_device_index)
return _ffi_api.alloc_storage(size, virtual_device_index, storage_scope, dtype) # type: ignore
@@ -64,7 +64,7 @@ def alloc_tensor(
offset: int | Expr,
shape: Expr,
dtype: str | Expr,
- runtime_device_ind: int | Expr = PrimValue(0),
+ runtime_device_ind: int | Expr = prim_value(0),
) -> Call:
"""Construct a Call to allocate a tensor on a certain storage starting from the given offset.
@@ -92,7 +92,7 @@ def alloc_tensor(
A relax Call, which gets the allocated tensor.
"""
if isinstance(offset, int):
- offset = PrimValue(offset)
+ offset = prim_value(offset)
shape = convert_to_expr(shape)
if isinstance(dtype, str):
dtype = DataTypeImm(dtype)
diff --git a/python/tvm/relax/op/memory/view.py b/python/tvm/relax/op/memory/view.py
index 645ab94a1a..b9b5b0977f 100644
--- a/python/tvm/relax/op/memory/view.py
+++ b/python/tvm/relax/op/memory/view.py
@@ -28,7 +28,8 @@ while keeping the same underlying data.
from collections.abc import Sequence
-from tvm.relax import DataTypeImm, Expr, PrimValue, ShapeExpr
+from tvm.relax import DataTypeImm, Expr, ShapeExpr
+from tvm.relax.expr import prim_value
from tvm.tirx import PrimExpr
from . import _ffi_api
@@ -89,7 +90,11 @@ def view(
shape = _normalize(shape, ShapeExpr)
dtype = _normalize(dtype, DataTypeImm)
- relative_byte_offset = _normalize(relative_byte_offset, PrimValue)
+ relative_byte_offset = (
+ relative_byte_offset
+ if relative_byte_offset is None or isinstance(relative_byte_offset, Expr)
+ else prim_value(relative_byte_offset)
+ )
return _ffi_api.view(data, shape, dtype, relative_byte_offset) # type: ignore
diff --git a/python/tvm/relax/op/set.py b/python/tvm/relax/op/set.py
index 010b3d41ad..28979d58d2 100644
--- a/python/tvm/relax/op/set.py
+++ b/python/tvm/relax/op/set.py
@@ -21,7 +21,7 @@ import numpy as np # type: ignore
import tvm
-from ..expr import Expr, PrimValue
+from ..expr import Expr, prim_value
from . import _ffi_api
@@ -70,15 +70,15 @@ def unique(
"""
if isinstance(sorted, bool):
- sorted = PrimValue(sorted)
+ sorted = prim_value(sorted)
if isinstance(return_index, bool):
- return_index = PrimValue(return_index)
+ return_index = prim_value(return_index)
if isinstance(return_inverse, bool):
- return_inverse = PrimValue(return_inverse)
+ return_inverse = prim_value(return_inverse)
if isinstance(return_counts, bool):
- return_counts = PrimValue(return_counts)
+ return_counts = prim_value(return_counts)
if axis is not None and isinstance(axis, int):
- axis = PrimValue(axis)
+ axis = prim_value(axis)
return _ffi_api.unique( # type: ignore
x, sorted, return_index, return_inverse, return_counts, axis
)
diff --git a/python/tvm/relax/op/vm/vm.py b/python/tvm/relax/op/vm/vm.py
index 868ac92295..a7edb9c307 100644
--- a/python/tvm/relax/op/vm/vm.py
+++ b/python/tvm/relax/op/vm/vm.py
@@ -15,7 +15,7 @@
# specific language governing permissions and limitations
"""Relax vm primitives."""
-from ...expr import Call, DataTypeImm, Expr, PrimValue, StringImm, Tuple
+from ...expr import Call, DataTypeImm, Expr, StringImm, Tuple, prim_value
from ...utils import convert_to_expr
from . import _ffi_api
@@ -55,7 +55,7 @@ def alloc_storage(
if isinstance(storage_scope, str):
storage_scope = StringImm(storage_scope)
if isinstance(runtime_device_index, int):
- runtime_device_index = PrimValue(runtime_device_index)
+ runtime_device_index = prim_value(runtime_device_index)
return _ffi_api.alloc_storage(shape, runtime_device_index, dtype, storage_scope) # type: ignore
@@ -64,7 +64,7 @@ def alloc_tensor(
offset: int | Expr,
shape: Expr,
dtype: str | Expr,
- runtime_device_ind: int | Expr = PrimValue(0),
+ runtime_device_ind: int | Expr = prim_value(0),
) -> Call:
"""Construct a Call to allocate a tensor on a certain storage starting from the given offset.
@@ -92,7 +92,7 @@ def alloc_tensor(
A relax Call, which gets the allocated tensor.
"""
if isinstance(offset, int):
- offset = PrimValue(offset)
+ offset = prim_value(offset)
shape = convert_to_expr(shape)
if isinstance(dtype, str):
dtype = DataTypeImm(dtype)
diff --git a/python/tvm/relax/relax_to_pyfunc_converter.py b/python/tvm/relax/relax_to_pyfunc_converter.py
index 970e51360e..6a1b199838 100644
--- a/python/tvm/relax/relax_to_pyfunc_converter.py
+++ b/python/tvm/relax/relax_to_pyfunc_converter.py
@@ -728,11 +728,11 @@ class RelaxExpressionConverter:
for arg in packed_args:
converted_arg = self.convert_expr(arg, args)
if isinstance(converted_arg, str) and converted_arg.startswith("<"):
- # Handle PrimValue and other special cases
- if "PrimValue" in converted_arg:
- # Extract the value from PrimValue
+ # Handle PrimExpr and other special cases
+ if "PrimExpr" in converted_arg:
+ # Extract the value from PrimExpr
try:
- # Try to get the actual value from the PrimValue
+ # Try to get the actual value from the PrimExpr
if hasattr(arg, "value"):
converted_arg = arg.value
else:
diff --git a/python/tvm/relax/script/builder/ir.py b/python/tvm/relax/script/builder/ir.py
index 8c4f0191db..bdb5e51029 100644
--- a/python/tvm/relax/script/builder/ir.py
+++ b/python/tvm/relax/script/builder/ir.py
@@ -686,7 +686,7 @@ def If(condition: Expr | PrimExpr) -> frame.IfFrame: # pylint: disable=invalid-
"""
if not isinstance(condition, Expr):
- condition = relax.PrimValue(condition)
+ condition = relax.prim_value(condition)
return _ffi_api.If(condition) # type: ignore[attr-defined] # pylint: disable=no-member
@@ -748,21 +748,23 @@ def shape(value: list[PrimExpr]) -> Expr:
return relax.ShapeExpr(value) # pylint: disable=no-member # type: ignore
-############################### PrimValue ##############################
+############################### PrimExpr ###############################
-def prim_value(value: PrimExpr) -> Expr:
- """Create a prim value expression.
+def prim_value(value: PrimExpr | int | float) -> Expr:
+ """Convert a value to a primitive expression.
+
Parameters
----------
- value : PrimExpr
- The value of the prim value.
+ value : PrimExpr | int | float
+ The value to convert.
+
Returns
-------
res : Expr
- The result prim value.
+ The primitive expression.
"""
- return relax.PrimValue(value) # type: ignore[attr-defined] # pylint: disable=no-member
+ return relax.prim_value(value) # type: ignore[attr-defined] # pylint: disable=no-member
def str(value: py_str) -> Expr:
diff --git a/python/tvm/relax/script/parser/parser.py b/python/tvm/relax/script/parser/parser.py
index 112b5b593b..fed7e14cfe 100644
--- a/python/tvm/relax/script/parser/parser.py
+++ b/python/tvm/relax/script/parser/parser.py
@@ -39,6 +39,12 @@ from .entry import (
_normalize_ty_proxy,
)
+relax.Expr._dispatch_type = relax.Expr # pylint: disable=protected-access
+dispatch.register_op(relax.Expr, doc.GtE, 0)(lambda lhs, rhs: lhs >= rhs)
+dispatch.register_op(relax.Expr, doc.Gt, 0)(lambda lhs, rhs: lhs > rhs)
+dispatch.register_op(relax.Expr, doc.LtE, 0)(lambda lhs, rhs: lhs <= rhs)
+dispatch.register_op(relax.Expr, doc.Lt, 0)(lambda lhs, rhs: lhs < rhs)
+
def bind_assign_value(
self: Parser,
@@ -46,6 +52,7 @@ def bind_assign_value(
var_name: str,
value: Any,
anno_ty: Type | None = None,
+ emit_prim_expr: bool = False,
) -> Any:
var_table = self.var_table.get()
@@ -80,6 +87,10 @@ def bind_assign_value(
IRBuilder.name(var_name, value)
return value
+ if isinstance(value, tirx.PrimExpr):
+ if not emit_prim_expr:
+ return value
+
if isinstance(value, tuple):
value = convert_to_expr(value)
if isinstance(value, numbers.Number):
@@ -95,12 +106,15 @@ def bind_assign_value(
var = R.emit_match_cast(value.value, value.ty)
else:
return value
- # raise TypeError(f"Unsupported type {type(value)} in assignment")
IRBuilder.name(var_name, var)
return var
+def is_prim_value_call(node: doc.expr) -> bool:
+ return isinstance(node, doc.Call) and getattr(node.func, "attr", None) == "prim_value"
+
+
def eval_ty_proxy(self: Parser, node: doc.expr) -> TypeProxy:
try:
annotation = self.eval_expr(node)
@@ -374,7 +388,10 @@ def visit_assign(self: Parser, node: doc.Assign) -> None:
self.eval_assign(
target=lhs,
source=rhs,
- bind_value=bind_assign_value,
+ bind_value=functools.partial(
+ bind_assign_value,
+ emit_prim_expr=is_prim_value_call(node.value),
+ ),
allow_shadowing=True,
)
@@ -387,7 +404,11 @@ def visit_ann_assign(self: Parser, node: doc.AnnAssign) -> None:
self.eval_assign(
target=lhs,
source=rhs,
- bind_value=functools.partial(bind_assign_value, anno_ty=anno_ty),
+ bind_value=functools.partial(
+ bind_assign_value,
+ anno_ty=anno_ty,
+ emit_prim_expr=is_prim_value_call(node.value),
+ ),
allow_shadowing=True,
)
diff --git a/python/tvm/relax/testing/ast_printer.py b/python/tvm/relax/testing/ast_printer.py
index 1bd58ce636..0c014728a0 100644
--- a/python/tvm/relax/testing/ast_printer.py
+++ b/python/tvm/relax/testing/ast_printer.py
@@ -207,9 +207,6 @@ class ASTPrinter(ExprFunctor):
false_branch=self.visit_expr(op.false_branch),
)
- def visit_prim_value_(self, op: relax.PrimValue) -> str:
- return self.build_expr(op, "PrimValue", value=self.visit_prim_expr_(op.value))
-
def visit_string_imm_(self, op: relax.StringImm) -> str:
return self.build_expr(op, "StringImm", value=wrap_quotes(op.value))
diff --git a/python/tvm/relax/transform/fold_batch_norm_to_conv2d_for_inference.py b/python/tvm/relax/transform/fold_batch_norm_to_conv2d_for_inference.py
index 18d75b66bf..47056d3837 100644
--- a/python/tvm/relax/transform/fold_batch_norm_to_conv2d_for_inference.py
+++ b/python/tvm/relax/transform/fold_batch_norm_to_conv2d_for_inference.py
@@ -81,7 +81,7 @@ class FoldBatchnormToConv2D:
bn_attrs = bn_op.attrs
bn_variance = relax.op.add(
- bn_variance, relax.PrimValue(tirx.FloatImm("float32", bn_attrs["epsilon"]))
+ bn_variance, relax.prim_value(tirx.FloatImm("float32", bn_attrs["epsilon"]))
)
dino = relax.op.sqrt(bn_variance)
wt = relax.op.divide(bn_weight, dino)
diff --git a/python/tvm/relax/transform/ipc_allreduce_rewrite.py b/python/tvm/relax/transform/ipc_allreduce_rewrite.py
index 0dee144004..9b551e2579 100644
--- a/python/tvm/relax/transform/ipc_allreduce_rewrite.py
+++ b/python/tvm/relax/transform/ipc_allreduce_rewrite.py
@@ -117,7 +117,7 @@ class _Visitor(PyExprVisitor): # pylint: disable=abstract-method
# The "cuda_ipc.custom_allreduce" implementation does not
# yet support num_groups>1, and therefore does not use the
# `in_group` argument.
- [allreduce_input, relax.PrimValue(self.allreduce_strategy), allreduce_output],
+ [allreduce_input, relax.prim_value(self.allreduce_strategy), allreduce_output],
)
diff --git a/python/tvm/relax/transform/lazy_transform_params.py b/python/tvm/relax/transform/lazy_transform_params.py
index 8a35486793..4eb3b39619 100644
--- a/python/tvm/relax/transform/lazy_transform_params.py
+++ b/python/tvm/relax/transform/lazy_transform_params.py
@@ -60,7 +60,7 @@ class ForwardCollector(PyExprVisitor):
for i, expr in enumerate(binding.value.fields):
if expr not in self.out_tuple_map:
self.out_tuple_map[expr] = []
- self.out_tuple_map[expr].append(relax.PrimValue(i))
+ self.out_tuple_map[expr].append(relax.prim_value(i))
else:
self.is_tuple_get_item_input = False
super().visit_var_binding_(binding)
@@ -266,7 +266,7 @@ class LazyInputMutator(PyExprMutator):
get_item_result = self.builder_.emit(
relax.Call(
relax.ExternFunc(self.func_creator.fget_item),
- self.func_creator.extra_get_item_params + [relax.PrimValue(index)],
+ self.func_creator.extra_get_item_params + [relax.prim_value(index)],
None,
[relax.AnyType()],
)
@@ -287,7 +287,7 @@ class LazyInputMutator(PyExprMutator):
get_item_result = self.builder_.emit(
relax.Call(
relax.ExternFunc(self.func_creator.fget_item),
- self.func_creator.extra_get_item_params + [relax.PrimValue(node.index)],
+ self.func_creator.extra_get_item_params + [relax.prim_value(node.index)],
None,
[relax.AnyType()],
)
diff --git a/python/tvm/relax/transform/legalize_ops/binary.py b/python/tvm/relax/transform/legalize_ops/binary.py
index 355fed86b9..2ca1d6fa64 100644
--- a/python/tvm/relax/transform/legalize_ops/binary.py
+++ b/python/tvm/relax/transform/legalize_ops/binary.py
@@ -21,7 +21,13 @@ from tvm import topi
from ...block_builder import BlockBuilder
from ...expr import Call, Expr
-from .common import LegalizeFunc, TEFunc, _try_convert_to_scalar_const, register_legalize
+from .common import (
+ LegalizeFunc,
+ TEFunc,
+ _is_relax_expr,
+ _try_convert_to_scalar_const,
+ register_legalize,
+)
def _binary(te_func: TEFunc) -> LegalizeFunc:
@@ -36,7 +42,7 @@ def _binary(te_func: TEFunc) -> LegalizeFunc:
# If it is not, we then check if arg0 is a constant scalar.
arg0 = call.args[0]
arg1 = _try_convert_to_scalar_const(call.args[1])
- if isinstance(arg1, Expr): # type: ignore
+ if _is_relax_expr(arg1):
arg0 = _try_convert_to_scalar_const(arg0)
return bb.call_te(te_func, arg0, arg1)
diff --git a/python/tvm/relax/transform/legalize_ops/common.py b/python/tvm/relax/transform/legalize_ops/common.py
index f464c248e3..e6151adbae 100644
--- a/python/tvm/relax/transform/legalize_ops/common.py
+++ b/python/tvm/relax/transform/legalize_ops/common.py
@@ -21,7 +21,7 @@ from collections.abc import Callable
import tvm
from tvm import te
from tvm.runtime import DataTypeCode
-from tvm.tirx import FloatImm, IntImm
+from tvm.tirx import FloatImm, IntImm, PrimExpr
from ...block_builder import BlockBuilder
from ...expr import Call, Constant, Expr
@@ -39,6 +39,10 @@ TEFunc = Callable[..., te.Tensor]
LegalizeFunc = Callable[[BlockBuilder, Call], Expr]
+def _is_relax_expr(expr: object) -> bool:
+ return isinstance(expr, Expr) and not isinstance(expr, PrimExpr)
+
+
def _try_convert_to_scalar_const(
expr: Expr, python_native: bool = False
) -> Expr | FloatImm | IntImm | bool | float | int:
diff --git a/python/tvm/relax/transform/legalize_ops/create.py b/python/tvm/relax/transform/legalize_ops/create.py
index 3cab08cf26..b8ddb2848e 100644
--- a/python/tvm/relax/transform/legalize_ops/create.py
+++ b/python/tvm/relax/transform/legalize_ops/create.py
@@ -23,7 +23,7 @@ import numpy as np
from tvm import tirx, topi
from ...block_builder import BlockBuilder
-from ...expr import Call, Expr, PrimValue, ShapeExpr, const
+from ...expr import Call, Expr, ShapeExpr, const
from ...type import ShapeType
from .common import LegalizeFunc, _try_convert_to_scalar_const, register_legalize
@@ -115,12 +115,12 @@ register_legalize("relax.eye_like", _eye(is_like=True, primfunc_name="eye_like")
@register_legalize("relax.arange")
def _arange(bb: BlockBuilder, call: Call) -> Expr:
assert len(call.args) == 3
- assert all([isinstance(x, PrimValue) for x in call.args])
- start, end, step = [x.value for x in call.args]
+ assert all(isinstance(x, tirx.PrimExpr) for x in call.args)
+ start, end, step = call.args
dtype = call.attrs.dtype
- def is_const_scalar(x: PrimValue):
- return isinstance(x.value, tirx.IntImm | tirx.FloatImm)
+ def is_const_scalar(x: tirx.PrimExpr):
+ return isinstance(x, tirx.IntImm | tirx.FloatImm)
if all([is_const_scalar(x) for x in call.args]):
return const(np.arange(start.value, end.value, step.value, dtype=dtype), dtype=dtype)
@@ -132,8 +132,8 @@ def _arange(bb: BlockBuilder, call: Call) -> Expr:
def _hamming_window(bb: BlockBuilder, call: Call) -> Expr:
assert len(call.args) == 4
dtype = call.attrs.dtype
- window_size = call.args[0].value
- periodic = call.args[1].value
- alpha = call.args[2].value
- beta = call.args[3].value
+ window_size = call.args[0]
+ periodic = call.args[1]
+ alpha = call.args[2]
+ beta = call.args[3]
return bb.call_te(topi.hamming_window, window_size, periodic, alpha, beta, dtype)
diff --git a/python/tvm/relax/transform/legalize_ops/datatype.py b/python/tvm/relax/transform/legalize_ops/datatype.py
index c8acfdff9c..d08b2b8555 100644
--- a/python/tvm/relax/transform/legalize_ops/datatype.py
+++ b/python/tvm/relax/transform/legalize_ops/datatype.py
@@ -21,13 +21,13 @@ from tvm import relax, topi
from ...block_builder import BlockBuilder
from ...expr import Call, Expr
-from .common import _try_convert_to_scalar_const, register_legalize
+from .common import _is_relax_expr, _try_convert_to_scalar_const, register_legalize
@register_legalize("relax.astype")
def _astype(bb: BlockBuilder, call: Call) -> Expr:
arg = _try_convert_to_scalar_const(call.args[0], python_native=True)
- if isinstance(arg, Expr): # type: ignore
+ if _is_relax_expr(arg):
return bb.call_te(topi.cast, arg, call.attrs.dtype)
else:
return relax.const(arg, call.attrs.dtype)
diff --git a/python/tvm/relax/transform/legalize_ops/index.py b/python/tvm/relax/transform/legalize_ops/index.py
index 5c7fdca1f4..7ccf0f63ab 100644
--- a/python/tvm/relax/transform/legalize_ops/index.py
+++ b/python/tvm/relax/transform/legalize_ops/index.py
@@ -21,7 +21,7 @@ from tvm import te, tirx, topi
from tvm.ir import PrimType
from ...block_builder import BlockBuilder
-from ...expr import Call, Expr, PrimValue, Tuple
+from ...expr import Call, Expr, Tuple
from ...op import tensor_to_shape
from ...type import ShapeType
from .common import register_legalize
@@ -40,8 +40,8 @@ def _strided_slice(bb: BlockBuilder, call: Call) -> Expr:
if isinstance(relax_tuple, Tuple):
output = []
for field in relax_tuple.fields:
- assert isinstance(field, PrimValue)
- output.append(field.value)
+ assert isinstance(field, tirx.PrimExpr)
+ output.append(field)
return output
output = []
diff --git a/python/tvm/relax/transform/legalize_ops/manipulate.py b/python/tvm/relax/transform/legalize_ops/manipulate.py
index acb00ead0f..bb37f03bb8 100644
--- a/python/tvm/relax/transform/legalize_ops/manipulate.py
+++ b/python/tvm/relax/transform/legalize_ops/manipulate.py
@@ -300,9 +300,8 @@ def _slice_scatter(bb: BlockBuilder, call: Call) -> Expr:
@register_legalize("relax.one_hot")
def _one_hot(bb: BlockBuilder, call: Call) -> Expr:
indices, on_value, off_value = call.args
- if not (isinstance(on_value, relax.PrimValue) and isinstance(off_value, relax.PrimValue)):
- raise ValueError("on_value and off_value must be PrimValue")
- on_value, off_value = on_value.value, off_value.value
+ if not (isinstance(on_value, tirx.PrimExpr) and isinstance(off_value, tirx.PrimExpr)):
+ raise ValueError("on_value and off_value must be PrimExpr")
if on_value.ty != off_value.ty:
raise ValueError("on_value and off_value must have the same dtype")
return bb.call_te(
diff --git a/python/tvm/relax/transform/lower_gpu_ipc_alloc_storage.py b/python/tvm/relax/transform/lower_gpu_ipc_alloc_storage.py
index bf90ccc455..7472c75a9f 100644
--- a/python/tvm/relax/transform/lower_gpu_ipc_alloc_storage.py
+++ b/python/tvm/relax/transform/lower_gpu_ipc_alloc_storage.py
@@ -78,6 +78,6 @@ class _Rewriter(PyExprMutator):
)
return relax.Call(
self.memory_alloc_tensor_op,
- args=[ipc_alloc_storage, call.args[2], shape, dtype, relax.PrimValue(0)],
+ args=[ipc_alloc_storage, call.args[2], shape, dtype, relax.prim_value(0)],
ty_args=call.ty_args,
)
diff --git a/python/tvm/relax/utils.py b/python/tvm/relax/utils.py
index 9091b3f499..7bd2af9831 100644
--- a/python/tvm/relax/utils.py
+++ b/python/tvm/relax/utils.py
@@ -37,7 +37,7 @@ from ..te import Tensor as te_Tensor
from ..te import create_prim_func
from ..tirx import PrimExpr
from . import _ffi_api
-from .expr import Expr, Function, PrimValue, ShapeExpr, StringImm, te_tensor
+from .expr import Expr, Function, ShapeExpr, StringImm, te_tensor
from .expr import Tuple as rx_Tuple
from .type import ShapeType, TensorType
@@ -87,20 +87,20 @@ def metadata_partitioner(rx_txt: str) -> list[str]:
def convert_to_expr(value: Any) -> Expr:
"""Helper function to convert the input to Expr, which follows the rules:
1. Return the input itself if it's already a `relax.Expr`;
- 2. Return `relax.PrimValue` if the input is a `PrimExpr`;
+ 2. Return `PrimExpr` if the input is a primitive scalar;
3. Return `relax.StringImm` if the input is `tvm.String` or `str`;
4. Return `relax.Tuple` if the input is a tuple/list of `Expr`.
Notes
-----
1. `tvm.tirx.StringImm` is not allowed because of ambiguity,
- which can be either `relax.StringImm` or `relax.PrimValue`.
+ which can be either `relax.StringImm` or `PrimExpr`.
"""
if isinstance(value, int):
- return PrimValue(tirx.IntImm("int64", value))
+ return tirx.IntImm("int64", value)
if isinstance(value, float):
- return PrimValue(tirx.FloatImm("float64", value))
+ return tirx.FloatImm("float64", value)
tvm_value = tvm_ffi.convert(value)
# Case 1
@@ -110,11 +110,11 @@ def convert_to_expr(value: Any) -> Expr:
if isinstance(tvm_value, tirx.StringImm):
raise TypeError(
"Cannot convert `tirx.StringImm` to `relax.Expr` because of ambiguity,"
- "which can be either `relax.StringImm` or `relax.PrimValue` "
+ "which can be either `relax.StringImm` or `PrimExpr` "
)
# Case 2
if isinstance(tvm_value, PrimExpr):
- return PrimValue(value)
+ return tvm_value
# Case 3
if isinstance(tvm_value, str):
return StringImm(value)
@@ -221,6 +221,12 @@ def gen_call_tir_inputs(
"""
def _convert_te_arg_helper(arg):
+ if isinstance(arg, tirx.PrimExpr):
+ _copy_undefined_var(arg)
+ new_arg = tirx.stmt_functor.substitute(arg, tir_var_map)
+ extra_tir_args_list.append(new_arg)
+ return new_arg
+
if isinstance(arg, Expr): # type: ignore
if isinstance(arg.ty, TensorType):
assert isinstance(arg.ty.shape, ShapeExpr), (
@@ -251,9 +257,6 @@ def gen_call_tir_inputs(
return [_convert_te_arg_helper(val) for val in arg.values]
if isinstance(arg.ty, PrimType):
- if isinstance(arg, PrimValue):
- return _convert_te_arg_helper(arg.value)
-
n_args = len(create_primfunc_args)
if isinstance(arg, tvm.relax.Var):
name = arg.name_hint
@@ -279,11 +282,6 @@ def gen_call_tir_inputs(
"emit_te only supports dict with string as the key currently"
)
return {k: _convert_te_arg_helper(arg[k]) for k in arg}
- elif isinstance(arg, tirx.PrimExpr):
- _copy_undefined_var(arg)
- new_arg = tirx.stmt_functor.substitute(arg, tir_var_map)
- extra_tir_args_list.append(new_arg)
- return new_arg
elif isinstance(arg, int | float | str | Type | Attrs) or arg is None:
return arg
raise TypeError(f"not supported type in emit_te: {type(arg)}")
diff --git a/src/arith/canonical_simplify.cc b/src/arith/canonical_simplify.cc
index 1c7c979ba4..fb5366835c 100644
--- a/src/arith/canonical_simplify.cc
+++ b/src/arith/canonical_simplify.cc
@@ -199,7 +199,7 @@ class SplitExprNode : public CanonicalExprNode {
*/
void PushCastToChildren(PrimType dtype) {
this->index = cast(dtype, this->index);
- this->BaseExprNode::ty = dtype;
+ this->ExprNode::ty = dtype;
}
inline bool IndexEqual(const SplitExpr& other) const;
@@ -390,7 +390,7 @@ class SumExprNode : public CanonicalExprNode {
for (auto& arg : args) {
arg.CopyOnWrite()->PushCastToChildren(dtype);
}
- this->BaseExprNode::ty = dtype;
+ this->ExprNode::ty = dtype;
}
TVM_FFI_DECLARE_OBJECT_INFO_FINAL("arith.SumExpr", SumExprNode, CanonicalExprNode);
@@ -648,7 +648,7 @@ class CanonicalSimplifier::Impl : public RewriteSimplifier::Impl {
expr = op->Normalize();
}
ffi::ObjectPtr<SplitExprNode> n = ffi::make_object<SplitExprNode>();
- n->BaseExprNode::ty = expr.ty();
+ n->ExprNode::ty = expr.ty();
n->index = std::move(expr);
n->div_mode = kTruncDiv;
return SplitExpr(n);
@@ -685,7 +685,7 @@ class CanonicalSimplifier::Impl : public RewriteSimplifier::Impl {
return op.value();
}
ffi::ObjectPtr<SumExprNode> n = ffi::make_object<SumExprNode>();
- n->BaseExprNode::ty = expr.ty();
+ n->ExprNode::ty = expr.ty();
if (const auto* op = expr.as<IntImmNode>()) {
n->base = op->value;
return SumExpr(n);
@@ -794,8 +794,8 @@ void CanonicalSimplifier::Impl::SeparateDivisibleParts(const SumExprNode* psum,
SumExpr* out_non_divisible) {
auto divisible = ffi::make_object<SumExprNode>();
auto non_divisible = ffi::make_object<SumExprNode>();
- divisible->BaseExprNode::ty = psum->ty();
- non_divisible->BaseExprNode::ty = psum->ty();
+ divisible->ExprNode::ty = psum->ty();
+ non_divisible->ExprNode::ty = psum->ty();
if (psum->base % coeff == 0) {
divisible->base = psum->base;
diff --git a/src/arith/const_fold.h b/src/arith/const_fold.h
index 0f1bd4d8a6..94e1219f08 100644
--- a/src/arith/const_fold.h
+++ b/src/arith/const_fold.h
@@ -79,8 +79,8 @@ inline bool IsIndexType(DLDataType type) {
inline bool IsIndexTypedExpr(const PrimExprNode* expr) {
TVM_FFI_DCHECK(expr != nullptr);
- TVM_FFI_DCHECK(expr->BaseExprNode::ty.defined());
- const auto* prim_ty = expr->BaseExprNode::ty.as<PrimTypeNode>();
+ TVM_FFI_DCHECK(expr->ExprNode::ty.defined());
+ const auto* prim_ty = expr->ExprNode::ty.as<PrimTypeNode>();
TVM_FFI_DCHECK(prim_ty != nullptr);
return IsIndexType(prim_ty->dtype);
}
diff --git a/src/arith/iter_affine_map.cc b/src/arith/iter_affine_map.cc
index f06d916547..f3079c10a7 100644
--- a/src/arith/iter_affine_map.cc
+++ b/src/arith/iter_affine_map.cc
@@ -67,7 +67,7 @@ TVM_FFI_STATIC_INIT_BLOCK() {
IterSplitExpr::IterSplitExpr(IterMark source) {
auto n = ffi::make_object<IterSplitExprNode>();
auto one = MakeConst(source->source.ty(), 1);
- n->BaseExprNode::ty = source->source.ty();
+ n->ExprNode::ty = source->source.ty();
n->source = std::move(source);
n->extent = n->source->extent;
n->lower_factor = one;
@@ -78,7 +78,7 @@ IterSplitExpr::IterSplitExpr(IterMark source) {
IterSplitExpr::IterSplitExpr(IterMark source, PrimExpr scale) {
auto n = ffi::make_object<IterSplitExprNode>();
auto one = MakeConst(source->source.ty(), 1);
- n->BaseExprNode::ty = source->source.ty();
+ n->ExprNode::ty = source->source.ty();
n->source = std::move(source);
n->extent = n->source->extent;
n->lower_factor = one;
@@ -89,7 +89,7 @@ IterSplitExpr::IterSplitExpr(IterMark source, PrimExpr scale) {
IterSplitExpr::IterSplitExpr(IterMark source, PrimExpr lower_factor, PrimExpr extent,
PrimExpr scale) {
auto n = ffi::make_object<IterSplitExprNode>();
- n->BaseExprNode::ty = source->source.ty();
+ n->ExprNode::ty = source->source.ty();
n->source = std::move(source);
n->lower_factor = std::move(lower_factor);
n->extent = std::move(extent);
@@ -109,7 +109,7 @@ TVM_FFI_STATIC_INIT_BLOCK() {
IterSumExpr::IterSumExpr(ffi::Array<IterSplitExpr> args, PrimExpr base) {
auto n = ffi::make_object<IterSumExprNode>();
- n->BaseExprNode::ty = base.ty();
+ n->ExprNode::ty = base.ty();
n->args = std::move(args);
n->base = std::move(base);
data_ = std::move(n);
diff --git a/src/backend/trn/transform/lower_trainium_layout.cc b/src/backend/trn/transform/lower_trainium_layout.cc
index fb1d92c521..38a51e930b 100644
--- a/src/backend/trn/transform/lower_trainium_layout.cc
+++ b/src/backend/trn/transform/lower_trainium_layout.cc
@@ -213,7 +213,7 @@ class TrainiumLayoutApplier : public arith::IRMutatorWithAnalyzer {
if (load_returns_bool) {
TVM_FFI_ICHECK_EQ(load->buffer->dtype->dtype, (DLDataType{kDLInt, 8, 1}))
<< "Expected int8 backing array for boolean tensor";
- load.CopyOnWrite()->BaseExprNode::ty = PrimType::Int(8);
+ load.CopyOnWrite()->ExprNode::ty = PrimType::Int(8);
return tvm::cast(PrimType::Bool(), load);
} else {
return std::move(load);
diff --git a/src/ir/expr.cc b/src/ir/expr.cc
index f73cd6ae39..da0cf1f5af 100644
--- a/src/ir/expr.cc
+++ b/src/ir/expr.cc
@@ -37,9 +37,8 @@
namespace tvm {
TVM_FFI_STATIC_INIT_BLOCK() {
- BaseExprNode::RegisterReflection();
+ ExprNode::RegisterReflection();
PrimExprNode::RegisterReflection();
- RelaxExprNode::RegisterReflection();
BaseFuncNode::RegisterReflection();
GlobalVarNode::RegisterReflection();
IntImmNode::RegisterReflection();
@@ -81,7 +80,7 @@ IntImm::IntImm(PrimType value_ty, int64_t value, Span span) {
<< "Literal value " << value << " exceeds maximum of " << runtime_dtype;
}
ffi::ObjectPtr<IntImmNode> node = ffi::make_object<IntImmNode>();
- node->BaseExprNode::ty = std::move(value_ty);
+ node->ExprNode::ty = std::move(value_ty);
node->value = value;
node->span = span;
data_ = std::move(node);
@@ -200,7 +199,7 @@ FloatImm::FloatImm(PrimType value_ty, double value, Span span) {
}
}
ffi::ObjectPtr<FloatImmNode> node = ffi::make_object<FloatImmNode>();
- node->BaseExprNode::ty = std::move(value_ty);
+ node->ExprNode::ty = std::move(value_ty);
node->value = value;
node->span = span;
data_ = std::move(node);
diff --git a/src/ir/module.cc b/src/ir/module.cc
index 0b52babe60..f4b8209097 100644
--- a/src/ir/module.cc
+++ b/src/ir/module.cc
@@ -203,7 +203,7 @@ IRModule IRModuleNode::ShallowCopy() {
return IRModule(this->functions, this->source_map, this->attrs, this->global_infos);
}
-IRModule IRModule::FromExpr(const RelaxExpr& expr,
+IRModule IRModule::FromExpr(const Expr& expr,
const tvm::ffi::Map<GlobalVar, BaseFunc>& global_funcs) {
auto mod = IRModule(global_funcs);
ffi::String gv_name;
@@ -276,7 +276,7 @@ TVM_FFI_STATIC_INIT_BLOCK() {
})
.def("ir.Module_Add",
[](IRModule mod, GlobalVar var, ffi::ObjectRef val, bool update) -> IRModule {
- TVM_FFI_ICHECK(val->IsInstance<RelaxExprNode>());
+ TVM_FFI_ICHECK(val->IsInstance<BaseFuncNode>());
mod->Add(var, val.as_or_throw<BaseFunc>(), update);
return mod;
})
diff --git a/src/relax/analysis/type_analysis.cc b/src/relax/analysis/type_analysis.cc
index 9111866cdc..8b50e6d10f 100644
--- a/src/relax/analysis/type_analysis.cc
+++ b/src/relax/analysis/type_analysis.cc
@@ -479,7 +479,7 @@ class TypeBaseChecker : public TypeFunctor<BaseCheckResult(const Type&, const Ty
* \param rhs The right hand shape.
* \return CheckResult.
*/
- virtual BaseCheckResult PrimValueMatchCheck(const PrimExpr& lhs, const PrimExpr& rhs) {
+ virtual BaseCheckResult PrimExprMatchCheck(const PrimExpr& lhs, const PrimExpr& rhs) {
// get static shape checking right.
auto* int_lhs = lhs.as<IntImmNode>();
auto* int_rhs = rhs.as<IntImmNode>();
@@ -504,7 +504,7 @@ class TypeBaseChecker : public TypeFunctor<BaseCheckResult(const Type&, const Ty
BaseCheckResult ret = BaseCheckResult::kPass;
for (size_t i = 0; i < lhs.size(); ++i) {
- auto cmp_ret = PrimValueMatchCheck(lhs[i], rhs[i]);
+ auto cmp_ret = PrimExprMatchCheck(lhs[i], rhs[i]);
if (ret == BaseCheckResult::kFailL0) return ret;
ret = CombineCheck(cmp_ret, ret);
}
@@ -869,9 +869,9 @@ class CallRetTypeDeriver : public TypeBaseChecker {
using TypeBaseChecker::ShapeMatchCheck;
// Match shape values in between param(lhs) and arg(rhs)
- BaseCheckResult PrimValueMatchCheck(const PrimExpr& param, const PrimExpr& arg) final {
+ BaseCheckResult PrimExprMatchCheck(const PrimExpr& param, const PrimExpr& arg) final {
if (!populate_mapping_) {
- return TypeBaseChecker::PrimValueMatchCheck(param, arg);
+ return TypeBaseChecker::PrimExprMatchCheck(param, arg);
}
if (auto* ptr = param.as<tirx::VarNode>()) {
@@ -892,7 +892,7 @@ class CallRetTypeDeriver : public TypeBaseChecker {
// Do not attempt to do prove when param contains a symbolic expr.
// such expression might depends on a later defined var in params created by dyn fusion.
// example: f(a: Tensor[(n+1)], s: Shape[(n,)]), the (n+1) case here.
- return TypeBaseChecker::PrimValueMatchCheck(param, arg);
+ return TypeBaseChecker::PrimExprMatchCheck(param, arg);
}
}
@@ -1387,8 +1387,8 @@ class SymbolicVarCollector : public relax::ExprVisitor,
this->VisitTypeExprField(val);
}
}
- if (auto prim_value = expr.as<relax::PrimValue>()) {
- this->VisitTypeExprField(prim_value.value()->value);
+ if (auto prim_value = expr.as<PrimExpr>()) {
+ this->VisitTypeExprField(prim_value.value());
}
}
diff --git a/src/relax/backend/contrib/tensorrt/codegen.cc b/src/relax/backend/contrib/tensorrt/codegen.cc
index 7b7f04939a..efa177d661 100644
--- a/src/relax/backend/contrib/tensorrt/codegen.cc
+++ b/src/relax/backend/contrib/tensorrt/codegen.cc
@@ -126,10 +126,11 @@ class CollectFromCompositeFunctionBody : public ExprVisitor {
for (size_t i = 0; i < call_node->args.size() && i < arg_infos.size(); ++i) {
const Expr& arg = call_node->args[i];
const std::string key = "arg_" + std::string(arg_infos[i]->name);
- if (const auto* prim_value = arg.as<PrimValueNode>()) {
- if (const auto* imm = prim_value->value.as<IntImmNode>()) {
+ if (const auto* prim_value = arg.as<PrimExprNode>()) {
+ PrimExpr value = ffi::GetRef<PrimExpr>(prim_value);
+ if (const auto* imm = value.as<IntImmNode>()) {
node_->SetAttr(key, static_cast<int64_t>(imm->value));
- } else if (const auto* fimm = prim_value->value.as<FloatImmNode>()) {
+ } else if (const auto* fimm = value.as<FloatImmNode>()) {
node_->SetAttr(key, static_cast<double>(fimm->value));
}
} else if (const auto* shape_expr = arg.as<ShapeExprNode>()) {
@@ -163,7 +164,9 @@ class CollectFromCompositeFunctionBody : public ExprVisitor {
if (tuple == nullptr) continue;
ffi::Array<PrimExpr> values;
for (const Expr& field : tuple->fields) {
- if (const auto* prim_value = field.as<PrimValueNode>()) values.push_back(prim_value->value);
+ if (const auto* prim_value = field.as<PrimExprNode>()) {
+ values.push_back(ffi::GetRef<PrimExpr>(prim_value));
+ }
}
if (values.size() == tuple->fields.size()) SetIntArrayAttr(kNames[i - 1], values);
}
diff --git a/src/relax/backend/vm/codegen_vm.cc b/src/relax/backend/vm/codegen_vm.cc
index d6c72f2cc9..e9fda4a0a8 100644
--- a/src/relax/backend/vm/codegen_vm.cc
+++ b/src/relax/backend/vm/codegen_vm.cc
@@ -242,15 +242,16 @@ class CodeGenVM : public ExprFunctor<Instruction::Arg(const Expr&)> {
return builder_->ConvertConstant(ffi::Shape(shape));
}
- Instruction::Arg VisitExpr_(const PrimValueNode* op) final {
- if (auto* int_imm = op->value.as<IntImmNode>()) {
+ Instruction::Arg VisitExpr_(const PrimExprNode* op) final {
+ PrimExpr value = ffi::GetRef<PrimExpr>(op);
+ if (auto* int_imm = value.as<IntImmNode>()) {
return builder_->ConvertConstant(int_imm->value);
- } else if (auto* float_imm = op->value.as<FloatImmNode>()) {
+ } else if (auto* float_imm = value.as<FloatImmNode>()) {
return builder_->ConvertConstant(float_imm->value);
} else {
TVM_FFI_THROW(InternalError)
- << "PrimValue should only contain constant after VMShapeLower, "
- << "but received " << ffi::GetRef<Expr>(op) << " with type " << op->value->GetTypeKey();
+ << "PrimExpr should only contain constant after VMShapeLower, "
+ << "but received " << value << " with type " << value->GetTypeKey();
TVM_FFI_UNREACHABLE();
}
}
@@ -353,8 +354,8 @@ class CodeGenVM : public ExprFunctor<Instruction::Arg(const Expr&)> {
args.push_back(this->VisitExpr(call_node->args[i]));
}
int64_t vdevice_index = -1;
- if (auto* prim_value_node = call_node->args[4].as<PrimValueNode>()) {
- vdevice_index = prim_value_node->value.as<IntImmNode>()->value;
+ if (auto* prim_value_node = call_node->args[4].as<PrimExprNode>()) {
+ vdevice_index = ffi::GetRef<PrimExpr>(prim_value_node).as<IntImmNode>()->value;
}
auto vdevice = GetGlobalVDevice(ctx_mod_, vdevice_index);
diff --git a/src/relax/backend/vm/codegen_vm_tir.cc b/src/relax/backend/vm/codegen_vm_tir.cc
index 3e2ac365d4..a2852116fa 100644
--- a/src/relax/backend/vm/codegen_vm_tir.cc
+++ b/src/relax/backend/vm/codegen_vm_tir.cc
@@ -52,7 +52,7 @@ using vm::VMFuncInfo;
* \brief A class to generate VMTIR for Relax functions.
*
* \note Skip CallPacked with special attrs for now, as they can be
- * further simplified with PrimValue.
+ * further simplified with PrimExpr.
*/
class CodeGenVMTIR : public ExprFunctor<ffi::Optional<PrimExpr>(const Expr&)> {
public:
@@ -303,7 +303,9 @@ class CodeGenVMTIR : public ExprFunctor<ffi::Optional<PrimExpr>(const Expr&)> {
return ConstListGet(builder_->ConvertConstant(ffi::Shape(shape)).value());
}
- ffi::Optional<PrimExpr> VisitExpr_(const PrimValueNode* op) final { return op->value; }
+ ffi::Optional<PrimExpr> VisitExpr_(const PrimExprNode* op) final {
+ return ffi::GetRef<PrimExpr>(op);
+ }
ffi::Optional<PrimExpr> VisitExpr_(const StringImmNode* op) final {
return ConstListGet(builder_->ConvertConstant(op->value).value());
@@ -414,8 +416,8 @@ class CodeGenVMTIR : public ExprFunctor<ffi::Optional<PrimExpr>(const Expr&)> {
args.push_back(this->VisitExpr(call_node->args[i]).value());
}
int64_t vdevice_index = -1;
- if (auto* prim_value_node = call_node->args[4].as<PrimValueNode>()) {
- vdevice_index = prim_value_node->value.as<IntImmNode>()->value;
+ if (auto* prim_value_node = call_node->args[4].as<PrimExprNode>()) {
+ vdevice_index = ffi::GetRef<PrimExpr>(prim_value_node).as<IntImmNode>()->value;
}
auto vdevice = GetGlobalVDevice(ctx_mod_, vdevice_index);
diff --git a/src/relax/backend/vm/lower_runtime_builtin.cc b/src/relax/backend/vm/lower_runtime_builtin.cc
index f7dc473200..7a9a095a6f 100644
--- a/src/relax/backend/vm/lower_runtime_builtin.cc
+++ b/src/relax/backend/vm/lower_runtime_builtin.cc
@@ -36,7 +36,7 @@ namespace tvm {
namespace relax {
// This pass lowers most ops to VM specific builtins.
-// TODO(relax-team): revisit after PrimValue.
+// TODO(relax-team): revisit after PrimExpr.
class LowerRuntimeBuiltinMutator : public ExprMutator {
public:
using ExprMutator::VisitExpr_;
@@ -83,7 +83,7 @@ class LowerRuntimeBuiltinMutator : public ExprMutator {
}
Expr MakeMemAllocStorage(const Call& call) {
- PrimValue runtime_device_index = call->args[1].as_or_throw<PrimValue>();
+ PrimExpr runtime_device_index = call->args[1].as_or_throw<PrimExpr>();
StringImm storage_scope = call->args[2].as_or_throw<StringImm>();
DataTypeImm output_dtype = DataTypeImm((DLDataType{kDLUInt, 8, 1}));
return Call(vm_alloc_storage_op_,
@@ -91,7 +91,7 @@ class LowerRuntimeBuiltinMutator : public ExprMutator {
}
Expr MakeMemAllocTensor(const Call& call) {
- PrimValue offset = call->args[1].as_or_throw<PrimValue>();
+ PrimExpr offset = call->args[1].as_or_throw<PrimExpr>();
DataTypeImm dtype = call->args[3].as_or_throw<DataTypeImm>();
ffi::Array<Expr> call_args = {call->args[0], offset, call->args[2], dtype};
@@ -175,8 +175,8 @@ class LowerRuntimeBuiltinMutator : public ExprMutator {
int dev_type = vdev->target->GetTargetDeviceType();
int dev_id = vdev->vdevice_id;
StringImm storage_scope = StringImm(vdev->memory_scope);
- args.push_back(PrimValue::Int64(dev_type));
- args.push_back(PrimValue::Int64(dev_id));
+ args.push_back(IntImm::Int64(dev_type));
+ args.push_back(IntImm::Int64(dev_id));
args.push_back(storage_scope);
return Call(builtin_to_device_, args, call_node->attrs, {GetType(call_node)});
}
diff --git a/src/relax/backend/vm/vm_shape_lower.cc b/src/relax/backend/vm/vm_shape_lower.cc
index 80589f8f00..b92ce0c5bd 100644
--- a/src/relax/backend/vm/vm_shape_lower.cc
+++ b/src/relax/backend/vm/vm_shape_lower.cc
@@ -333,7 +333,7 @@ class VMShapeLowerMutator
Var var("shape_heap", heap_ty);
// set up the builtin func.
Call call(call_builtin_with_ctx_op_,
- {builtin_alloc_shape_heap_, Tuple({PrimValue(heap_size)})}, Attrs(), {heap_ty});
+ {builtin_alloc_shape_heap_, Tuple({PrimExpr(heap_size)})}, Attrs(), {heap_ty});
UpdateType(call, heap_ty);
return VarBinding(var, call);
} else {
@@ -357,35 +357,35 @@ class VMShapeLowerMutator
using runtime::vm::MakeShapeCode;
if (auto* int_expr = expr.as<IntImmNode>()) {
- return {PrimValue::Int64(static_cast<int>(MakeShapeCode::kUseImm)),
- PrimValue::Int64(int_expr->value)};
+ return {IntImm::Int64(static_cast<int>(MakeShapeCode::kUseImm)),
+ IntImm::Int64(int_expr->value)};
} else {
auto it = slot_map_.find(expr);
TVM_FFI_ICHECK(it != slot_map_.end());
auto* slot = it->second;
TVM_FFI_ICHECK(slot->value_computed)
<< "PrimExpr " << expr << " in function " << current_gvar_ << " has not been computed";
- return {PrimValue::Int64(static_cast<int>(MakeShapeCode::kLoadShape)),
- PrimValue::Int64(slot->index)};
+ return {IntImm::Int64(static_cast<int>(MakeShapeCode::kLoadShape)),
+ IntImm::Int64(slot->index)};
}
}
- Expr VisitExpr_(const PrimValueNode* op) final {
+ Expr VisitExpr_(const PrimExprNode* op) final {
using runtime::vm::MakeShapeCode;
+ PrimExpr value = ffi::GetRef<PrimExpr>(op);
// Constant shape can be preserved.
- bool is_const_value =
- op->value->IsInstance<IntImmNode>() || op->value->IsInstance<FloatImmNode>();
+ bool is_const_value = value->IsInstance<IntImmNode>() || value->IsInstance<FloatImmNode>();
if (is_const_value) {
return ffi::GetRef<Expr>(op);
}
ffi::Array<Expr> args = {shape_heap_};
- auto [code, value_or_index] = MakeSymbolicShapeArg(op->value);
+ auto [code, value_or_index] = MakeSymbolicShapeArg(value);
args.push_back(code);
args.push_back(value_or_index);
// make_shape(heap, n, c[0], r[0], c[1], r[1] ..., c[n], r[n])
- Call call(builtin_make_prim_value_, args, Attrs(), {op->ty.as_or_throw<Type>()});
+ Call call(builtin_make_prim_value_, args, Attrs(), {op->ty()});
return call;
}
@@ -399,8 +399,7 @@ class VMShapeLowerMutator
return ffi::GetRef<Expr>(op);
}
- ffi::Array<Expr> args = {shape_heap_,
- PrimValue::Int64(static_cast<int64_t>(op->values.size()))};
+ ffi::Array<Expr> args = {shape_heap_, IntImm::Int64(static_cast<int64_t>(op->values.size()))};
for (PrimExpr expr : op->values) {
auto [code, value_or_index] = MakeSymbolicShapeArg(expr);
args.push_back(code);
@@ -450,14 +449,14 @@ class VMShapeLowerMutator
using runtime::vm::MatchShapeCode;
if (auto* int_expr = expr.as<IntImmNode>()) {
- return {MatchShapeCode::kAssertEqualToImm, PrimValue::Int64(int_expr->value)};
+ return {MatchShapeCode::kAssertEqualToImm, IntImm::Int64(int_expr->value)};
}
auto it = slot_map_.find(expr);
TVM_FFI_ICHECK(it != slot_map_.end());
auto* slot = it->second;
if (slot->value_computed) {
- return {MatchShapeCode::kAssertEqualToLoad, PrimValue::Int64(slot->index)};
+ return {MatchShapeCode::kAssertEqualToLoad, IntImm::Int64(slot->index)};
}
// the value is not yet computed
@@ -468,11 +467,11 @@ class VMShapeLowerMutator
slot->value_computed = true;
ready_vars_.push_back(slot);
- return {MatchShapeCode::kStoreToHeap, PrimValue::Int64(slot->index)};
+ return {MatchShapeCode::kStoreToHeap, IntImm::Int64(slot->index)};
}
// otherwise, we skip and mark it as outstanding
- return {MatchShapeCode::kNoOp, PrimValue::Int64(0)};
+ return {MatchShapeCode::kNoOp, IntImm::Int64(0)};
}
//-------------------------------------------------------
@@ -510,14 +509,14 @@ class VMShapeLowerMutator
TVM_FFI_ICHECK_EQ(item.pattern.size(), 1);
} else {
match_op = builtin_match_shape_;
- args.push_back(PrimValue::Int64(item.pattern.size()));
+ args.push_back(IntImm::Int64(item.pattern.size()));
}
for (PrimExpr expr : item.pattern) {
auto [code, rvalue] = MakeMatchArgs(expr, require_value_computed);
all_nop = all_nop && code == MatchShapeCode::kNoOp;
any_nop = any_nop || code == MatchShapeCode::kNoOp;
- args.push_back(PrimValue::Int64(static_cast<int>(code)));
+ args.push_back(IntImm::Int64(static_cast<int>(code)));
args.push_back(rvalue);
}
if (any_nop) {
@@ -657,8 +656,8 @@ class VMShapeLowerMutator
// emit runtime check of shape
if (always_check || !IsBaseOf(ShapeType(op->ndim), GetType(value))) {
// check_shape_info(value, ndim, err_ctx)
- Call call(builtin_check_shape_info_,
- {value, PrimValue::Int64(op->ndim), GetErrContext(err_ctx)}, Attrs(), {void_ty_});
+ Call call(builtin_check_shape_info_, {value, IntImm::Int64(op->ndim), GetErrContext(err_ctx)},
+ Attrs(), {void_ty_});
builder_->Emit(call, "_");
}
if (op->values.defined()) {
@@ -682,10 +681,10 @@ class VMShapeLowerMutator
}
if (always_check || !IsBaseOf(TensorType(PrimType(op->dtype), op->ndim), GetType(value))) {
// check_tensor_info(value, ndim, dtype, err_ctx)
- Call call(builtin_check_tensor_info_,
- {value, PrimValue::Int64(op->ndim), DataTypeImm(op->dtype->dtype),
- GetErrContext(err_ctx)},
- Attrs(), {void_ty_});
+ Call call(
+ builtin_check_tensor_info_,
+ {value, IntImm::Int64(op->ndim), DataTypeImm(op->dtype->dtype), GetErrContext(err_ctx)},
+ Attrs(), {void_ty_});
builder_->Emit(call, "_");
}
@@ -716,8 +715,8 @@ class VMShapeLowerMutator
return TupleGetItem(value, index);
} else {
// call runtime tuple get item, and return a object.
- Call call(builtin_tuple_getitem_, {value, PrimValue::Int64(index)}, Attrs(), {object_ty_});
- UpdateType(call, AnyType());
+ Call call(builtin_tuple_getitem_, {value, IntImm::Int64(index)}, Attrs(), {object_ty_});
+ UpdateType(call, ObjectType());
return call;
}
}
@@ -731,10 +730,10 @@ class VMShapeLowerMutator
}
if (always_check || !value_tinfo) {
// check_tuple_info(value, tuple_size)
- Call call(builtin_check_tuple_info_,
- {value, PrimValue::Int64(static_cast<int64_t>(op->fields.size())),
- GetErrContext(err_ctx)},
- Attrs(), {void_ty_});
+ Call call(
+ builtin_check_tuple_info_,
+ {value, IntImm::Int64(static_cast<int64_t>(op->fields.size())), GetErrContext(err_ctx)},
+ Attrs(), {void_ty_});
builder_->Emit(call, "_");
}
// recursively visit each sub-field and run matching
diff --git a/src/relax/ir/block_builder.cc b/src/relax/ir/block_builder.cc
index 93b095bc6f..891e97ad57 100644
--- a/src/relax/ir/block_builder.cc
+++ b/src/relax/ir/block_builder.cc
@@ -575,7 +575,7 @@ class Normalizer : public BlockBuilderImpl, private ExprFunctor<Expr(const Expr&
RELAX_EXPR_NORMALIZER_LEAF(OpNode);
RELAX_EXPR_NORMALIZER_LEAF(ConstantNode);
RELAX_EXPR_NORMALIZER_LEAF(ShapeExprNode);
- RELAX_EXPR_NORMALIZER_LEAF(PrimValueNode);
+ RELAX_EXPR_NORMALIZER_LEAF(PrimExprNode);
RELAX_EXPR_NORMALIZER_LEAF(StringImmNode);
RELAX_EXPR_NORMALIZER_LEAF(DataTypeImmNode);
diff --git a/src/relax/ir/dataflow_expr_rewriter.cc b/src/relax/ir/dataflow_expr_rewriter.cc
index 10fd67de17..a0e36d75ea 100644
--- a/src/relax/ir/dataflow_expr_rewriter.cc
+++ b/src/relax/ir/dataflow_expr_rewriter.cc
@@ -735,8 +735,8 @@ PatternMatchingRewriter PatternMatchingRewriter::FromModule(IRModule mod) {
} else if (auto func = expr.as<ExternFuncNode>()) {
return ExternFuncPattern(func->global_symbol);
- } else if (auto prim = expr.as<PrimValueNode>()) {
- return TypePattern(WildcardPattern(), PrimType(prim->value.ty()));
+ } else if (auto prim = expr.as<PrimExprNode>()) {
+ return TypePattern(WildcardPattern(), prim->ty());
} else {
TVM_FFI_THROW(TypeError) << "Cannot convert Relax expression of type " << expr->GetTypeKey()
diff --git a/src/relax/ir/expr.cc b/src/relax/ir/expr.cc
index 2407943203..ffeccde003 100644
--- a/src/relax/ir/expr.cc
+++ b/src/relax/ir/expr.cc
@@ -37,7 +37,6 @@ TVM_FFI_STATIC_INIT_BLOCK() {
BindingNode::RegisterReflection();
DataflowVarNode::RegisterReflection();
ConstantNode::RegisterReflection();
- PrimValueNode::RegisterReflection();
StringImmNode::RegisterReflection();
DataTypeImmNode::RegisterReflection();
MatchCastNode::RegisterReflection();
@@ -364,24 +363,6 @@ TVM_FFI_STATIC_INIT_BLOCK() {
Span span = Span()) { return Constant(data, ty_annotation, span); });
}
-PrimValue::PrimValue(PrimExpr value, Span span) {
- ffi::ObjectPtr<PrimValueNode> n = ffi::make_object<PrimValueNode>();
- n->ty = PrimType(value.ty());
- n->value = std::move(value);
- n->span = std::move(span);
- data_ = std::move(n);
-}
-
-PrimValue PrimValue::Int64(int64_t value, Span span) {
- return PrimValue(IntImm::Int64(value), span);
-}
-
-TVM_FFI_STATIC_INIT_BLOCK() {
- namespace refl = tvm::ffi::reflection;
- refl::GlobalDef().def("relax.PrimValue",
- [](PrimExpr value, Span span) { return PrimValue(value, span); });
-}
-
StringImm::StringImm(ffi::String value, Span span) {
ffi::ObjectPtr<StringImmNode> n = ffi::make_object<StringImmNode>();
n->value = std::move(value);
diff --git a/src/relax/ir/expr_functor.cc b/src/relax/ir/expr_functor.cc
index 1f4972c73c..c25c739bee 100644
--- a/src/relax/ir/expr_functor.cc
+++ b/src/relax/ir/expr_functor.cc
@@ -54,7 +54,7 @@
RELAX_VISIT_BINDING_DISPATCH(IfNode); \
RELAX_VISIT_BINDING_DISPATCH(OpNode); \
RELAX_VISIT_BINDING_DISPATCH(TupleGetItemNode); \
- RELAX_VISIT_BINDING_DISPATCH(PrimValueNode); \
+ RELAX_PRIM_EXPR_NODE_DISPATCH_LIST(RELAX_VISIT_BINDING_DISPATCH); \
RELAX_VISIT_BINDING_DISPATCH(StringImmNode); \
RELAX_VISIT_BINDING_DISPATCH(DataTypeImmNode); \
return vtable; \
@@ -214,9 +214,9 @@ void ExprVisitor::VisitExpr_(const SeqExprNode* op) {
VisitExprDepTypeFieldIfNeeded(this, op->ty);
}
-void ExprVisitor::VisitExpr_(const PrimValueNode* op) {
- this->VisitPrimExpr(op->value);
- VisitExprDepTypeFieldIfNeeded(this, op->ty);
+void ExprVisitor::VisitExpr_(const PrimExprNode* op) {
+ this->VisitPrimExpr(ffi::GetRef<PrimExpr>(op));
+ VisitExprDepTypeFieldIfNeeded(this, op->ty());
this->VisitSpan(op->span);
}
@@ -243,7 +243,7 @@ RELAX_EXPR_VISITOR_VISIT_BINDING_IMPL(SeqExprNode);
RELAX_EXPR_VISITOR_VISIT_BINDING_IMPL(IfNode);
RELAX_EXPR_VISITOR_VISIT_BINDING_IMPL(OpNode);
RELAX_EXPR_VISITOR_VISIT_BINDING_IMPL(TupleGetItemNode);
-RELAX_EXPR_VISITOR_VISIT_BINDING_IMPL(PrimValueNode);
+RELAX_EXPR_VISITOR_VISIT_BINDING_IMPL(PrimExprNode);
RELAX_EXPR_VISITOR_VISIT_BINDING_IMPL(StringImmNode);
RELAX_EXPR_VISITOR_VISIT_BINDING_IMPL(DataTypeImmNode);
@@ -457,14 +457,15 @@ Expr ExprMutatorBase::VisitExpr_(const TupleGetItemNode* op) {
}
}
-Expr ExprMutatorBase::VisitExpr_(const PrimValueNode* op) {
- auto value = this->VisitPrimExpr(op->value);
- if (op->value.same_as(value)) {
+Expr ExprMutatorBase::VisitExpr_(const PrimExprNode* op) {
+ PrimExpr prim_expr = ffi::GetRef<PrimExpr>(op);
+ auto value = this->VisitPrimExpr(prim_expr);
+ if (prim_expr.same_as(value)) {
// type can be deterministically derived by value
// if value does not change, then type won't change.
return ffi::GetRef<Expr>(op);
}
- return PrimValue(value, op->span);
+ return value;
}
Expr ExprMutatorBase::VisitExpr_(const StringImmNode* op) { return ffi::GetRef<Expr>(op); }
@@ -646,7 +647,7 @@ RELAX_EXPR_MUTATOR_VISIT_BINDING_IMPL(SeqExprNode);
RELAX_EXPR_MUTATOR_VISIT_BINDING_IMPL(IfNode);
RELAX_EXPR_MUTATOR_VISIT_BINDING_IMPL(OpNode);
RELAX_EXPR_MUTATOR_VISIT_BINDING_IMPL(TupleGetItemNode);
-RELAX_EXPR_MUTATOR_VISIT_BINDING_IMPL(PrimValueNode);
+RELAX_EXPR_MUTATOR_VISIT_BINDING_IMPL(PrimExprNode);
RELAX_EXPR_MUTATOR_VISIT_BINDING_IMPL(StringImmNode);
RELAX_EXPR_MUTATOR_VISIT_BINDING_IMPL(DataTypeImmNode);
diff --git a/src/relax/ir/py_expr_functor.cc b/src/relax/ir/py_expr_functor.cc
index 09d0fd983d..006c5fdb2f 100644
--- a/src/relax/ir/py_expr_functor.cc
+++ b/src/relax/ir/py_expr_functor.cc
@@ -65,8 +65,8 @@ class PyExprVisitorNode : public ffi::Object, public ExprVisitor {
ffi::Function f_visit_op_{nullptr};
/*! \brief The packed function to the `VisitExpr_(const TupleGetItemNode* op)` function. */
ffi::Function f_visit_tuple_getitem_{nullptr};
- /*! \brief The packed function to the `VisitExpr_(const PrimValueNode* op)` function. */
- ffi::Function f_visit_prim_value_{nullptr};
+ /*! \brief The packed function to the `VisitExpr_(const PrimExprNode* op)` function. */
+ ffi::Function f_visit_prim_expr_{nullptr};
/*! \brief The packed function to the `VisitExpr_(const StringImmNode* op)` function. */
ffi::Function f_visit_string_imm_{nullptr};
/*! \brief The packed function to the `VisitExpr_(const DataTypeImmNode* op)` function. */
@@ -164,7 +164,7 @@ class PyExprVisitorNode : public ffi::Object, public ExprVisitor {
PY_EXPR_VISITOR_DISPATCH(IfNode, f_visit_if_);
PY_EXPR_VISITOR_DISPATCH(OpNode, f_visit_op_);
PY_EXPR_VISITOR_DISPATCH(TupleGetItemNode, f_visit_tuple_getitem_);
- PY_EXPR_VISITOR_DISPATCH(PrimValueNode, f_visit_prim_value_);
+ RELAX_PRIM_EXPR_NODE_DISPATCH_LIST(PY_EXPR_VISITOR_DISPATCH_PRIM_EXPR);
PY_EXPR_VISITOR_DISPATCH(StringImmNode, f_visit_string_imm_);
PY_EXPR_VISITOR_DISPATCH(DataTypeImmNode, f_visit_data_type_imm_);
vtable.Finalize();
@@ -197,7 +197,7 @@ class PyExprVisitor : public ffi::ObjectRef {
* \param f_visit_if_ The packed function of `VisitExpr_(const IfNode* op)`.
* \param f_visit_op_ The packed function of `VisitExpr_(const OpNode* op)`.
* \param f_visit_tuple_getitem_ The packed function of `VisitExpr_(const TupleGetItemNode* op)`.
- * \param f_visit_prim_value_ The packed function of `VisitExpr_(const PrimValueNode* op)`.
+ * \param f_visit_prim_expr_ The packed function of `VisitExpr_(const PrimExprNode* op)`.
* \param f_visit_string_imm_ The packed function of `VisitExpr_(const StringImmNode* op)`.
* \param f_visit_data_type_imm_ The packed function of `VisitExpr_(const DataTypeImmNode* op)`.
* \param f_visit_binding The packed function of `VisitBinding(const Binding& binding)`.
@@ -225,7 +225,7 @@ class PyExprVisitor : public ffi::ObjectRef {
ffi::Function f_visit_global_var_, ffi::Function f_visit_function_,
ffi::Function f_visit_call_, ffi::Function f_visit_seq_expr_, ffi::Function f_visit_if_,
ffi::Function f_visit_op_, ffi::Function f_visit_tuple_getitem_,
- ffi::Function f_visit_prim_value_, ffi::Function f_visit_string_imm_,
+ ffi::Function f_visit_prim_expr_, ffi::Function f_visit_string_imm_,
ffi::Function f_visit_data_type_imm_, ffi::Function f_visit_binding,
ffi::Function f_visit_var_binding_, ffi::Function f_visit_match_cast_,
ffi::Function f_visit_binding_block, ffi::Function f_visit_binding_block_,
@@ -251,7 +251,7 @@ class PyExprVisitor : public ffi::ObjectRef {
n->f_visit_if_ = f_visit_if_;
n->f_visit_op_ = f_visit_op_;
n->f_visit_tuple_getitem_ = f_visit_tuple_getitem_;
- n->f_visit_prim_value_ = f_visit_prim_value_;
+ n->f_visit_prim_expr_ = f_visit_prim_expr_;
n->f_visit_string_imm_ = f_visit_string_imm_;
n->f_visit_data_type_imm_ = f_visit_data_type_imm_;
n->f_visit_var_binding_ = f_visit_var_binding_;
@@ -303,8 +303,8 @@ class PyExprMutatorNode : public ffi::Object, public ExprMutator {
ffi::Function f_visit_op_{nullptr};
/*! \brief The packed function to the `VisitExpr_(const TupleGetItemNode* op)` function. */
ffi::Function f_visit_tuple_getitem_{nullptr};
- /*! \brief The packed function to the `VisitExpr_(const PrimValueNode* op)` function. */
- ffi::Function f_visit_prim_value_{nullptr};
+ /*! \brief The packed function to the `VisitExpr_(const PrimExprNode* op)` function. */
+ ffi::Function f_visit_prim_expr_{nullptr};
/*! \brief The packed function to the `VisitExpr_(const StringImmNode* op)` function. */
ffi::Function f_visit_string_imm_{nullptr};
/*! \brief The packed function to the `VisitExpr_(const DataTypeImmNode* op)` function. */
@@ -427,7 +427,7 @@ class PyExprMutatorNode : public ffi::Object, public ExprMutator {
PY_EXPR_MUTATOR_DISPATCH(IfNode, f_visit_if_);
PY_EXPR_MUTATOR_DISPATCH(OpNode, f_visit_op_);
PY_EXPR_MUTATOR_DISPATCH(TupleGetItemNode, f_visit_tuple_getitem_);
- PY_EXPR_MUTATOR_DISPATCH(PrimValueNode, f_visit_prim_value_);
+ RELAX_PRIM_EXPR_NODE_DISPATCH_LIST(PY_EXPR_MUTATOR_DISPATCH_PRIM_EXPR);
PY_EXPR_MUTATOR_DISPATCH(StringImmNode, f_visit_string_imm_);
PY_EXPR_MUTATOR_DISPATCH(DataTypeImmNode, f_visit_data_type_imm_);
vtable.Finalize();
@@ -451,7 +451,7 @@ class PyExprMutatorNode : public ffi::Object, public ExprMutator {
PY_EXPR_MUTATOR_VISIT_EXPR_POST_ORDER_DISPATCH(IfNode);
PY_EXPR_MUTATOR_VISIT_EXPR_POST_ORDER_DISPATCH(OpNode);
PY_EXPR_MUTATOR_VISIT_EXPR_POST_ORDER_DISPATCH(TupleGetItemNode);
- PY_EXPR_MUTATOR_VISIT_EXPR_POST_ORDER_DISPATCH(PrimValueNode);
+ RELAX_PRIM_EXPR_NODE_DISPATCH_LIST(PY_EXPR_MUTATOR_VISIT_EXPR_POST_ORDER_DISPATCH);
PY_EXPR_MUTATOR_VISIT_EXPR_POST_ORDER_DISPATCH(StringImmNode);
PY_EXPR_MUTATOR_VISIT_EXPR_POST_ORDER_DISPATCH(DataTypeImmNode);
post_order_vtable.Finalize();
@@ -484,7 +484,7 @@ class PyExprMutator : public ffi::ObjectRef {
* \param f_visit_if_ The packed function of `VisitExpr_(const IfNode* op)`.
* \param f_visit_op_ The packed function of `VisitExpr_(const OpNode* op)`.
* \param f_visit_tuple_getitem_ The packed function of `VisitExpr_(const TupleGetItemNode* op)`.
- * \param f_visit_prim_value_ The packed function of `VisitExpr_(const PrimValueNode* op)`.
+ * \param f_visit_prim_expr_ The packed function of `VisitExpr_(const PrimExprNode* op)`.
* \param f_visit_string_imm_ The packed function of `VisitExpr_(const StringImmNode* op)`.
* \param f_visit_data_type_imm_ The packed function of `VisitExpr_(const DataTypeImmNode* op)`.
* \param f_visit_binding The packed function of `VisitBinding(const Binding& binding)`.
@@ -512,7 +512,7 @@ class PyExprMutator : public ffi::ObjectRef {
ffi::Function f_visit_global_var_, ffi::Function f_visit_function_,
ffi::Function f_visit_call_, ffi::Function f_visit_seq_expr_, ffi::Function f_visit_if_,
ffi::Function f_visit_op_, ffi::Function f_visit_tuple_getitem_,
- ffi::Function f_visit_prim_value_, ffi::Function f_visit_string_imm_,
+ ffi::Function f_visit_prim_expr_, ffi::Function f_visit_string_imm_,
ffi::Function f_visit_data_type_imm_, ffi::Function f_visit_binding,
ffi::Function f_visit_var_binding_, ffi::Function f_visit_match_cast_,
ffi::Function f_visit_binding_block, ffi::Function f_visit_binding_block_,
@@ -535,7 +535,7 @@ class PyExprMutator : public ffi::ObjectRef {
n->f_visit_if_ = f_visit_if_;
n->f_visit_op_ = f_visit_op_;
n->f_visit_tuple_getitem_ = f_visit_tuple_getitem_;
- n->f_visit_prim_value_ = f_visit_prim_value_;
+ n->f_visit_prim_expr_ = f_visit_prim_expr_;
n->f_visit_string_imm_ = f_visit_string_imm_;
n->f_visit_data_type_imm_ = f_visit_data_type_imm_;
n->f_visit_binding = f_visit_binding;
diff --git a/src/relax/op/memory/view.cc b/src/relax/op/memory/view.cc
index 2e1410e55a..75cb135386 100644
--- a/src/relax/op/memory/view.cc
+++ b/src/relax/op/memory/view.cc
@@ -135,10 +135,10 @@ Type InferTypeView(const Call& call, const BlockBuilder& ctx) {
<< "Operator " << call->op
<< " expects the relative_byte_offset to be a 64-bit integer, but received "
<< arg_relative_byte_offset << ", which has type " << ty;
- if (const auto* prim_value = arg_relative_byte_offset.as<PrimValueNode>()) {
+ if (const auto* prim_value = arg_relative_byte_offset.as<PrimExprNode>()) {
// An offset of known value is applied. The known value may
// be dynamic.
- return prim_value->value;
+ return ffi::GetRef<PrimExpr>(prim_value);
} else {
// An offset of unknown value is applied.
return std::nullopt;
@@ -146,7 +146,7 @@ Type InferTypeView(const Call& call, const BlockBuilder& ctx) {
} else {
TVM_FFI_THROW(TypeError) << "Operator " << call->op
<< " expects the relative_byte_offset argument "
- << "to be a Relax PrimValue. "
+ << "to be a Relax PrimExpr. "
<< "However, expression " << call
<< " provides relative_byte_offset of " << arg_relative_byte_offset
<< ", which has type " << ty;
@@ -340,7 +340,7 @@ Expr LowerBuiltinView(const BlockBuilder& bb, const Call& call) {
}
if (HasVoidType(relative_byte_offset)) {
- relative_byte_offset = relax::PrimValue::Int64(0);
+ relative_byte_offset = IntImm::Int64(0);
}
TypeDeriveFunc infer_ty_env_func;
diff --git a/src/relax/op/op.cc b/src/relax/op/op.cc
index fc99d83958..e310e04d50 100644
--- a/src/relax/op/op.cc
+++ b/src/relax/op/op.cc
@@ -1215,8 +1215,8 @@ Type InferTypeAllocateTensor(const Call& call, const BlockBuilder& ctx) {
out_dtype = PrimType(dtype_imm->value);
}
int64_t vdevice_index = -1;
- if (auto* prim_value_node = call->args[2].as<PrimValueNode>()) {
- vdevice_index = prim_value_node->value.as<IntImmNode>()->value;
+ if (auto* prim_value_node = call->args[2].as<PrimExprNode>()) {
+ vdevice_index = ffi::GetRef<PrimExpr>(prim_value_node).as<IntImmNode>()->value;
}
auto vdevice = GetGlobalVDevice(ctx->GetContextIRModule(), vdevice_index);
@@ -1230,7 +1230,7 @@ TVM_REGISTER_OP("relax.builtin.alloc_tensor")
.set_num_inputs(4)
.add_argument("shape", "Expr", "The shape of the tensor to allocate.")
.add_argument("dtype", "DataTypeImm", "The dtype of the tensor to allocate.")
- .add_argument("runtime_device_index", "PrimValue",
+ .add_argument("runtime_device_index", "PrimExpr",
"The device index indicating on which device the tensor is to be "
"allocated at runtime. Index -1 is reserved for the host device.")
.add_argument("storage_scope", "StringImm",
@@ -1240,7 +1240,7 @@ TVM_REGISTER_OP("relax.builtin.alloc_tensor")
.set_attr<bool>("FPurity", true)
.set_attr<bool>("TAllocator", true);
-Expr MakeAllocTensor(Expr shape, DataTypeImm dtype, PrimValue runtime_device_index,
+Expr MakeAllocTensor(Expr shape, DataTypeImm dtype, PrimExpr runtime_device_index,
StringImm storage_scope) {
static const Op& op = Op::Get("relax.builtin.alloc_tensor");
return Call(op, {shape, dtype, runtime_device_index, storage_scope}, Attrs(), {});
@@ -1257,7 +1257,7 @@ TVM_REGISTER_OP("relax.memory.alloc_storage")
.set_num_inputs(4)
.add_argument("total_space", "Expr", "The total space of the storage to allocate.")
.add_argument(
- "virtual_device_index", "PrimValue",
+ "virtual_device_index", "PrimExpr",
"The virtual device index indicating on which device the storage is to be allocated, "
"Index -1 is reserved for the host device.")
.add_argument("storage_scope", "StringImm",
@@ -1268,7 +1268,7 @@ TVM_REGISTER_OP("relax.memory.alloc_storage")
.set_attr<bool>("FPurity", true)
.set_attr<bool>("TAllocator", true);
-Expr MakeAllocStorage(Expr size, PrimValue virtual_device_index, StringImm storage_scope,
+Expr MakeAllocStorage(Expr size, PrimExpr virtual_device_index, StringImm storage_scope,
DataTypeImm dtype) {
static const Op& op = Op::Get("relax.memory.alloc_storage");
return Call(op, {size, virtual_device_index, storage_scope, dtype}, Attrs(), {});
@@ -1292,8 +1292,8 @@ Type InferTypeMemAllocTensor(const Call& call, const BlockBuilder& ctx) {
if (call->args.size() == 5) {
int64_t vdevice_index = -1;
- if (auto* prim_value_node = call->args[4].as<PrimValueNode>()) {
- vdevice_index = prim_value_node->value.as<IntImmNode>()->value;
+ if (auto* prim_value_node = call->args[4].as<PrimExprNode>()) {
+ vdevice_index = ffi::GetRef<PrimExpr>(prim_value_node).as<IntImmNode>()->value;
}
auto vdevice = GetGlobalVDevice(ctx->GetContextIRModule(), vdevice_index);
if (vdevice.defined()) {
@@ -1307,10 +1307,10 @@ Type InferTypeMemAllocTensor(const Call& call, const BlockBuilder& ctx) {
TVM_REGISTER_OP("relax.memory.alloc_tensor")
.set_num_inputs(5)
.add_argument("storage", "Expr", "The storage to allocate the tensor to.")
- .add_argument("offset", "PrimValue", "Storage offset to allocate the tensor.")
+ .add_argument("offset", "PrimExpr", "Storage offset to allocate the tensor.")
.add_argument("shape", "Expr", "The shape of the tensor to allocate.")
.add_argument("dtype", "DataTypeImm", "The dtype of the tensor to allocate.")
- .add_argument("runtime_device_index", "PrimValue",
+ .add_argument("runtime_device_index", "PrimExpr",
"The device index indicating on which device the tensor is to be "
"allocated at runtime. Index -1 is reserved for the host device.")
.set_attr<FInferType>("FInferType", InferTypeMemAllocTensor)
@@ -1318,8 +1318,8 @@ TVM_REGISTER_OP("relax.memory.alloc_tensor")
.set_attr<bool>("FPurity", true)
.set_attr<bool>("TAllocator", true);
-Expr MakeMemAllocTensor(Expr storage, PrimValue offset, Expr shape, DataTypeImm dtype,
- PrimValue virtual_device_index) {
+Expr MakeMemAllocTensor(Expr storage, PrimExpr offset, Expr shape, DataTypeImm dtype,
+ PrimExpr virtual_device_index) {
static const Op& op = Op::Get("relax.memory.alloc_tensor");
return Call(op, {storage, offset, shape, dtype, virtual_device_index}, Attrs(), {});
}
@@ -1329,13 +1329,13 @@ TVM_FFI_STATIC_INIT_BLOCK() {
refl::GlobalDef().def_packed(
"relax.op.memory.alloc_tensor", [](ffi::PackedArgs args, ffi::Any* ret) {
if (args.size() == 5) {
- *ret = MakeMemAllocTensor(args[0].cast<Expr>(), args[1].cast<PrimValue>(),
+ *ret = MakeMemAllocTensor(args[0].cast<Expr>(), args[1].cast<PrimExpr>(),
args[2].cast<Expr>(), args[3].cast<DataTypeImm>(),
- args[4].cast<PrimValue>());
+ args[4].cast<PrimExpr>());
} else {
- *ret = MakeMemAllocTensor(args[0].cast<Expr>(), args[1].cast<PrimValue>(),
+ *ret = MakeMemAllocTensor(args[0].cast<Expr>(), args[1].cast<PrimExpr>(),
args[2].cast<Expr>(), args[3].cast<DataTypeImm>(),
- PrimValue::Int64(0));
+ IntImm::Int64(0));
}
});
}
@@ -1384,7 +1384,7 @@ TVM_REGISTER_OP("relax.vm.alloc_storage")
.set_num_inputs(4)
.add_argument("size", "Expr", "The size of the storage to allocate.")
.add_argument("dtype", "DataTypeImm", "The dtype of the tensor to allocate.")
- .add_argument("runtime_device_index", "PrimValue",
+ .add_argument("runtime_device_index", "PrimExpr",
"The device index indicating on which device the tensor is "
"to be allocated at runtime.")
.add_argument("storage_scope", "StringImm",
@@ -1394,7 +1394,7 @@ TVM_REGISTER_OP("relax.vm.alloc_storage")
.set_attr<bool>("FPurity", true)
.set_attr<bool>("TAllocator", true);
-Expr MakeVMAllocStorage(Expr size, PrimValue runtime_device_index, DataTypeImm dtype,
+Expr MakeVMAllocStorage(Expr size, PrimExpr runtime_device_index, DataTypeImm dtype,
StringImm storage_scope) {
static const Op& op = Op::Get("relax.vm.alloc_storage");
return Call(op, {size, runtime_device_index, dtype, storage_scope}, Attrs(), {});
@@ -1414,8 +1414,8 @@ Type InferTypeVMAllocTensor(const Call& call, const BlockBuilder& ctx) {
out_dtype = PrimType(dtype_imm->value);
}
int64_t vdevice_index = -1;
- if (auto* prim_value_node = call->args[4].as<PrimValueNode>()) {
- vdevice_index = prim_value_node->value.as<IntImmNode>()->value;
+ if (auto* prim_value_node = call->args[4].as<PrimExprNode>()) {
+ vdevice_index = ffi::GetRef<PrimExpr>(prim_value_node).as<IntImmNode>()->value;
}
auto vdevice = GetGlobalVDevice(ctx->GetContextIRModule(), vdevice_index);
@@ -1434,10 +1434,10 @@ Type InferTypeVMAllocTensor(const Call& call, const BlockBuilder& ctx) {
TVM_REGISTER_OP("relax.vm.alloc_tensor")
.set_num_inputs(5)
.add_argument("storage", "Expr", "The storage to allocate the tensor to.")
- .add_argument("offset", "PrimValue", "Storage offset to allocate the tensor.")
+ .add_argument("offset", "PrimExpr", "Storage offset to allocate the tensor.")
.add_argument("shape", "Expr", "The shape of the tensor to allocate.")
.add_argument("dtype", "DataTypeImm", "The dtype of the tensor to allocate.")
- .add_argument("runtime_device_index", "PrimValue",
+ .add_argument("runtime_device_index", "PrimExpr",
"The device index indicating on which device the tensor is "
"to be allocated at runtime.")
.set_attr<FInferType>("FInferType", InferTypeVMAllocTensor)
@@ -1445,8 +1445,8 @@ TVM_REGISTER_OP("relax.vm.alloc_tensor")
.set_attr<bool>("FPurity", true)
.set_attr<bool>("TAllocator", true);
-Expr MakeVMAllocTensor(Expr storage, PrimValue offset, Expr shape, DataTypeImm dtype,
- PrimValue runtime_device_index) {
+Expr MakeVMAllocTensor(Expr storage, PrimExpr offset, Expr shape, DataTypeImm dtype,
+ PrimExpr runtime_device_index) {
static const Op& op = Op::Get("relax.vm.alloc_tensor");
return Call(op, {storage, offset, shape, dtype, runtime_device_index}, Attrs(), {});
}
@@ -1455,13 +1455,11 @@ TVM_FFI_STATIC_INIT_BLOCK() {
namespace refl = tvm::ffi::reflection;
refl::GlobalDef().def_packed("relax.op.vm.alloc_tensor", [](ffi::PackedArgs args, ffi::Any* ret) {
if (args.size() == 5) {
- *ret =
- MakeVMAllocTensor(args[0].cast<Expr>(), args[1].cast<PrimValue>(), args[2].cast<Expr>(),
- args[3].cast<DataTypeImm>(), args[4].cast<PrimValue>());
+ *ret = MakeVMAllocTensor(args[0].cast<Expr>(), args[1].cast<PrimExpr>(), args[2].cast<Expr>(),
+ args[3].cast<DataTypeImm>(), args[4].cast<PrimExpr>());
} else {
- *ret =
- MakeVMAllocTensor(args[0].cast<Expr>(), args[1].cast<PrimValue>(), args[2].cast<Expr>(),
- args[3].cast<DataTypeImm>(), PrimValue::Int64(0));
+ *ret = MakeVMAllocTensor(args[0].cast<Expr>(), args[1].cast<PrimExpr>(), args[2].cast<Expr>(),
+ args[3].cast<DataTypeImm>(), IntImm::Int64(0));
}
});
}
diff --git a/src/relax/op/op_common.h b/src/relax/op/op_common.h
index 5975c51c57..9a3932c181 100644
--- a/src/relax/op/op_common.h
+++ b/src/relax/op/op_common.h
@@ -598,12 +598,12 @@ inline ffi::Optional<ShapeExpr> CheckNdimPerLayoutAndGetShape(const Call& call,
return std::nullopt;
}
-Expr MakeVMAllocStorage(Expr size, PrimValue runtime_device_index, DataTypeImm dtype,
+Expr MakeVMAllocStorage(Expr size, PrimExpr runtime_device_index, DataTypeImm dtype,
StringImm storage_scope = StringImm("global"));
-Expr MakeVMAllocTensor(Expr storage, PrimValue offset, Expr shape, DataTypeImm dtype,
- PrimValue runtime_device_index);
+Expr MakeVMAllocTensor(Expr storage, PrimExpr offset, Expr shape, DataTypeImm dtype,
+ PrimExpr runtime_device_index);
-Expr MakeAllocTensor(Expr shape, DataTypeImm dtype, PrimValue runtime_device_index,
+Expr MakeAllocTensor(Expr shape, DataTypeImm dtype, PrimExpr runtime_device_index,
StringImm storage_scope = StringImm("global"));
/**
diff --git a/src/relax/op/tensor/create.cc b/src/relax/op/tensor/create.cc
index fbe3a0b0c5..81f07bf50e 100644
--- a/src/relax/op/tensor/create.cc
+++ b/src/relax/op/tensor/create.cc
@@ -252,14 +252,14 @@ TVM_REGISTER_OP("relax.zeros_like")
.set_attr<bool>("FPurity", true);
/* relax.eye & relax.eye_like */
-Expr eye(PrimValue n, PrimValue m, PrimValue k, DLDataType dtype) {
+Expr eye(PrimExpr n, PrimExpr m, PrimExpr k, DLDataType dtype) {
ffi::ObjectPtr<InitAttrs> attrs = ffi::make_object<InitAttrs>();
attrs->dtype = dtype;
static const Op& op = Op::Get("relax.eye");
return Call(op, {std::move(n), std::move(m), std::move(k)}, Attrs(attrs), {});
}
-Expr eye_like(Expr x, PrimValue k, ffi::Optional<DLDataType> dtype) {
+Expr eye_like(Expr x, PrimExpr k, ffi::Optional<DLDataType> dtype) {
ffi::ObjectPtr<InitAttrs> attrs = ffi::make_object<InitAttrs>();
attrs->dtype = dtype.value_or((DLDataType{kDLOpaqueHandle, 0, 0}));
static const Op& op = Op::Get("relax.eye_like");
@@ -278,11 +278,11 @@ Type InferTypeEye(const Call& call, const BlockBuilder& ctx) {
}
auto get_prim_value = [&ctx](const Expr& expr, std::string key) {
- if (!expr->IsInstance<PrimValueNode>()) {
+ if (!expr->IsInstance<PrimExprNode>()) {
TVM_FFI_VISIT_THROW(TypeError, expr)
- << "Eye expects the `" << key << "` to be a PrimValue, but got " << expr->GetTypeKey();
+ << "Eye expects the `" << key << "` to be a PrimExpr, but got " << expr->GetTypeKey();
}
- return expr.as<PrimValueNode>()->value;
+ return expr.as_or_throw<PrimExpr>();
};
PrimExpr n = get_prim_value(call->args[0], "n");
@@ -321,9 +321,9 @@ Type InferTypeEyeLike(const Call& call, const BlockBuilder& ctx) {
TVM_REGISTER_OP("relax.eye")
.set_attrs_type<InitAttrs>()
.set_num_inputs(3)
- .add_argument("n", "PrimValue", "Number of rows in the output.")
- .add_argument("m", "PrimValue", "Number of columns in the output.")
- .add_argument("k", "PrimValue", "Index of the diagonal.")
+ .add_argument("n", "PrimExpr", "Number of rows in the output.")
+ .add_argument("m", "PrimExpr", "Number of columns in the output.")
+ .add_argument("k", "PrimExpr", "Index of the diagonal.")
.set_attr<FInferType>("FInferType", InferTypeEye)
.set_attr<TMixedPrecisionPolicy>("TMixedPrecisionPolicy", MixedPrecisionPolicyKind::kFollow)
.set_attr<bool>("FPurity", true);
@@ -332,12 +332,12 @@ TVM_REGISTER_OP("relax.eye_like")
.set_attrs_type<InitAttrs>()
.set_num_inputs(2)
.add_argument("x", "Tensor", "The input tensor.")
- .add_argument("k", "PrimValue", "Index of the diagonal.")
+ .add_argument("k", "PrimExpr", "Index of the diagonal.")
.set_attr<FInferType>("FInferType", InferTypeEyeLike)
.set_attr<bool>("FPurity", true);
/* relax.arange */
-Expr arange(PrimValue start, PrimValue stop, PrimValue step, DLDataType dtype) {
+Expr arange(PrimExpr start, PrimExpr stop, PrimExpr step, DLDataType dtype) {
ffi::ObjectPtr<InitAttrs> attrs = ffi::make_object<InitAttrs>();
attrs->dtype = dtype;
static const Op& op = Op::Get("relax.arange");
@@ -357,11 +357,11 @@ Type InferTypeArange(const Call& call, const BlockBuilder& ctx) {
}
// TODO(Siyuan): Support indirect prim_values
auto get_prim_value = [&ctx](const Expr& expr, std::string key) {
- if (!expr->IsInstance<PrimValueNode>()) {
+ if (!expr->IsInstance<PrimExprNode>()) {
TVM_FFI_VISIT_THROW(TypeError, expr)
- << "Arange expects the `" << key << "` to be a PrimValue, but got " << expr->GetTypeKey();
+ << "Arange expects the `" << key << "` to be a PrimExpr, but got " << expr->GetTypeKey();
}
- return expr.as<PrimValueNode>()->value;
+ return expr.as_or_throw<PrimExpr>();
};
PrimExpr start = get_prim_value(call->args[0], "start");
PrimExpr end = get_prim_value(call->args[1], "end");
@@ -383,15 +383,15 @@ Type InferTypeArange(const Call& call, const BlockBuilder& ctx) {
TVM_REGISTER_OP("relax.arange")
.set_attrs_type<InitAttrs>()
.set_num_inputs(3)
- .add_argument("start", "PrimValue", "The starting value for the set of points.")
- .add_argument("end", "PrimValue", "The ending value for the set of points.")
- .add_argument("step", "PrimValue", "The gap between each pair of adjacent points.")
+ .add_argument("start", "PrimExpr", "The starting value for the set of points.")
+ .add_argument("end", "PrimExpr", "The ending value for the set of points.")
+ .add_argument("step", "PrimExpr", "The gap between each pair of adjacent points.")
.set_attr<FInferType>("FInferType", InferTypeArange)
.set_attr<TMixedPrecisionPolicy>("TMixedPrecisionPolicy", MixedPrecisionPolicyKind::kFollow)
.set_attr<bool>("FPurity", true);
/* relax.hamming_window */
-Expr hamming_window(PrimValue window_size, PrimValue periodic, PrimValue alpha, PrimValue beta,
+Expr hamming_window(PrimExpr window_size, PrimExpr periodic, PrimExpr alpha, PrimExpr beta,
DLDataType dtype) {
ffi::ObjectPtr<InitAttrs> attrs = ffi::make_object<InitAttrs>();
attrs->dtype = dtype;
@@ -412,11 +412,11 @@ Type InferTypeHammingWindow(const Call& call, const BlockBuilder& ctx) {
<< "Hamming Window expects the datatype to be float but got " << dtype;
}
auto get_prim_value = [&ctx](const Expr& expr, std::string key) {
- if (!expr->IsInstance<PrimValueNode>()) {
+ if (!expr->IsInstance<PrimExprNode>()) {
TVM_FFI_VISIT_THROW(TypeError, expr) << "Hamming_window expects the `" << key
- << "` to be a PrimValue, but got " << expr->GetTypeKey();
+ << "` to be a PrimExpr, but got " << expr->GetTypeKey();
}
- return expr.as<PrimValueNode>()->value;
+ return expr.as_or_throw<PrimExpr>();
};
PrimExpr window_size = get_prim_value(call->args[0], "window_size");
@@ -433,12 +433,12 @@ Type InferTypeHammingWindow(const Call& call, const BlockBuilder& ctx) {
TVM_REGISTER_OP("relax.hamming_window")
.set_attrs_type<InitAttrs>()
.set_num_inputs(4)
- .add_argument("window_size", "PrimValue", "The size of the window")
- .add_argument("periodic", "PrimValue",
+ .add_argument("window_size", "PrimExpr", "The size of the window")
+ .add_argument("periodic", "PrimExpr",
"If True, returns a window to be used as periodic function. If False, return a "
"symmetric window")
- .add_argument("alpha", "PrimValue", "The coefficient alpha")
- .add_argument("beta", "PrimValue", "The coefficient beta")
+ .add_argument("alpha", "PrimExpr", "The coefficient alpha")
+ .add_argument("beta", "PrimExpr", "The coefficient beta")
.set_attr<FInferType>("FInferType", InferTypeHammingWindow)
.set_attr<TMixedPrecisionPolicy>("TMixedPrecisionPolicy", MixedPrecisionPolicyKind::kFollow)
.set_attr<bool>("FPurity", true);
@@ -450,14 +450,14 @@ Expr tril(Expr x, Expr k) {
return Call(op, {x, k});
}
-Expr tril(Expr x, int k) { return tril(x, relax::PrimValue::Int64(k)); }
+Expr tril(Expr x, int k) { return tril(x, IntImm::Int64(k)); }
Expr triu(Expr x, Expr k) {
static const Op& op = Op::Get("relax.triu");
return Call(op, {x, k});
}
-Expr triu(Expr x, int k) { return triu(x, relax::PrimValue::Int64(k)); }
+Expr triu(Expr x, int k) { return triu(x, IntImm::Int64(k)); }
TVM_FFI_STATIC_INIT_BLOCK() {
namespace refl = tvm::ffi::reflection;
@@ -481,14 +481,14 @@ Type InferTypeTrilTriu(const Call& call, const BlockBuilder& ctx) {
TVM_REGISTER_OP("relax.tril")
.set_num_inputs(2)
.add_argument("x", "Tensor", "The input tensor.")
- .add_argument("k", "PrimValue", "The offset of the diagonal.")
+ .add_argument("k", "PrimExpr", "The offset of the diagonal.")
.set_attr<FInferType>("FInferType", InferTypeTrilTriu)
.set_attr<bool>("FPurity", true);
TVM_REGISTER_OP("relax.triu")
.set_num_inputs(2)
.add_argument("x", "Tensor", "The input tensor.")
- .add_argument("k", "PrimValue", "The offset of the diagonal.")
+ .add_argument("k", "PrimExpr", "The offset of the diagonal.")
.set_attr<FInferType>("FInferType", InferTypeTrilTriu)
.set_attr<bool>("FPurity", true);
diff --git a/src/relax/op/tensor/create.h b/src/relax/op/tensor/create.h
index 497a535a4d..19b7f221ed 100644
--- a/src/relax/op/tensor/create.h
+++ b/src/relax/op/tensor/create.h
@@ -102,7 +102,7 @@ Expr zeros_like(Expr x, ffi::Optional<DLDataType> dtype);
* \param dtype The data type of the created tensor.
* \return The result tensor.
*/
-Expr eye(PrimValue n, PrimValue m, PrimValue k, DLDataType dtype);
+Expr eye(PrimExpr n, PrimExpr m, PrimExpr k, DLDataType dtype);
/*!
* \brief Construct a tensor with ones on the diagonal and zeros elsewhere,
@@ -115,10 +115,10 @@ Expr eye(PrimValue n, PrimValue m, PrimValue k, DLDataType dtype);
* void, the input tensor's dtype will be used.
* \return The result tensor.
*/
-Expr eye_like(Expr x, PrimValue k, ffi::Optional<DLDataType> dtype);
+Expr eye_like(Expr x, PrimExpr k, ffi::Optional<DLDataType> dtype);
/*! \brief Construct a tensor with evenly spaced elements. */
-Expr arange(PrimValue start, PrimValue stop, PrimValue step, DLDataType dtype);
+Expr arange(PrimExpr start, PrimExpr stop, PrimExpr step, DLDataType dtype);
/*!
* \brief Hamming window function.
@@ -130,7 +130,7 @@ Expr arange(PrimValue start, PrimValue stop, PrimValue step, DLDataType dtype);
* \param dtype The data type of the created tensor.
* \return The result tensor.
*/
-Expr hamming_window(PrimValue window_size, PrimValue periodic, PrimValue alpha, PrimValue beta,
+Expr hamming_window(PrimExpr window_size, PrimExpr periodic, PrimExpr alpha, PrimExpr beta,
DLDataType dtype);
/*! \brief Return the lower triangular part of a matrix or a batch of matrices. */
diff --git a/src/relax/op/tensor/index.cc b/src/relax/op/tensor/index.cc
index cc696809a7..d5794b54fa 100644
--- a/src/relax/op/tensor/index.cc
+++ b/src/relax/op/tensor/index.cc
@@ -64,7 +64,7 @@ Type InferTypeTake(const Call& call, const BlockBuilder& ctx) {
CheckNumArguments(call, ctx);
TensorType data_ty = GetInputTensorType(call, 0, ctx);
- // Type inference when the index is a PrimValue is equivalent
+ // Type inference when the index is a PrimExpr is equivalent
// to that of a scalar (0-d) tensor.
TensorType indices_ty = [&]() {
auto arg = call->args[1];
@@ -188,7 +188,7 @@ TVM_FFI_STATIC_INIT_BLOCK() {
* A `relax::Tuple` may be provided to an operator as an in-line
* expression, as a variable bound to known tuple within the current
* function, as a function argument, etc. This overload validates that
- * the Type could contain a tuple of `PrimValue` elements. Without a
+ * the Type could contain a tuple of `PrimExpr` elements. Without a
* concrete tuple expression, the values are not statically known.
*
* If the Type cannot contain a tuple of the type specified,
@@ -205,7 +205,7 @@ TVM_FFI_STATIC_INIT_BLOCK() {
*/
template <typename PrimType = PrimExpr,
typename = std::enable_if_t<std::is_base_of_v<PrimExpr, PrimType>>>
-ffi::Optional<ffi::Array<PrimType>> UnpackTupleOfPrimValue(ffi::Optional<Type> ty) {
+ffi::Optional<ffi::Array<PrimType>> UnpackTupleOfPrimExpr(ffi::Optional<Type> ty) {
if (!ty) return std::nullopt;
// An AnyType may contain a tuple of the desired type, but
@@ -239,7 +239,7 @@ ffi::Optional<ffi::Array<PrimType>> UnpackTupleOfPrimValue(ffi::Optional<Type> t
* A `relax::Tuple` may be provided to an operator as an in-line
* expression, as a variable bound to known tuple within the current
* function, as a function argument, etc. This utility extracts
- * `PrimValue` contents only when the concrete tuple expression is
+ * `PrimExpr` contents only when the concrete tuple expression is
* available.
*
* If the Type cannot contain a tuple of the type specified,
@@ -256,7 +256,7 @@ ffi::Optional<ffi::Array<PrimType>> UnpackTupleOfPrimValue(ffi::Optional<Type> t
*/
template <typename PrimType = PrimExpr,
typename = std::enable_if_t<std::is_base_of_v<PrimExpr, PrimType>>>
-ffi::Optional<ffi::Array<PrimType>> UnpackTupleOfPrimValue(ffi::Optional<Expr> expr) {
+ffi::Optional<ffi::Array<PrimType>> UnpackTupleOfPrimExpr(ffi::Optional<Expr> expr) {
if (!expr) return std::nullopt;
const Expr& value = expr.value();
@@ -264,22 +264,23 @@ ffi::Optional<ffi::Array<PrimType>> UnpackTupleOfPrimValue(ffi::Optional<Expr> e
ffi::Array<PrimType> output;
for (size_t i = 0; i < tuple->fields.size(); i++) {
const Expr& field = tuple->fields[i];
- auto prim_value = field.as<PrimValueNode>();
+ auto prim_value = field.as<PrimExprNode>();
TVM_FFI_CHECK(prim_value, TypeError)
<< "The expression " << value << " cannot contain a tuple whose elements are "
<< PrimType::ContainerType::_type_key << ", because element " << i << " is " << field;
- TVM_FFI_CHECK(prim_value->value.template as<typename PrimType::ContainerType>(), TypeError)
+ PrimExpr prim_expr = ffi::GetRef<PrimExpr>(prim_value);
+ TVM_FFI_CHECK(prim_expr.template as<typename PrimType::ContainerType>(), TypeError)
<< "The expression " << value << " cannot contain a tuple whose elements are "
<< PrimType::ContainerType::_type_key << ", because element " << i << " has value "
- << prim_value->value;
+ << prim_expr;
- output.push_back(prim_value->value.template as_or_throw<PrimType>());
+ output.push_back(prim_expr.template as_or_throw<PrimType>());
}
return output;
}
- return UnpackTupleOfPrimValue<PrimType>(GetType(value));
+ return UnpackTupleOfPrimExpr<PrimType>(GetType(value));
}
Type InferTypeStridedSlice(const Call& call, const BlockBuilder& ctx) {
@@ -336,7 +337,7 @@ Type InferTypeStridedSlice(const Call& call, const BlockBuilder& ctx) {
TVM_FFI_ICHECK(is_base_of_tuple_of_int64(ty))
<< "Operator " << call->op << " requires the " << name
- << " argument to be a tuple of int64 PrimValues. "
+ << " argument to be a tuple of int64 PrimExpr values. "
<< "However, in expression " << call << ", the " << name << " argument " << expr
<< " has type " << ty;
};
@@ -362,11 +363,11 @@ Type InferTypeStridedSlice(const Call& call, const BlockBuilder& ctx) {
if (!data_ty) return std::nullopt;
if (!data_ty->shape) return std::nullopt;
- auto opt_axes_tuple = UnpackTupleOfPrimValue<IntImm>(axes);
+ auto opt_axes_tuple = UnpackTupleOfPrimExpr<IntImm>(axes);
if (!opt_axes_tuple) return std::nullopt;
auto axes_tuple = opt_axes_tuple.value();
- auto opt_begin_tuple = UnpackTupleOfPrimValue(begin);
+ auto opt_begin_tuple = UnpackTupleOfPrimExpr(begin);
if (!opt_begin_tuple) return std::nullopt;
auto begin_tuple = opt_begin_tuple.value();
@@ -376,7 +377,7 @@ Type InferTypeStridedSlice(const Call& call, const BlockBuilder& ctx) {
<< "However, there are " << axes_tuple.size() << " axes specified (" << axes_tuple
<< ") and " << begin_tuple.size() << " 'begin' indices specified (" << begin_tuple << ")";
- auto opt_end_tuple = UnpackTupleOfPrimValue(end);
+ auto opt_end_tuple = UnpackTupleOfPrimExpr(end);
if (!opt_end_tuple) return std::nullopt;
auto end_tuple = opt_end_tuple.value();
@@ -388,7 +389,7 @@ Type InferTypeStridedSlice(const Call& call, const BlockBuilder& ctx) {
ffi::Array<PrimExpr> strides_tuple;
if (strides.defined()) {
- auto opt_strides_tuple = UnpackTupleOfPrimValue(strides);
+ auto opt_strides_tuple = UnpackTupleOfPrimExpr(strides);
if (!opt_strides_tuple) return std::nullopt;
strides_tuple = opt_strides_tuple.value();
@@ -467,7 +468,7 @@ InferLayoutOutput InferLayoutStridedSlice(
existing_layout = LayoutDecision(InitialLayout(tensor_ty->ndim));
}
- auto opt_axes_tuple = UnpackTupleOfPrimValue<IntImm>(call->args[1]);
+ auto opt_axes_tuple = UnpackTupleOfPrimExpr<IntImm>(call->args[1]);
TVM_FFI_ICHECK(opt_axes_tuple) << "Layout inference of " << call->op
<< " requires slices to be along static axes. "
<< "However, expression " << call
@@ -477,7 +478,7 @@ InferLayoutOutput InferLayoutStridedSlice(
ffi::Array<Expr> new_axes;
for (const auto& axis : axes_tuple) {
int new_axis = FindAxis(existing_layout->layout, axis->value);
- new_axes.push_back(relax::PrimValue::Int64(new_axis));
+ new_axes.push_back(IntImm::Int64(new_axis));
}
return InferLayoutOutput({existing_layout}, {existing_layout}, call->attrs,
@@ -558,7 +559,7 @@ Type InferTypeDynStridedSlice(const Call& call, const BlockBuilder& ctx) {
// The output shape will depend on the runtime value in begin/end/strides tensors.
// TODO(tvm-team): Currently, it is unable to express partially-static shape. Revisit when
- // PrimValue lands.
+ // PrimExpr lands.
return TensorType(data_ty->dtype, n_axis, data_ty->vdevice);
}
diff --git a/src/relax/op/tensor/inspect.cc b/src/relax/op/tensor/inspect.cc
index 97955eb624..e9d1f854f1 100644
--- a/src/relax/op/tensor/inspect.cc
+++ b/src/relax/op/tensor/inspect.cc
@@ -69,8 +69,8 @@ std::tuple<TensorType, ffi::Optional<int64_t>> GetTensorArgInfoWithIndex(const C
<< "but the second argument " << arg << " in expression " << call << " has type " << axis->ty;
ffi::Optional<int64_t> int_imm_axis = std::nullopt;
- if (const auto* prim_value = axis.as<PrimValueNode>()) {
- if (const auto* int_imm = prim_value->value.as<IntImmNode>()) {
+ if (const auto* prim_value = axis.as<PrimExprNode>()) {
+ if (const auto* int_imm = ffi::GetRef<PrimExpr>(prim_value).as<IntImmNode>()) {
int_imm_axis = int_imm->value;
}
}
@@ -108,7 +108,7 @@ tirx::PrimFunc GetDLTensorField(tirx::builtin::TVMStructFieldKind field, PrimTyp
return func;
}
-Expr NormalizeToKnownPrimValue(const BlockBuilder&, Call call) { return call; }
+Expr NormalizeToKnownPrimExpr(const BlockBuilder&, Call call) { return call; }
//// relax.tensor_dtype_code
@@ -136,7 +136,7 @@ TVM_REGISTER_OP("relax.inspect.tensor_dtype_code")
.set_attr<FInferType>("FInferType", InferTypeTensorDtypeCode)
.set_attr<FLegalize>("FLegalize", LegalizeTensorDtypeCode)
.set_attr<bool>("RequiresArgumentShapes", false)
- .set_attr<FNormalize>("FNormalize", NormalizeToKnownPrimValue)
+ .set_attr<FNormalize>("FNormalize", NormalizeToKnownPrimExpr)
.set_attr<bool>("FPurity", true);
//// relax.tensor_dtype_bits
@@ -165,7 +165,7 @@ TVM_REGISTER_OP("relax.inspect.tensor_dtype_bits")
.set_attr<FInferType>("FInferType", InferTypeTensorDtypeBits)
.set_attr<FLegalize>("FLegalize", LegalizeTensorDtypeBits)
.set_attr<bool>("RequiresArgumentShapes", false)
- .set_attr<FNormalize>("FNormalize", NormalizeToKnownPrimValue)
+ .set_attr<FNormalize>("FNormalize", NormalizeToKnownPrimExpr)
.set_attr<bool>("FPurity", true);
//// relax.tensor_dtype_lanes
@@ -194,7 +194,7 @@ TVM_REGISTER_OP("relax.inspect.tensor_dtype_lanes")
.set_attr<FInferType>("FInferType", InferTypeTensorDtypeLanes)
.set_attr<FLegalize>("FLegalize", LegalizeTensorDtypeLanes)
.set_attr<bool>("RequiresArgumentShapes", false)
- .set_attr<FNormalize>("FNormalize", NormalizeToKnownPrimValue)
+ .set_attr<FNormalize>("FNormalize", NormalizeToKnownPrimExpr)
.set_attr<bool>("FPurity", true);
//// relax.tensor_ndim
@@ -223,7 +223,7 @@ TVM_REGISTER_OP("relax.inspect.tensor_ndim")
.set_attr<FInferType>("FInferType", InferTypeTensorNDim)
.set_attr<FLegalize>("FLegalize", LegalizeTensorNDim)
.set_attr<bool>("RequiresArgumentShapes", false)
- .set_attr<FNormalize>("FNormalize", NormalizeToKnownPrimValue)
+ .set_attr<FNormalize>("FNormalize", NormalizeToKnownPrimExpr)
.set_attr<bool>("FPurity", true);
//// relax.tensor_shape_i
@@ -298,7 +298,7 @@ TVM_REGISTER_OP("relax.inspect.tensor_shape_i")
.set_attr<FInferType>("FInferType", InferTypeTensorShape)
.set_attr<FLegalize>("FLegalize", LegalizeTensorShape)
.set_attr<bool>("RequiresArgumentShapes", false)
- .set_attr<FNormalize>("FNormalize", NormalizeToKnownPrimValue)
+ .set_attr<FNormalize>("FNormalize", NormalizeToKnownPrimExpr)
.set_attr<bool>("FPurity", true);
//// relax.tensor_stride_i
@@ -345,7 +345,7 @@ TVM_REGISTER_OP("relax.inspect.tensor_stride_i")
.add_argument("axis", "Prim(int64)", "The axis whose extent should be returned")
.set_attr<FInferType>("FInferType", InferTypeTensorStride)
.set_attr<bool>("RequiresArgumentShapes", false)
- .set_attr<FNormalize>("FNormalize", NormalizeToKnownPrimValue)
+ .set_attr<FNormalize>("FNormalize", NormalizeToKnownPrimExpr)
.set_attr<bool>("FPurity", true);
//// relax.tensor_byte_offset
@@ -376,7 +376,7 @@ TVM_REGISTER_OP("relax.inspect.tensor_byte_offset")
.add_argument("tensor", "Tensor", "The tensor to be inspected")
.set_attr<FInferType>("FInferType", InferTypeTensorByteOffset)
.set_attr<bool>("RequiresArgumentShapes", false)
- .set_attr<FNormalize>("FNormalize", NormalizeToKnownPrimValue)
+ .set_attr<FNormalize>("FNormalize", NormalizeToKnownPrimExpr)
.set_attr<bool>("FPurity", true);
//// relax.tensor_elem_offset
@@ -407,7 +407,7 @@ TVM_REGISTER_OP("relax.inspect.tensor_elem_offset")
.add_argument("tensor", "Tensor", "The tensor to be inspected")
.set_attr<FInferType>("FInferType", InferTypeTensorElemOffset)
.set_attr<bool>("RequiresArgumentShapes", false)
- .set_attr<FNormalize>("FNormalize", NormalizeToKnownPrimValue)
+ .set_attr<FNormalize>("FNormalize", NormalizeToKnownPrimExpr)
.set_attr<bool>("FPurity", true);
} // namespace inspect
diff --git a/src/relax/op/tensor/manipulate.cc b/src/relax/op/tensor/manipulate.cc
index f0c7947b5b..96b5c61c9a 100644
--- a/src/relax/op/tensor/manipulate.cc
+++ b/src/relax/op/tensor/manipulate.cc
@@ -700,7 +700,7 @@ TVM_REGISTER_OP("relax.index_tensor")
/* relax.layout_transform */
-Expr layout_transform(Expr x, tirx::IndexMap index_map, ffi::Optional<PrimValue> pad_value,
+Expr layout_transform(Expr x, tirx::IndexMap index_map, ffi::Optional<PrimExpr> pad_value,
ffi::Optional<ffi::Array<IntImm>> axis_separators,
ffi::Optional<ffi::Array<IntImm>> input_axis_separators) {
ffi::ObjectPtr<LayoutTransformAttrs> attrs = ffi::make_object<LayoutTransformAttrs>();
@@ -722,11 +722,11 @@ Type InferTypeLayoutTransform(const Call& call, const BlockBuilder& ctx) {
TensorType data_ty = GetUnaryInputTensorType(call, ctx);
const auto* attrs = call->attrs.as<LayoutTransformAttrs>();
tirx::IndexMap index_map = attrs->index_map;
- ffi::Optional<PrimValue> optional_pad_value = attrs->pad_value;
+ ffi::Optional<PrimExpr> optional_pad_value = attrs->pad_value;
// Check pad_value has same dtype as input.
if (optional_pad_value.defined()) {
- PrimExpr padded_value = optional_pad_value.value()->value;
+ PrimExpr padded_value = optional_pad_value.value();
PrimType padded_dtype = padded_value.ty();
if (padded_dtype != data_ty->dtype) {
TVM_FFI_VISIT_THROW(TypeError, call)
@@ -2944,7 +2944,7 @@ TVM_REGISTER_OP("relax.scatter_nd")
/* relax.scatter_nd */
-Expr slice_scatter(Expr input, Expr src, int axis, PrimValue start, PrimValue end, PrimValue step) {
+Expr slice_scatter(Expr input, Expr src, int axis, PrimExpr start, PrimExpr end, PrimExpr step) {
auto attrs = ffi::make_object<SliceScatterAttrs>();
attrs->axis = std::move(axis);
static const Op& op = Op::Get("relax.slice_scatter");
@@ -3015,18 +3015,18 @@ Type InferTypeSliceScatter(const Call& call, const BlockBuilder& ctx) {
}
auto get_prim_expr_from_arg = [&ctx, &call](const Expr& arg_expr, std::string key) -> PrimExpr {
- const auto* prim_value_node = arg_expr.as<PrimValueNode>();
+ const auto* prim_value_node = arg_expr.as<PrimExprNode>();
if (prim_value_node == nullptr) {
TVM_FFI_VISIT_THROW(TypeError, call)
<< "SliceScatter expects the `" << key << "` argument (" << arg_expr
- << ") to be a PrimValue, but got " << arg_expr->GetTypeKey();
+ << ") to be a PrimExpr, but got " << arg_expr->GetTypeKey();
}
- const PrimExpr& prim_expr = prim_value_node->value;
+ PrimExpr prim_expr = ffi::GetRef<PrimExpr>(prim_value_node);
tvm::PrimType prim_ty = prim_expr.ty();
if (prim_ty.code() != DLDataTypeCode::kDLInt && prim_ty.code() != DLDataTypeCode::kDLUInt) {
TVM_FFI_VISIT_THROW(TypeError, call)
<< "SliceScatter expects `" << key << "` (" << prim_expr
- << ") to be an integer PrimValue, but got dtype " << prim_ty;
+ << ") to be an integer PrimExpr, but got dtype " << prim_ty;
}
return prim_expr;
};
@@ -3091,22 +3091,22 @@ TVM_REGISTER_OP("relax.slice_scatter")
.set_num_inputs(5)
.add_argument("input", "Tensor", "The input tensor.")
.add_argument("src", "Tensor", "The source tensor to scatter.")
- .add_argument("start", "PrimValue", "The starting index of the slice (inclusive).")
- .add_argument("end", "PrimValue", "The ending index of the slice (exclusive).")
- .add_argument("step", "PrimValue", "The step of the slice.")
+ .add_argument("start", "PrimExpr", "The starting index of the slice (inclusive).")
+ .add_argument("end", "PrimExpr", "The ending index of the slice (exclusive).")
+ .add_argument("step", "PrimExpr", "The step of the slice.")
.set_attr<FInferType>("FInferType", InferTypeSliceScatter)
.set_attr<bool>("FPurity", true);
/* relax.one_hot */
-Expr one_hot(Expr indices, PrimValue on_value, PrimValue off_value, int depth, int axis) {
+Expr one_hot(Expr indices, PrimExpr on_value, PrimExpr off_value, int depth, int axis) {
ffi::ObjectPtr<OneHotAttrs> attrs = ffi::make_object<OneHotAttrs>();
attrs->depth = depth;
attrs->axis = axis;
// Check if on_value and off_value have the same dtype
- PrimType on_dtype = on_value->value.ty();
- PrimType off_dtype = off_value->value.ty();
+ PrimType on_dtype = on_value.ty();
+ PrimType off_dtype = off_value.ty();
TVM_FFI_ICHECK(on_dtype == off_dtype)
<< "one_hot: on_value and off_value must have the same dtype, "
<< "but got " << on_dtype << " and " << off_dtype;
@@ -3125,11 +3125,11 @@ TVM_FFI_STATIC_INIT_BLOCK() {
Type InferTypeOneHot(const Call& call, const BlockBuilder& ctx) {
TensorType indices_ty = GetInputTensorType(call, 0, ctx);
const auto* attrs = call->attrs.as<OneHotAttrs>();
- PrimValue on_value = call->args[1].as_or_throw<PrimValue>();
- PrimValue off_value = call->args[2].as_or_throw<PrimValue>();
+ PrimExpr on_value = call->args[1].as_or_throw<PrimExpr>();
+ PrimExpr off_value = call->args[2].as_or_throw<PrimExpr>();
// Check if on_value and off_value have the same dtype
- PrimType on_dtype = on_value->value.ty();
- PrimType off_dtype = off_value->value.ty();
+ PrimType on_dtype = on_value.ty();
+ PrimType off_dtype = off_value.ty();
TVM_FFI_ICHECK(on_dtype == off_dtype)
<< "one_hot: on_value and off_value must have the same dtype, "
<< "but got " << on_dtype << " and " << off_dtype;
@@ -3175,8 +3175,8 @@ TVM_REGISTER_OP("relax.one_hot")
.set_attrs_type<OneHotAttrs>()
.set_num_inputs(3)
.add_argument("indices", "Tensor", "The indices tensor.")
- .add_argument("on_value", "PrimValue", "The value to fill at specified indices.")
- .add_argument("off_value", "PrimValue", "The value to fill at other indices.")
+ .add_argument("on_value", "PrimExpr", "The value to fill at specified indices.")
+ .add_argument("off_value", "PrimExpr", "The value to fill at other indices.")
.set_attr<FInferType>("FInferType", InferTypeOneHot)
.set_attr<bool>("FPurity", true);
diff --git a/src/relax/op/tensor/manipulate.h b/src/relax/op/tensor/manipulate.h
index 343b0f6651..a818998545 100644
--- a/src/relax/op/tensor/manipulate.h
+++ b/src/relax/op/tensor/manipulate.h
@@ -72,7 +72,7 @@ Expr flatten(Expr x);
* \param input axis_separators Array of values for input buffer.
* \return The transformed result.
*/
-Expr layout_transform(Expr x, tirx::IndexMap index_map, ffi::Optional<PrimValue> pad_value,
+Expr layout_transform(Expr x, tirx::IndexMap index_map, ffi::Optional<PrimExpr> pad_value,
ffi::Optional<ffi::Array<IntImm>> axis_separators,
ffi::Optional<ffi::Array<IntImm>> input_axis_separators = std::nullopt);
@@ -293,7 +293,7 @@ Expr scatter_nd(Expr data, Expr indices, Expr updates, ffi::String reduction);
* \param step The how many elements to skip in
* \return The computed result tensor with the same shape as `data`.
*/
-Expr slice_scatter(Expr input, Expr src, int axis, PrimValue start, PrimValue end, PrimValue step);
+Expr slice_scatter(Expr input, Expr src, int axis, PrimExpr start, PrimExpr end, PrimExpr step);
/*!
* \brief Returns a one-hot tensor.
@@ -304,7 +304,7 @@ Expr slice_scatter(Expr input, Expr src, int axis, PrimValue start, PrimValue en
* \param axis The axis to fill.
* \return The computed result.
*/
-Expr one_hot(Expr indices, PrimValue on_value, PrimValue off_value, int depth, int axis);
+Expr one_hot(Expr indices, PrimExpr on_value, PrimExpr off_value, int depth, int axis);
} // namespace relax
} // namespace tvm
diff --git a/src/relax/op/tensor/set.cc b/src/relax/op/tensor/set.cc
index a92cbee4a0..3415034e27 100644
--- a/src/relax/op/tensor/set.cc
+++ b/src/relax/op/tensor/set.cc
@@ -36,14 +36,14 @@ namespace relax {
/* relax.unique */
-Expr unique(Expr x, PrimValue sorted, PrimValue return_index, PrimValue return_inverse,
- PrimValue return_counts, ffi::Optional<PrimValue> axis) {
+Expr unique(Expr x, PrimExpr sorted, PrimExpr return_index, PrimExpr return_inverse,
+ PrimExpr return_counts, ffi::Optional<PrimExpr> axis) {
static const Op& op = Op::Get("relax.unique");
Call call;
if (!axis) {
call = Call(op, {std::move(x), sorted, return_index, return_inverse, return_counts});
} else {
- PrimValue pv_axis = axis.value();
+ PrimExpr pv_axis = axis.value();
call = Call(op, {std::move(x), sorted, return_index, return_inverse, return_counts, pv_axis});
}
return call;
@@ -56,25 +56,25 @@ TVM_FFI_STATIC_INIT_BLOCK() {
Type InferTypeUnique(const Call& call, const BlockBuilder& ctx) {
TensorType data_ty = call->args[0]->ty.as_or_throw<TensorType>();
- PrimValue axis, return_index, return_inverse, return_counts;
+ PrimExpr axis, return_index, return_inverse, return_counts;
if (call->args.size() == 6) {
- if (auto* prim_value_node = call->args[5].as<PrimValueNode>()) {
- axis = ffi::GetRef<PrimValue>(prim_value_node);
+ if (auto* prim_value_node = call->args[5].as<PrimExprNode>()) {
+ axis = ffi::GetRef<PrimExpr>(prim_value_node);
}
}
if (!data_ty->IsUnknownNdim() && axis.defined()) {
// Normalize the axis for sanity check purpose.
- if (const auto* axis_int = axis->value.as<IntImmNode>()) {
+ if (const auto* axis_int = axis.as<IntImmNode>()) {
NormalizeAxis(call, ctx, data_ty->ndim, axis_int->value);
}
}
- TVM_FFI_ICHECK(call->args[2]->IsInstance<PrimValueNode>());
- TVM_FFI_ICHECK(call->args[3]->IsInstance<PrimValueNode>());
- TVM_FFI_ICHECK(call->args[4]->IsInstance<PrimValueNode>());
+ TVM_FFI_ICHECK(call->args[2]->IsInstance<PrimExprNode>());
+ TVM_FFI_ICHECK(call->args[3]->IsInstance<PrimExprNode>());
+ TVM_FFI_ICHECK(call->args[4]->IsInstance<PrimExprNode>());
- return_index = call->args[2].as_or_throw<PrimValue>();
- return_inverse = call->args[3].as_or_throw<PrimValue>();
- return_counts = call->args[4].as_or_throw<PrimValue>();
+ return_index = call->args[2].as_or_throw<PrimExpr>();
+ return_inverse = call->args[3].as_or_throw<PrimExpr>();
+ return_counts = call->args[4].as_or_throw<PrimExpr>();
auto f_convert_to_int64 = [](const PrimExpr& value) {
TVM_FFI_ICHECK(value->IsInstance<IntImmNode>())
@@ -84,9 +84,8 @@ Type InferTypeUnique(const Call& call, const BlockBuilder& ctx) {
return val_imm->value;
};
- int64_t n_int_return = f_convert_to_int64(return_index->value) +
- f_convert_to_int64(return_inverse->value) +
- f_convert_to_int64(return_counts->value);
+ int64_t n_int_return = f_convert_to_int64(return_index) + f_convert_to_int64(return_inverse) +
+ f_convert_to_int64(return_counts);
std::vector<Type> output_ty;
output_ty.reserve(1 + n_int_return);
@@ -103,7 +102,7 @@ Type InferTypeUnique(const Call& call, const BlockBuilder& ctx) {
// index, inverse_indices, and counts
// index: always 1D
- if (f_convert_to_int64(return_index->value)) {
+ if (f_convert_to_int64(return_index)) {
if (data_ty->ndim == 0) {
output_ty.push_back(
TensorType(ShapeExpr({IntImm::Int64(/*value=*/1)}), PrimType::Int(64), data_ty->vdevice));
@@ -113,7 +112,7 @@ Type InferTypeUnique(const Call& call, const BlockBuilder& ctx) {
}
// inverse_indices: always 1D per ONNX spec
- if (f_convert_to_int64(return_inverse->value)) {
+ if (f_convert_to_int64(return_inverse)) {
if (data_ty->ndim == 0) {
output_ty.push_back(
TensorType(ShapeExpr({IntImm::Int64(/*value=*/1)}), PrimType::Int(64), data_ty->vdevice));
@@ -123,7 +122,7 @@ Type InferTypeUnique(const Call& call, const BlockBuilder& ctx) {
}
// counts: always 1D
- if (f_convert_to_int64(return_counts->value)) {
+ if (f_convert_to_int64(return_counts)) {
if (data_ty->ndim == 0) {
output_ty.push_back(
TensorType(ShapeExpr({IntImm::Int64(/*value=*/1)}), PrimType::Int(64), data_ty->vdevice));
diff --git a/src/relax/op/tensor/set.h b/src/relax/op/tensor/set.h
index 4af7478d61..cd8f198a0e 100644
--- a/src/relax/op/tensor/set.h
+++ b/src/relax/op/tensor/set.h
@@ -48,8 +48,8 @@ namespace relax {
* \return The unique elements of the array. The returned array will be sorted if `sorted` is True.
* Additional return values depend on `return_index`, `return_inverse`, and `return_counts`.
*/
-Expr unique(Expr x, PrimValue sorted, PrimValue return_index, PrimValue return_inverse,
- PrimValue return_counts, ffi::Optional<PrimValue> axis);
+Expr unique(Expr x, PrimExpr sorted, PrimExpr return_index, PrimExpr return_inverse,
+ PrimExpr return_counts, ffi::Optional<PrimExpr> axis);
/*!
* \brief Returns the indices of the non-zero elements of the input tensor.
diff --git a/src/relax/op/tensor/unary.cc b/src/relax/op/tensor/unary.cc
index bd15223df8..ef84ac2314 100644
--- a/src/relax/op/tensor/unary.cc
+++ b/src/relax/op/tensor/unary.cc
@@ -71,17 +71,17 @@ RELAX_REGISTER_UNARY_ARITH_OP_AND_IMPL(erf, /*require_float_dtype=*/true);
TVM_REGISTER_OP("relax.clip")
.set_num_inputs(3)
.add_argument("x", "Tensor", "The input tensor.")
- .add_argument("min", "PrimValue", "The lower-bound of the range to be clipped to")
- .add_argument("max", "PrimValue", "The upper-bound of the range to be clipped to")
+ .add_argument("min", "PrimExpr", "The lower-bound of the range to be clipped to")
+ .add_argument("max", "PrimExpr", "The upper-bound of the range to be clipped to")
.set_attr<FInferType>("FInferType", ReturnTypeFromArg<0>)
.set_attr<bool>("FPurity", true);
Expr clip(Expr x, Expr min, Expr max) {
- TVM_FFI_ICHECK(min->IsInstance<PrimValueNode>())
- << "The argument `min` of relax.clip is expected to be a PrimValue, but got "
+ TVM_FFI_ICHECK(min->IsInstance<PrimExprNode>())
+ << "The argument `min` of relax.clip is expected to be a PrimExpr, but got "
<< min->GetTypeKey();
- TVM_FFI_ICHECK(max->IsInstance<PrimValueNode>())
- << "The argument `max` of relax.clip is expected to be a PrimValue, but got "
+ TVM_FFI_ICHECK(max->IsInstance<PrimExprNode>())
+ << "The argument `max` of relax.clip is expected to be a PrimExpr, but got "
<< max->GetTypeKey();
static const Op& op = Op::Get("relax.clip");
return Call(op, {std::move(x), std::move(min), std::move(max)});
diff --git a/src/relax/script/printer/expr.cc b/src/relax/script/printer/expr.cc
index 7b2f39ecf3..229260cdf7 100644
--- a/src/relax/script/printer/expr.cc
+++ b/src/relax/script/printer/expr.cc
@@ -28,13 +28,6 @@ namespace tvm {
namespace script {
namespace printer {
-TVM_STATIC_IR_FUNCTOR(IRDocsifier, vtable)
- .set_dispatch<relax::PrimValue>( //
- "", [](relax::PrimValue n, AccessPath n_p, IRDocsifier d) -> Doc {
- // TODO(@junrushao): float numbers
- return Relax(d, "prim_value")->Call({d->AsDoc<ExprDoc>(n->value, n_p->Attr("value"))});
- });
-
TVM_STATIC_IR_FUNCTOR(IRDocsifier, vtable)
.set_dispatch<relax::StringImm>( //
"", [](relax::StringImm n, AccessPath n_p, IRDocsifier d) -> Doc {
@@ -163,7 +156,6 @@ Doc PrintRelaxVar(relax::Var n, AccessPath p, IRDocsifier d) {
TVM_STATIC_IR_FUNCTOR(IRDocsifier, vtable).set_dispatch<relax::Var>("", PrintRelaxVar);
TVM_STATIC_IR_FUNCTOR(IRDocsifier, vtable).set_dispatch<relax::DataflowVar>("", PrintRelaxVar);
-TVM_REGISTER_SCRIPT_AS_REPR(relax::PrimValueNode, ReprPrintRelax);
TVM_REGISTER_SCRIPT_AS_REPR(relax::StringImmNode, ReprPrintRelax);
TVM_REGISTER_SCRIPT_AS_REPR(relax::DataTypeImmNode, ReprPrintRelax);
TVM_REGISTER_SCRIPT_AS_REPR(relax::TupleNode, ReprPrintRelax);
diff --git a/src/relax/transform/allocate_workspace.cc b/src/relax/transform/allocate_workspace.cc
index a593cb7ffe..f7adcfbb40 100644
--- a/src/relax/transform/allocate_workspace.cc
+++ b/src/relax/transform/allocate_workspace.cc
@@ -150,7 +150,7 @@ class WorkspaceProvider : ExprMutator {
if (!workspace_var_main_.defined()) {
auto shape = ShapeExpr({IntImm::Int32(max_workspace_size_)});
auto ty = DataTypeImm((DLDataType{kDLUInt, 8, 1}));
- auto workspace = MakeAllocTensor(shape, ty, PrimValue::Int64(0));
+ auto workspace = MakeAllocTensor(shape, ty, IntImm::Int64(0));
workspace_var_main_ = builder_->Emit(workspace, "workspace_main");
}
for (const auto& binding : block_node->bindings) {
diff --git a/src/relax/transform/call_tir_rewrite.cc b/src/relax/transform/call_tir_rewrite.cc
index 5a1bbcaa00..ac74f628b8 100644
--- a/src/relax/transform/call_tir_rewrite.cc
+++ b/src/relax/transform/call_tir_rewrite.cc
@@ -93,7 +93,7 @@ class CallTIRMutator : public ExprMutator {
outs.push_back(builder_->Emit(Call(alloc_tensor_op,
{output_ty->shape.value().as_or_throw<ShapeExpr>(),
DataTypeImm(output_ty->dtype->dtype),
- PrimValue::Int64(dev_index), StringImm(scope)},
+ IntImm::Int64(dev_index), StringImm(scope)},
Attrs(), {output_ty}),
"alloc"));
} else {
@@ -130,7 +130,7 @@ class CallTIRMutator : public ExprMutator {
builder_->Emit(Call(alloc_tensor_op,
{field_tensor->shape.value().as_or_throw<ShapeExpr>(),
DataTypeImm(field_tensor->dtype->dtype),
- PrimValue::Int64(dev_index), StringImm(scope)},
+ IntImm::Int64(dev_index), StringImm(scope)},
Attrs(), {field_tensor}),
"alloc"));
} else {
diff --git a/src/relax/transform/compute_prim_value.cc b/src/relax/transform/compute_prim_value.cc
index 4c937fe135..beb0825732 100644
--- a/src/relax/transform/compute_prim_value.cc
+++ b/src/relax/transform/compute_prim_value.cc
@@ -30,23 +30,22 @@ namespace relax {
namespace {
-class PrimValueComputeInjector : public ExprMutator {
+class PrimExprComputeInjector : public ExprMutator {
public:
IRModule Finalize() const { return builder_->Finalize(); }
using ExprMutator::VisitExpr_;
- Expr VisitExpr_(const PrimValueNode* op) override {
- auto node = ExprMutator::VisitExpr_(op).as_or_throw<PrimValue>();
+ Expr VisitExpr_(const PrimExprNode* op) override {
+ auto node = ExprMutator::VisitExpr_(op).as_or_throw<PrimExpr>();
- if (node->value->IsInstance<tirx::IntImmNode>() || node->value->IsInstance<tirx::VarNode>()) {
+ if (node->IsInstance<tirx::IntImmNode>() || node->IsInstance<tirx::VarNode>()) {
return node;
}
- tvm::PrimType ret_ty = node->value.ty();
- auto param_vars = tirx::UndefinedVars(node->value);
- tirx::Stmt body =
- tirx::Evaluate(tirx::Call(node->value.ty(), tirx::builtin::ret(), {node->value}));
+ tvm::PrimType ret_ty = node.ty();
+ auto param_vars = tirx::UndefinedVars(node);
+ tirx::Stmt body = tirx::Evaluate(tirx::Call(node.ty(), tirx::builtin::ret(), {node}));
tirx::PrimFunc func(param_vars, body, ret_ty, {},
DictAttrs({{tirx::attr::kIsHostFunc, true}, {tvm::attr::kSTir, true}}));
@@ -55,7 +54,7 @@ class PrimValueComputeInjector : public ExprMutator {
auto callee = builder_->AddFunction(func, "compute_symbolic_expr");
return relax::Call(callee, param_vars.Map([](const tirx::Var& tir_var) -> relax::Expr {
- return relax::PrimValue(tir_var);
+ return PrimExpr(tir_var);
}));
}
};
@@ -66,7 +65,7 @@ namespace transform {
Pass ComputePrimValue() {
auto pass_func = [=](IRModule mod, PassContext pc) -> IRModule {
- PrimValueComputeInjector mutator;
+ PrimExprComputeInjector mutator;
IRModule updates;
for (const auto& [gvar, base_func] : mod->functions) {
diff --git a/src/relax/transform/dataflow_inplace.cc b/src/relax/transform/dataflow_inplace.cc
index 289c1c3c3b..6ee7dc96e3 100644
--- a/src/relax/transform/dataflow_inplace.cc
+++ b/src/relax/transform/dataflow_inplace.cc
@@ -285,7 +285,7 @@ class AliasAnalyzer {
// function constant: give them a fresh index (TODO: we can handle in more detail if this is a
// case we need to support) prim value: fresh index if node: should not happen inside dataflow
// block
- if (value.as<ConstantNode>() || value.as<PrimValueNode>() || value.as<FunctionNode>()) {
+ if (value.as<ConstantNode>() || value.as<PrimExprNode>() || value.as<FunctionNode>()) {
// TODO(@slyubomirsky): We will probably want special handling for closures
ret.insert(get_fresh_idx());
} else if (auto* target_var_node = value.as<VarNode>()) {
diff --git a/src/relax/transform/fuse_ops.cc b/src/relax/transform/fuse_ops.cc
index f0ab24e40e..1b5794406d 100644
--- a/src/relax/transform/fuse_ops.cc
+++ b/src/relax/transform/fuse_ops.cc
@@ -271,7 +271,9 @@ class GraphCreator : public ExprVisitor {
return;
}
- if (!leaf_expr->IsInstance<LeafExprNode>()) {
+ if (!leaf_expr.as<ShapeExprNode>() && !leaf_expr.as<VarNode>() &&
+ !leaf_expr.as<ConstantNode>() && !leaf_expr.as<PrimExprNode>() &&
+ !leaf_expr.as<StringImmNode>() && !leaf_expr.as<DataTypeImmNode>()) {
// Skip GlobalVar, ExternFunc, OpNode.
return;
}
@@ -644,14 +646,14 @@ class FunctionCreator : public ExprMutator {
return ExprMutator::VisitExpr(expr);
}
- // Check if the expression is constant PrimValue or ShapeExpr or tuple of them that can be
+ // Check if the expression is constant PrimExpr or ShapeExpr or tuple of them that can be
// inlined in the composite functions and excluded from args/params.
bool IsInlinableConstants(const Expr& expr) {
if (const auto* tuple = expr.as<TupleNode>()) {
return std::all_of(tuple->fields.begin(), tuple->fields.end(),
[this](const Expr& e) { return IsInlinableConstants(e); });
- } else if (const auto* prim_value = expr.as<PrimValueNode>()) {
- return tvm::tirx::UndefinedVars(prim_value->value).empty();
+ } else if (const auto* prim_value = expr.as<PrimExprNode>()) {
+ return tvm::tirx::UndefinedVars(ffi::GetRef<PrimExpr>(prim_value)).empty();
} else if (const auto* shape_expr = expr.as<ShapeExprNode>()) {
return std::all_of(shape_expr->values.begin(), shape_expr->values.end(),
[](const PrimExpr& e) { return tvm::tirx::UndefinedVars(e).empty(); });
diff --git a/src/relax/transform/fuse_tir.cc b/src/relax/transform/fuse_tir.cc
index 9037dc1c0f..502ad2ee09 100644
--- a/src/relax/transform/fuse_tir.cc
+++ b/src/relax/transform/fuse_tir.cc
@@ -992,7 +992,7 @@ class FusedTIRConstructor : public ExprVisitor {
}
} else {
TVM_FFI_THROW(TypeError) << "The param type of PrimFunc is expected to be "
- << "Tensor, PrimValue, or ShapeExpr, "
+ << "Tensor, PrimExpr, or ShapeExpr, "
<< "but got " << ty->GetTypeKey();
}
}
@@ -1256,12 +1256,12 @@ class TIRFuseMutator : public ExprMutator {
tir_vars.push_back(prim_value);
}
} else if (const auto* prim_value = ty.as<PrimTypeNode>()) {
- if (const auto* literal = arg.as<PrimValueNode>()) {
- tir_vars.push_back(literal->value);
+ if (const auto* literal = arg.as<PrimExprNode>()) {
+ tir_vars.push_back(ffi::GetRef<PrimExpr>(literal));
} else if (const auto* var = arg.as<VarNode>()) {
tir_vars.push_back(tirx::Var(var->name_hint(), tvm::PrimType(prim_value->dtype)));
} else {
- TVM_FFI_THROW(TypeError) << "FuseTIR expects scalar arguments to be PrimValue or Var, "
+ TVM_FFI_THROW(TypeError) << "FuseTIR expects scalar arguments to be PrimExpr or Var, "
<< "but received " << arg;
}
diff --git a/src/relax/transform/lazy_transform_params.cc b/src/relax/transform/lazy_transform_params.cc
index e245200d4e..7961623e1a 100644
--- a/src/relax/transform/lazy_transform_params.cc
+++ b/src/relax/transform/lazy_transform_params.cc
@@ -99,7 +99,7 @@ class LazyInputMutator : public ExprMutator {
if (auto it = plan_->param_lookup.find(var); it != plan_->param_lookup.end()) {
auto untyped = builder_->Emit(relax::Call(plan_->fget_param,
{
- PrimValue(IntImm::Int64(it->second)),
+ PrimExpr(IntImm::Int64(it->second)),
StringImm(var->name_hint()),
}),
var->name_hint() + "_untyped");
@@ -167,7 +167,7 @@ class LazyOutputMutator : public ExprMutator {
BindingBlock end_of_func = [&]() {
ffi::Array<Binding> propagated_params;
for (const auto& [output_index, expr] : inline_outputs) {
- Call fset_output_call(fset_output, {PrimValue(IntImm::Int64(output_index)), expr});
+ Call fset_output_call(fset_output, {PrimExpr(IntImm::Int64(output_index)), expr});
Var void_output("_void", TupleType(ffi::Array<Type>{}));
propagated_params.push_back(VarBinding(void_output, fset_output_call));
}
@@ -208,7 +208,7 @@ class LazyOutputMutator : public ExprMutator {
if (plan_.has_value()) {
if (auto it = plan_->output_lookup.find(var); it != plan_->output_lookup.end()) {
for (auto output_index : it->second) {
- callback(Call(plan_->fset_output, {PrimValue(IntImm::Int64(output_index)), var}));
+ callback(Call(plan_->fset_output, {PrimExpr(IntImm::Int64(output_index)), var}));
}
}
}
diff --git a/src/relax/transform/lift_transform_params.cc b/src/relax/transform/lift_transform_params.cc
index 1df218941b..0700b43180 100644
--- a/src/relax/transform/lift_transform_params.cc
+++ b/src/relax/transform/lift_transform_params.cc
@@ -676,7 +676,7 @@ class ConsumeBundledParams : public ExprMutator {
param_remap_[tuple_get_item->index] = new_var;
builder_->Emit(
Call(call_pure_packed,
- {builtin_tuple_reset_item, tuple_get_item->tuple, PrimValue(tuple_get_item->index)},
+ {builtin_tuple_reset_item, tuple_get_item->tuple, PrimExpr(tuple_get_item->index)},
tvm::Attrs(), {TupleType(ffi::Array<Type>{})}));
} else {
ExprMutator::VisitBinding_(binding, tuple_get_item);
diff --git a/src/relax/transform/lower_alloc_tensor.cc b/src/relax/transform/lower_alloc_tensor.cc
index 52bca3e707..96014fa2f0 100644
--- a/src/relax/transform/lower_alloc_tensor.cc
+++ b/src/relax/transform/lower_alloc_tensor.cc
@@ -49,7 +49,7 @@ class Mutator : public ExprMutator {
auto shape_arg = op->args[0];
auto dtype = op->args[1].as_or_throw<DataTypeImm>();
- PrimValue runtime_device_index = op->args[2].as_or_throw<PrimValue>();
+ PrimExpr runtime_device_index = op->args[2].as_or_throw<PrimExpr>();
StringImm storage_scope = op->args[3].as_or_throw<StringImm>();
auto shape = [&]() -> ffi::Array<PrimExpr> {
@@ -85,8 +85,8 @@ class Mutator : public ExprMutator {
ShapeExpr size({nbytes});
int64_t vdevice_index = -1;
- if (auto* prim_value_node = op->args[2].as<PrimValueNode>()) {
- vdevice_index = prim_value_node->value.as<IntImmNode>()->value;
+ if (auto* prim_value_node = op->args[2].as<PrimExprNode>()) {
+ vdevice_index = ffi::GetRef<PrimExpr>(prim_value_node).as<IntImmNode>()->value;
}
ffi::Optional<VDevice> vdevice = GetGlobalVDevice(ctx_mod_, vdevice_index);
@@ -112,7 +112,7 @@ class Mutator : public ExprMutator {
}
}
- auto offset = PrimValue::Int64(0);
+ auto offset = IntImm::Int64(0);
Expr storage = relax::Call(mem_alloc_storage_op, {size, runtime_device_index, storage_scope,
DataTypeImm((DLDataType{kDLUInt, 8, 1}))});
diff --git a/src/relax/transform/merge_composite_functions.cc b/src/relax/transform/merge_composite_functions.cc
index aedd52db8f..7a50ae5f0e 100644
--- a/src/relax/transform/merge_composite_functions.cc
+++ b/src/relax/transform/merge_composite_functions.cc
@@ -90,7 +90,7 @@ class CompositeGroupsBuilder : public MemoizedExprTranslator<Group*> {
// Groups for CallNode are created in its visitor.
if (e->IsInstance<ConstantNode>() || e->IsInstance<ShapeExprNode>() ||
e->IsInstance<TupleNode>() || e->IsInstance<TupleGetItemNode>() ||
- e->IsInstance<PrimValueNode>()) {
+ e->IsInstance<PrimExprNode>()) {
memo_[e] = arena_->make<Group>();
}
});
diff --git a/src/relax/transform/remove_unused_outputs.cc b/src/relax/transform/remove_unused_outputs.cc
index f8a9e8cde7..18793136a9 100644
--- a/src/relax/transform/remove_unused_outputs.cc
+++ b/src/relax/transform/remove_unused_outputs.cc
@@ -288,8 +288,7 @@ Pass RemoveUnusedOutputs() {
// could remember the index mapping and re-index any access
// into the old tuple, but it's simpler to just let
// CanonicalizeBindings and DCE handle it.
- new_results.push_back(
- relax::PrimValue(FloatImm(tvm::PrimType::Float(64), std::nan(""))));
+ new_results.push_back(PrimExpr(FloatImm(tvm::PrimType::Float(64), std::nan(""))));
}
}
diff --git a/src/relax/transform/remove_unused_parameters.cc b/src/relax/transform/remove_unused_parameters.cc
index 4f28f9d131..df986a37d1 100644
--- a/src/relax/transform/remove_unused_parameters.cc
+++ b/src/relax/transform/remove_unused_parameters.cc
@@ -129,7 +129,7 @@ std::optional<CalleeAnalysis> AnalyzeCallee(Function func) {
auto tir_binding = InferSymbolicVarMap(old_binding, analyzer);
for (const auto& tir_var : free_tir_vars) {
- new_args.push_back(PrimValue(tir_binding.at(tir_var)));
+ new_args.push_back(PrimExpr(tir_binding.at(tir_var)));
}
}
diff --git a/src/relax/transform/rewrite_cuda_graph.cc b/src/relax/transform/rewrite_cuda_graph.cc
index c9ff7b4407..58c209eab5 100644
--- a/src/relax/transform/rewrite_cuda_graph.cc
+++ b/src/relax/transform/rewrite_cuda_graph.cc
@@ -504,8 +504,8 @@ class CUDAGraphRewritePlanner : public ExprVisitor {
expr->IsInstance<StringImmNode>() || expr->IsInstance<GlobalVarNode>()) {
return true;
}
- if (const auto* prim_value = expr.as<PrimValueNode>()) {
- return IsStatic(prim_value->value, vars_collector, tir_vars_collector);
+ if (const auto* prim_value = expr.as<PrimExprNode>()) {
+ return IsStatic(ffi::GetRef<PrimExpr>(prim_value), vars_collector, tir_vars_collector);
}
if (const auto* var = expr.as<VarNode>()) {
if (vars_collector != nullptr) {
@@ -674,7 +674,7 @@ Function MergeAllocationPlans(const std::vector<LiftedFunctionRewritePlan*>& all
TVM_FFI_ICHECK_EQ(storage_shape->values.size(), 1);
int64_t size = storage_shape->values[0].as_or_throw<IntImm>()->value;
int64_t virtual_device_id =
- alloc_storage->args[1].as_or_throw<PrimValue>()->value.as_or_throw<IntImm>()->value;
+ alloc_storage->args[1].as_or_throw<PrimExpr>().as_or_throw<IntImm>()->value;
TVM_FFI_ICHECK_EQ(virtual_device_id, 0);
ffi::String storage_scope = alloc_storage->args[2].as_or_throw<StringImm>()->value;
auto [it, _] = storage_records.try_emplace(storage_scope, alloc_plans.size());
@@ -785,7 +785,7 @@ class CUDAGraphRewriter : public ExprMutator {
auto ret_ty = gv_alloc->ty.as_or_throw<FuncType>()->ret;
launch_subgraph =
Call(call_builtin_with_ctx_op,
- {builtin_get_cached_alloc, Tuple({gv_alloc, PrimValue(IntImm::Int64(0))})}, Attrs(),
+ {builtin_get_cached_alloc, Tuple({gv_alloc, PrimExpr(IntImm::Int64(0))})}, Attrs(),
{ret_ty});
} else {
auto gv_func = builder_->AddFunction(
@@ -813,7 +813,7 @@ class CUDAGraphRewriter : public ExprMutator {
}
// Arguments of builtin_run_or_capture
ffi::Array<Expr> tuple_arg_fields{gv_func, Tuple(args),
- PrimValue(IntImm::Int64(index_capture_++))};
+ PrimExpr(IntImm::Int64(index_capture_++))};
if (plan->propogated_tir_vars.defined()) {
// The shape expr is explicitly passed twice, one as the last argument of the lifted
// function, one as the last argument of builtin_run_or_capture as the cache key. Explicitly
diff --git a/src/relax/transform/static_plan_block_memory.cc b/src/relax/transform/static_plan_block_memory.cc
index 2a04461555..d1f35882d8 100644
--- a/src/relax/transform/static_plan_block_memory.cc
+++ b/src/relax/transform/static_plan_block_memory.cc
@@ -652,8 +652,8 @@ class StorageAllocatorInit : public StorageAllocatorBaseVisitor {
StringImm storage_scope = call->args[3].as_or_throw<StringImm>();
int64_t vdevice_index = -1;
- if (auto* prim_value_node = call->args[2].as<PrimValueNode>()) {
- vdevice_index = prim_value_node->value.as<IntImmNode>()->value;
+ if (auto* prim_value_node = call->args[2].as<PrimExprNode>()) {
+ vdevice_index = ffi::GetRef<PrimExpr>(prim_value_node).as<IntImmNode>()->value;
}
ffi::Optional<VDevice> vdevice = GetGlobalVDevice(ctx_mod_, vdevice_index);
@@ -932,7 +932,7 @@ class StorageAllocationRewriter : public ExprMutator {
const auto* ty = call->ty.as<TensorTypeNode>();
TVM_FFI_ICHECK_NOTNULL(ty);
TVM_FFI_ICHECK_NOTNULL(ty->shape.as<ShapeExprNode>());
- PrimValue runtime_device_index = call->args[2].as_or_throw<PrimValue>();
+ PrimExpr runtime_device_index = call->args[2].as_or_throw<PrimExpr>();
// If the token is visited for the first time, create a storage variable using
// `memory.alloc_storage` for it.
@@ -941,7 +941,7 @@ class StorageAllocationRewriter : public ExprMutator {
auto it_token = token2storage_var_.find(token.get());
if (it_token == token2storage_var_.end()) {
ShapeExpr size({token->bytes});
- PrimValue virtual_device_index = runtime_device_index;
+ PrimExpr virtual_device_index = runtime_device_index;
DLDataType dtype = token->dtype;
Call alloc_storage(mem_alloc_storage,
{std::move(size), virtual_device_index, StringImm(token->storage_scope),
@@ -954,7 +954,7 @@ class StorageAllocationRewriter : public ExprMutator {
}
// And always create a `memory.alloc_tensor` for the old `builtin.alloc_tensor`.
- PrimValue offset = PrimValue::Int64(0);
+ PrimExpr offset = IntImm::Int64(0);
DLDataType dtype = ty->dtype->dtype;
return Call(mem_alloc_tensor,
{storage_var, offset, ty->shape.value(), DataTypeImm(dtype), call->args[2]},
@@ -986,12 +986,12 @@ class StorageAllocationRewriter : public ExprMutator {
bytes *= IntImm::Int64(static_cast<int64_t>(dtype_ty.StorageBytes()));
Call alloc_storage(mem_alloc_storage,
{/*size=*/ShapeExpr({bytes}),
- /*virtual_device_index=*/call->args[2].as_or_throw<PrimValue>(),
+ /*virtual_device_index=*/call->args[2].as_or_throw<PrimExpr>(),
/*storage_scope=*/call->args[3].as_or_throw<StringImm>(), //
/*dtype=*/DataTypeImm(dtype)});
Var storage = builder_->Emit(alloc_storage, "storage");
return Call(mem_alloc_tensor, {storage, //
- /*offset=*/PrimValue::Int64(0),
+ /*offset=*/IntImm::Int64(0),
/*shape=*/ffi::GetRef<ShapeExpr>(shape), //
/*dtype=*/DataTypeImm(dtype),
/*vdevice_index=*/call->args[2]});
diff --git a/src/relax/utils.cc b/src/relax/utils.cc
index 2f5cc6d9de..caedfa3663 100644
--- a/src/relax/utils.cc
+++ b/src/relax/utils.cc
@@ -200,8 +200,8 @@ bool IsBoolType(const Type& ty, bool permit_unknown_rank, bool permit_unknown_dt
}
bool IsLeafOrTuple(const Expr& expr) {
- return expr.as<LeafExprNode>() || expr.as<GlobalVarNode>() || expr.as<ExternFuncNode>() ||
- expr.as<OpNode>() || expr.as<TupleNode>();
+ return !expr.as<CallNode>() && !expr.as<TupleGetItemNode>() && !expr.as<SeqExprNode>() &&
+ !expr.as<IfNode>() && !expr.as<FunctionNode>();
}
bool IsImpureCall(const Call& call) {
diff --git a/src/runtime/extra/contrib/tensorrt/tensorrt_ops.cc b/src/runtime/extra/contrib/tensorrt/tensorrt_ops.cc
index e7783ae80d..61dee5a0fb 100644
--- a/src/runtime/extra/contrib/tensorrt/tensorrt_ops.cc
+++ b/src/runtime/extra/contrib/tensorrt/tensorrt_ops.cc
@@ -180,7 +180,7 @@ class ActivationOpConverter : public TensorRTOpConverter {
params->network->addActivation(*params->inputs.at(0).tensor, it->second);
#if TRT_VERSION_GE(5, 1, 5)
if (op_name == "clip") {
- // Relax clip min/max are PrimValue args (serialized as arg_min/arg_max), not Relay attrs.
+ // Relax clip min/max are PrimExpr args (serialized as arg_min/arg_max), not Relay attrs.
float a_min = static_cast<float>(params->node.GetAttr<double>("arg_min"));
float a_max = static_cast<float>(params->node.GetAttr<double>("arg_max"));
act_layer->setAlpha(a_min);
diff --git a/src/runtime/vm/builtin.cc b/src/runtime/vm/builtin.cc
index 30fbf77b9c..f0f69769f2 100644
--- a/src/runtime/vm/builtin.cc
+++ b/src/runtime/vm/builtin.cc
@@ -97,14 +97,14 @@ void MatchPrimValue(int64_t input_value, DLTensor* heap, int code_value, int64_t
if (code == MatchShapeCode::kAssertEqualToImm) {
TVM_FFI_CHECK_EQ(input_value, reg, RuntimeError)
<< err_ctx.value_or("") << " match_cast error, "
- << " PrimValue mismatch to specified constant.";
+ << " PrimExpr mismatch to specified constant.";
} else if (code == MatchShapeCode::kStoreToHeap) {
heap_data[reg] = input_value;
} else if (code == MatchShapeCode::kNoOp) {
} else if (code == MatchShapeCode::kAssertEqualToLoad) {
TVM_FFI_CHECK_EQ(input_value, heap_data[reg], RuntimeError)
<< err_ctx.value_or("") << " match_cast error, "
- << " PrimValue mismatch to a previous populated value.";
+ << " PrimExpr mismatch to a previous populated value.";
} else {
TVM_FFI_THROW(InternalError) << "Unknown match shape code: " << static_cast<int>(code);
}
@@ -299,9 +299,9 @@ TVM_FFI_STATIC_INIT_BLOCK() {
}
/*!
- * \brief Builtin function to check if arg is PrimValue(dtype)
+ * \brief Builtin function to check if arg is PrimExpr(dtype)
* \param arg The input argument.
- * \param dtype Expected dtype of the PrimValue. Can be DLDataType{kDLOpaqueHandle, 0, 0} for
+ * \param dtype Expected dtype of the PrimExpr. Can be DLDataType{kDLOpaqueHandle, 0, 0} for
* unknown dtype.
* \param err_ctx Additional context if error occurs.
*/
diff --git a/src/s_tir/transform/inject_virtual_thread.cc b/src/s_tir/transform/inject_virtual_thread.cc
index ba3a300c33..f0bc74f6bb 100644
--- a/src/s_tir/transform/inject_virtual_thread.cc
+++ b/src/s_tir/transform/inject_virtual_thread.cc
@@ -228,7 +228,7 @@ class VTInjector : public arith::IRMutatorWithAnalyzer {
PrimExpr stride = it->second / MakeConst(offset.ty(), dtype.lanes());
offset = RewriteIndex(offset, stride);
- return Call(op->BaseExprNode::ty.as_or_throw<PrimType>(), op->op,
+ return Call(op->ExprNode::ty.as_or_throw<PrimType>(), op->op,
{op->args[0], op->args[1], offset, extent, op->args[4]});
} else if (op->op.same_as(builtin::tvm_context_id())) {
return allow_share_ ? ffi::GetRef<PrimExpr>(op) : var_;
diff --git a/src/tirx/ir/expr.cc b/src/tirx/ir/expr.cc
index d30fc9da6b..ad9278c47a 100644
--- a/src/tirx/ir/expr.cc
+++ b/src/tirx/ir/expr.cc
@@ -64,8 +64,8 @@ TVM_FFI_INLINE const PrimTypeNode* GetPrimTypeNode(const PrimExpr& expr) {
// Avoid PrimExpr::ty() ObjectRef materialization in expression constructor hot paths.
const auto* node = expr.get();
TVM_FFI_DCHECK(node != nullptr);
- TVM_FFI_DCHECK(node->BaseExprNode::ty.defined());
- const auto* prim_ty = node->BaseExprNode::ty.as<PrimTypeNode>();
+ TVM_FFI_DCHECK(node->ExprNode::ty.defined());
+ const auto* prim_ty = node->ExprNode::ty.as<PrimTypeNode>();
TVM_FFI_DCHECK(prim_ty != nullptr);
return prim_ty;
}
@@ -133,7 +133,7 @@ TVM_FFI_STATIC_INIT_BLOCK() {
TVM_FFI_CHECK(a_ty->dtype == b_ty->dtype, TypeError) \
<< "mismatched types. " << a_ty->dtype << " vs. " << b_ty->dtype << "\n"; \
ffi::ObjectPtr<T> node = ffi::make_object<T>(); \
- node->BaseExprNode::ty = a.get()->BaseExprNode::ty; \
+ node->ExprNode::ty = a.get()->ExprNode::ty; \
node->a = std::move(a); \
node->b = std::move(b); \
node->span = std::move(span); \
@@ -150,7 +150,7 @@ TVM_FFI_STATIC_INIT_BLOCK() {
TVM_FFI_CHECK(a_ty->dtype == b_ty->dtype, TypeError) \
<< "mismatched types. " << a_ty->dtype << " vs. " << b_ty->dtype << "\n"; \
ffi::ObjectPtr<T> node = ffi::make_object<T>(); \
- node->BaseExprNode::ty = PrimType(DLDataType{kDLBool, 8, a_ty->dtype.lanes}); \
+ node->ExprNode::ty = PrimType(DLDataType{kDLBool, 8, a_ty->dtype.lanes}); \
node->a = std::move(a); \
node->b = std::move(b); \
node->span = std::move(span); \
@@ -162,7 +162,7 @@ Var::Var(ffi::String name_hint, PrimType dtype, Span span) {
auto n = ffi::make_object<VarNode>();
n->name_hint = std::move(name_hint);
n->type_annotation = dtype;
- n->BaseExprNode::ty = dtype;
+ n->ExprNode::ty = dtype;
n->span = std::move(span);
data_ = std::move(n);
}
@@ -172,9 +172,9 @@ Var::Var(ffi::String name_hint, Type type_annotation, Span span) {
n->name_hint = std::move(name_hint);
n->type_annotation = std::move(type_annotation);
if (n->type_annotation.as<PrimTypeNode>()) {
- n->BaseExprNode::ty = n->type_annotation;
+ n->ExprNode::ty = n->type_annotation;
} else {
- n->BaseExprNode::ty = PrimType(GetRuntimeDLDataType(n->type_annotation));
+ n->ExprNode::ty = PrimType(GetRuntimeDLDataType(n->type_annotation));
}
n->span = std::move(span);
data_ = std::move(n);
@@ -205,7 +205,7 @@ Var Var::copy_with_dtype(PrimType dtype) const {
new_ptr = ffi::make_object<VarNode>(*node);
}
new_ptr->type_annotation = dtype;
- new_ptr->BaseExprNode::ty = dtype;
+ new_ptr->ExprNode::ty = dtype;
return Var(new_ptr);
}
@@ -225,7 +225,7 @@ SizeVar::SizeVar(ffi::String name_hint, PrimType dtype, Span span) {
auto n = ffi::make_object<SizeVarNode>();
n->name_hint = std::move(name_hint);
n->type_annotation = dtype;
- n->BaseExprNode::ty = n->type_annotation;
+ n->ExprNode::ty = n->type_annotation;
n->span = std::move(span);
data_ = std::move(n);
}
@@ -234,7 +234,7 @@ SizeVar::SizeVar(ffi::String name_hint, Type type_annotation, Span span) {
auto n = ffi::make_object<SizeVarNode>();
n->name_hint = std::move(name_hint);
n->type_annotation = std::move(type_annotation);
- n->BaseExprNode::ty = PrimType(GetRuntimeDLDataType(n->type_annotation));
+ n->ExprNode::ty = PrimType(GetRuntimeDLDataType(n->type_annotation));
n->span = std::move(span);
data_ = std::move(n);
}
@@ -278,7 +278,7 @@ TVM_FFI_STATIC_INIT_BLOCK() {
// StringImm
StringImm::StringImm(ffi::String value, Span span) {
ffi::ObjectPtr<StringImmNode> node = ffi::make_object<StringImmNode>();
- node->BaseExprNode::ty = PrimType::Handle();
+ node->ExprNode::ty = PrimType::Handle();
node->value = std::move(value);
node->span = std::move(span);
data_ = std::move(node);
@@ -296,7 +296,7 @@ Cast::Cast(PrimType value_ty, PrimExpr value, Span span) {
PrimType value_expr_ty = value.ty();
TVM_FFI_ICHECK_EQ(value_ty->dtype.lanes, value_expr_ty->dtype.lanes);
ffi::ObjectPtr<CastNode> node = ffi::make_object<CastNode>();
- node->BaseExprNode::ty = std::move(value_ty);
+ node->ExprNode::ty = std::move(value_ty);
node->value = std::move(value);
node->span = std::move(span);
data_ = std::move(node);
@@ -455,7 +455,7 @@ And::And(PrimExpr a, PrimExpr b, Span span) {
TVM_FFI_CHECK(a_ty == b_ty, TypeError) << "mismatched types";
ffi::ObjectPtr<AndNode> node = ffi::make_object<AndNode>();
- node->BaseExprNode::ty = PrimType(DLDataType{kDLBool, 8, a_ty->dtype.lanes});
+ node->ExprNode::ty = PrimType(DLDataType{kDLBool, 8, a_ty->dtype.lanes});
node->a = std::move(a);
node->b = std::move(b);
node->span = std::move(span);
@@ -479,7 +479,7 @@ Or::Or(PrimExpr a, PrimExpr b, Span span) {
TVM_FFI_CHECK(a_ty == b_ty, TypeError) << "mismatched types";
ffi::ObjectPtr<OrNode> node = ffi::make_object<OrNode>();
- node->BaseExprNode::ty = PrimType(DLDataType{kDLBool, 8, a_ty->dtype.lanes});
+ node->ExprNode::ty = PrimType(DLDataType{kDLBool, 8, a_ty->dtype.lanes});
node->a = std::move(a);
node->b = std::move(b);
node->span = std::move(span);
@@ -499,7 +499,7 @@ Not::Not(PrimExpr a, Span span) {
TVM_FFI_ICHECK(a_ty.MatchesCode(DLDataTypeCode::kDLBool));
ffi::ObjectPtr<NotNode> node = ffi::make_object<NotNode>();
- node->BaseExprNode::ty = PrimType(DLDataType{kDLBool, 8, a_ty->dtype.lanes});
+ node->ExprNode::ty = PrimType(DLDataType{kDLBool, 8, a_ty->dtype.lanes});
node->a = std::move(a);
node->span = std::move(span);
data_ = std::move(node);
@@ -526,7 +526,7 @@ Select::Select(PrimExpr condition, PrimExpr true_value, PrimExpr false_value, Sp
<< "False type: " << false_ty->dtype << "; True type: " << true_ty->dtype;
ffi::ObjectPtr<SelectNode> node = ffi::make_object<SelectNode>();
- node->BaseExprNode::ty = true_ty;
+ node->ExprNode::ty = true_ty;
node->condition = std::move(condition);
node->true_value = std::move(true_value);
node->false_value = std::move(false_value);
@@ -559,14 +559,14 @@ Ramp::Ramp(PrimExpr base, PrimExpr stride, PrimExpr lanes, Span span) {
if (lanes_as_int) {
int lanes = static_cast<int>(lanes_as_int->value);
TVM_FFI_ICHECK_GT(lanes, 1);
- node->BaseExprNode::ty = base_ty.WithLanes(lanes);
+ node->ExprNode::ty = base_ty.WithLanes(lanes);
// Stick to int32 lanes for fixed length vectors
node->lanes = lanes;
} else { /* scalable vector */
std::optional<int> vscale_factor = ExtractVscaleFactor(lanes);
TVM_FFI_ICHECK(vscale_factor) << "Invalid expression for scalable lanes " << lanes;
- node->BaseExprNode::ty =
+ node->ExprNode::ty =
PrimType::ScalableVector(base_ty.code(), base_ty.bits(), vscale_factor.value());
lanes = Mul(Call(PrimType::Int(32), tirx::builtin::vscale(), {}), vscale_factor.value());
node->lanes = lanes;
@@ -595,14 +595,14 @@ Broadcast::Broadcast(PrimExpr value, PrimExpr lanes, Span span) {
if (lanes_int) {
int lanes = static_cast<int>(lanes_int->value);
TVM_FFI_ICHECK_GT(lanes, 1);
- node->BaseExprNode::ty = value_ty.WithLanes(lanes);
+ node->ExprNode::ty = value_ty.WithLanes(lanes);
// Stick to int32 lanes for fixed length vectors
node->lanes = lanes;
} else { /* scalable vector */
std::optional<int> vscale_factor = ExtractVscaleFactor(lanes);
TVM_FFI_ICHECK(vscale_factor) << "Invalid expression for scalable lanes " << lanes;
- node->BaseExprNode::ty =
+ node->ExprNode::ty =
PrimType::ScalableVector(value_ty.code(), value_ty.bits(), vscale_factor.value());
lanes = Mul(Call(PrimType::Int(32), tirx::builtin::vscale(), {}), vscale_factor.value());
node->lanes = lanes;
@@ -626,7 +626,7 @@ Let::Let(Var var, PrimExpr value, PrimExpr body, Span span) {
TVM_FFI_ICHECK(value.ty() == var.ty());
ffi::ObjectPtr<LetNode> node = ffi::make_object<LetNode>();
- node->BaseExprNode::ty = body.ty();
+ node->ExprNode::ty = body.ty();
node->var = std::move(var);
node->value = std::move(value);
node->body = std::move(body);
@@ -675,13 +675,13 @@ static ffi::Array<PrimExpr> ConvertCallArgs(ffi::Array<CallArg> args) {
return prim_expr_args;
}
-Call::Call(PrimType ret_ty, RelaxExpr op, ffi::Array<PrimExpr> args, Attrs attrs, Span span) {
+Call::Call(PrimType ret_ty, tvm::Expr op, ffi::Array<PrimExpr> args, Attrs attrs, Span span) {
for (size_t i = 0; i < args.size(); ++i) {
TVM_FFI_ICHECK(args[i].defined()) << "arg " << i << " is not defined()";
}
ffi::ObjectPtr<CallNode> node = ffi::make_object<CallNode>();
- node->BaseExprNode::ty = std::move(ret_ty);
+ node->ExprNode::ty = std::move(ret_ty);
node->op = std::move(op);
node->args = std::move(args);
node->attrs = std::move(attrs);
@@ -689,19 +689,19 @@ Call::Call(PrimType ret_ty, RelaxExpr op, ffi::Array<PrimExpr> args, Attrs attrs
data_ = std::move(node);
}
-Call::Call(PrimType ret_ty, RelaxExpr op, ffi::Array<PrimExpr> args, Span span)
+Call::Call(PrimType ret_ty, tvm::Expr op, ffi::Array<PrimExpr> args, Span span)
: Call(std::move(ret_ty), std::move(op), std::move(args), Attrs(), std::move(span)) {}
TVM_FFI_STATIC_INIT_BLOCK() {
namespace refl = tvm::ffi::reflection;
refl::GlobalDef()
.def("tirx.Call",
- [](ffi::Optional<PrimType> dtype, RelaxExpr op, ffi::Array<CallArg> args, Span span) {
+ [](ffi::Optional<PrimType> dtype, tvm::Expr op, ffi::Array<CallArg> args, Span span) {
return Call(dtype.value_or(PrimType::Void()), op, ConvertCallArgs(args), Attrs(),
span);
})
.def("tirx.CallWithAttrs",
- [](ffi::Optional<PrimType> dtype, RelaxExpr op, ffi::Array<CallArg> args,
+ [](ffi::Optional<PrimType> dtype, tvm::Expr op, ffi::Array<CallArg> args,
ffi::Optional<Attrs> attrs, Span span) {
return Call(dtype.value_or(PrimType::Void()), op, ConvertCallArgs(args),
attrs.value_or(Attrs()), span);
@@ -724,7 +724,7 @@ Shuffle::Shuffle(ffi::Array<PrimExpr> vectors, ffi::Array<PrimExpr> indices, Spa
TVM_FFI_ICHECK_LE(indices.size(), static_cast<size_t>(total_lanes));
ffi::ObjectPtr<ShuffleNode> node = ffi::make_object<ShuffleNode>();
- node->BaseExprNode::ty = base_type.WithLanes(static_cast<int>(indices.size()));
+ node->ExprNode::ty = base_type.WithLanes(static_cast<int>(indices.size()));
node->vectors = std::move(vectors);
node->indices = std::move(indices);
node->span = std::move(span);
@@ -849,7 +849,7 @@ Reduce::Reduce(CommReducer combiner, ffi::Array<PrimExpr> source, ffi::Array<Ite
<< "but received " << init[i] << " of type " << init[i]->GetTypeKey();
}
}
- n->BaseExprNode::ty = source[value_index].ty();
+ n->ExprNode::ty = source[value_index].ty();
n->combiner = std::move(combiner);
n->source = std::move(source);
n->init = std::move(init);
@@ -877,7 +877,7 @@ void BufferLoadNode::LegalizeDType() {
}
if (indices.empty()) {
- this->BaseExprNode::ty = buffer->dtype;
+ this->ExprNode::ty = buffer->dtype;
} else {
PrimType index_ty = indices.back().ty();
int16_t buffer_encoded_lanes = static_cast<int16_t>(buffer->dtype->dtype.lanes);
@@ -888,14 +888,14 @@ void BufferLoadNode::LegalizeDType() {
<< "Index dtype and buffer dtype can't both be scalable.";
if (is_index_scalable) {
- this->BaseExprNode::ty =
+ this->ExprNode::ty =
PrimType::ScalableVector(buffer->dtype.code(), buffer->dtype.bits(),
index_ty.VScaleFactor() * buffer->dtype.lanes());
} else if (is_buffer_dtype_scalable) {
- this->BaseExprNode::ty = PrimType::ScalableVector(buffer->dtype.code(), buffer->dtype.bits(),
- -buffer_encoded_lanes * index_ty.lanes());
+ this->ExprNode::ty = PrimType::ScalableVector(buffer->dtype.code(), buffer->dtype.bits(),
+ -buffer_encoded_lanes * index_ty.lanes());
} else {
- this->BaseExprNode::ty = buffer->dtype.WithLanes(index_ty.lanes() * buffer->dtype.lanes());
+ this->ExprNode::ty = buffer->dtype.WithLanes(index_ty.lanes() * buffer->dtype.lanes());
}
}
}
@@ -948,7 +948,7 @@ TVM_FFI_STATIC_INIT_BLOCK() {
// ProducerLoad
ProducerLoad::ProducerLoad(DataProducer producer, ffi::Array<PrimExpr> indices, Span span) {
ffi::ObjectPtr<ProducerLoadNode> node = ffi::make_object<ProducerLoadNode>();
- node->BaseExprNode::ty = producer->GetDataType();
+ node->ExprNode::ty = producer->GetDataType();
node->producer = std::move(producer);
node->indices = std::move(indices);
node->span = std::move(span);
diff --git a/src/tirx/ir/expr_functor.cc b/src/tirx/ir/expr_functor.cc
index 9fa3a39214..36f7e28f4f 100644
--- a/src/tirx/ir/expr_functor.cc
+++ b/src/tirx/ir/expr_functor.cc
@@ -155,7 +155,7 @@ PrimExpr ExprMutator::VisitExpr_(const CallNode* op) {
if (args.same_as(op->args)) {
return ffi::GetRef<PrimExpr>(op);
} else {
- return Call(op->BaseExprNode::ty.as_or_throw<PrimType>(), op->op, args, op->attrs, op->span);
+ return Call(op->ExprNode::ty.as_or_throw<PrimType>(), op->op, args, op->attrs, op->span);
}
}
@@ -227,7 +227,7 @@ PrimExpr ExprMutator::VisitExpr_(const CastNode* op) {
if (value.same_as(op->value)) {
return ffi::GetRef<PrimExpr>(op);
} else {
- return Cast(op->BaseExprNode::ty.as_or_throw<PrimType>(), value);
+ return Cast(op->ExprNode::ty.as_or_throw<PrimType>(), value);
}
}
diff --git a/src/tirx/op/op.cc b/src/tirx/op/op.cc
index 2be5c7123f..8caaf4964e 100644
--- a/src/tirx/op/op.cc
+++ b/src/tirx/op/op.cc
@@ -54,8 +54,8 @@ TVM_FFI_INLINE const PrimTypeNode* GetPrimTypeNode(const PrimExpr& expr) {
// Avoid PrimExpr::ty() ObjectRef materialization on binary operator hot paths.
const auto* node = expr.get();
TVM_FFI_DCHECK(node != nullptr);
- TVM_FFI_DCHECK(node->BaseExprNode::ty.defined());
- const auto* prim_ty = node->BaseExprNode::ty.as<PrimTypeNode>();
+ TVM_FFI_DCHECK(node->ExprNode::ty.defined());
+ const auto* prim_ty = node->ExprNode::ty.as<PrimTypeNode>();
TVM_FFI_DCHECK(prim_ty != nullptr);
return prim_ty;
}
diff --git a/src/tirx/transform/flatten_buffer.cc b/src/tirx/transform/flatten_buffer.cc
index 48e7edc417..d959fb0ad8 100644
--- a/src/tirx/transform/flatten_buffer.cc
+++ b/src/tirx/transform/flatten_buffer.cc
@@ -190,7 +190,7 @@ class BufferFlattener : public arith::IRMutatorWithAnalyzer {
if (load_returns_bool) {
TVM_FFI_ICHECK_EQ(load->buffer->dtype->dtype, (DLDataType{kDLInt, 8, 1}))
<< "Expected int8 backing array for boolean tensor";
- load.CopyOnWrite()->BaseExprNode::ty = PrimType::Int(8);
+ load.CopyOnWrite()->ExprNode::ty = PrimType::Int(8);
return tvm::cast(PrimType::Bool(), load);
} else {
return load;
diff --git a/src/tirx/transform/lower_tirx_cleanup.cc b/src/tirx/transform/lower_tirx_cleanup.cc
index b1586b9aed..3637e2af42 100644
--- a/src/tirx/transform/lower_tirx_cleanup.cc
+++ b/src/tirx/transform/lower_tirx_cleanup.cc
@@ -216,7 +216,7 @@ class LayoutApplier : public arith::IRMutatorWithAnalyzer {
if (load_returns_bool) {
TVM_FFI_ICHECK_EQ(load->buffer->dtype, PrimType::Int(8))
<< "Expected int8 backing array for boolean tensor";
- load.CopyOnWrite()->BaseExprNode::ty = PrimType::Int(8);
+ load.CopyOnWrite()->ExprNode::ty = PrimType::Int(8);
return tvm::cast(PrimType::Bool(), load);
} else {
return std::move(load);
diff --git a/tests/python/relax/test_analysis_type_analysis.py b/tests/python/relax/test_analysis_type_analysis.py
index 9fd0d7a959..a10114c6fa 100644
--- a/tests/python/relax/test_analysis_type_analysis.py
+++ b/tests/python/relax/test_analysis_type_analysis.py
@@ -834,7 +834,7 @@ def test_collect_nonnegative_expressions():
[M, N],
)
- # PrimValue instances may contain negative values, and do not
+ # PrimExpr instances may contain negative values, and do not
# imply that their contents are non-negative.
tvm.ir.assert_structural_equal(
rx.analysis.collect_non_negative_expressions(func.params[3].ty),
diff --git a/tests/python/relax/test_ast_printer.py b/tests/python/relax/test_ast_printer.py
index c4fc189534..1c133b573c 100644
--- a/tests/python/relax/test_ast_printer.py
+++ b/tests/python/relax/test_ast_printer.py
@@ -563,8 +563,8 @@ def test_operators():
)
)
assert 'Op(name="relax.unique")' in foo_str
- # the sorted argument is true, so it will be a PrimValue of 1
- assert "PrimExpr(value=`T.int64(1)`)" in foo_str
+ # the sorted argument is true, so it will be a boolean PrimExpr
+ assert "PrimExpr(value=`T.bool(True)`)" in foo_str
# axis is -1
assert "PrimExpr(value=`T.int64(-1)`)" in foo_str
@@ -651,14 +651,11 @@ def test_tuple_get_item():
def test_prim_value():
- prim_value = rx.PrimValue(tirx.IntImm("int64", 1))
+ prim_value = tirx.IntImm("int64", 1)
prim_str = strip_whitespace(dump_ast(prim_value))
assert prim_str == strip_whitespace(
"""
- PrimValue(
- value=PrimExpr(value=`T.int64(1)`),
- ty=PrimType(dtype=int64)
- )
+ PrimExpr(value=`T.int64(1)`)
"""
)
diff --git a/tests/python/relax/test_bind_params.py b/tests/python/relax/test_bind_params.py
index 9959f94b05..c0a1df581e 100644
--- a/tests/python/relax/test_bind_params.py
+++ b/tests/python/relax/test_bind_params.py
@@ -130,7 +130,7 @@ def test_bind_prim_value(prim_value_dtype):
B = R.prim_value(value)
return B
- after = before.bind_params({"A": relax.PrimValue(value)})
+ after = before.bind_params({"A": value})
tvm.ir.assert_structural_equal(expected, after)
diff --git a/tests/python/relax/test_blockbuilder_core.py b/tests/python/relax/test_blockbuilder_core.py
index 34be64df5d..725ebd8219 100644
--- a/tests/python/relax/test_blockbuilder_core.py
+++ b/tests/python/relax/test_blockbuilder_core.py
@@ -540,8 +540,8 @@ def test_emit_te_prim_value():
bb = rx.BlockBuilder()
n, m = tirx.Var("n", "int64"), tirx.Var("m", "int64")
x = rx.Var("x", R.Tensor([n, m], "float32"))
- a_min = rx.PrimValue(0)
- a_max = rx.PrimValue(6)
+ a_min = tirx.IntImm("int64", 0)
+ a_max = tirx.IntImm("int64", 6)
with bb.function("rx_clip", [x]):
out = bb.emit_te(topi.clip, x, a_min, a_max)
diff --git a/tests/python/relax/test_codegen_tensorrt.py b/tests/python/relax/test_codegen_tensorrt.py
index d51fae0f5a..4c618c1a0a 100644
--- a/tests/python/relax/test_codegen_tensorrt.py
+++ b/tests/python/relax/test_codegen_tensorrt.py
@@ -396,7 +396,7 @@ def test_tensorrt_layer_norm():
def test_tensorrt_clip():
- # Regression test: Relax clip passes min/max as PrimValue arguments (Relay used a_min/a_max
+ # Regression test: Relax clip passes min/max as PrimExpr arguments (Relay used a_min/a_max
# attributes); the codegen serializes them under the op's argument names.
@tvm.script.ir_module
class Clip:
diff --git a/tests/python/relax/test_dataflow_pattern.py b/tests/python/relax/test_dataflow_pattern.py
index 80acc6c65e..0b2fc579f1 100644
--- a/tests/python/relax/test_dataflow_pattern.py
+++ b/tests/python/relax/test_dataflow_pattern.py
@@ -1618,12 +1618,15 @@ def test_iterative_rewrite_without_trivial_binding():
if len(axes) != 1:
return expr
- axis = axes[0].value
- begin = begin[0].value
- end = end[0].value
- stride = strides[0].value
+ axis = axes[0]
+ begin = begin[0]
+ end = end[0]
+ stride = strides[0]
- if stride != 1:
+ if not isinstance(axis, tirx.IntImm) or axis.value != 0:
+ return expr
+
+ if not isinstance(stride, tirx.IntImm) or stride.value != 1:
return expr
size = arg.ty.shape[0]
diff --git a/tests/python/relax/test_dataflow_rewriter.py b/tests/python/relax/test_dataflow_rewriter.py
index 965e47299e..13641bdf6e 100644
--- a/tests/python/relax/test_dataflow_rewriter.py
+++ b/tests/python/relax/test_dataflow_rewriter.py
@@ -392,10 +392,10 @@ def test_rewrite_of_arbitrary_dtype():
N = T.int64()
# TODO(Lunderberg): Improve this syntax. A Relax
- # PrimValue (e.g. `A.dtype.bits`) should be usable in any
+ # PrimExpr (e.g. `A.dtype.bits`) should be usable in any
# Relax context that accepts a `PrimExpr`. Currently,
# this requires `R.match_cast` to produce a TIR symbolic
- # variable from the Relax PrimValue.
+ # variable from the Relax PrimExpr.
bits_per_element = T.uint8()
_ = R.match_cast(
A.dtype.bits,
diff --git a/tests/python/relax/test_expr.py b/tests/python/relax/test_expr.py
index c6a1a956e0..b168dc7519 100644
--- a/tests/python/relax/test_expr.py
+++ b/tests/python/relax/test_expr.py
@@ -260,28 +260,42 @@ def test_shape_expr():
rx.ShapeExpr([m, 3])
-def test_prim_value():
- pv = rx.PrimValue(tirx.IntImm("int64", 1))
- assert pv.value.value == 1
- _check_equal(pv, rx.PrimValue(tirx.IntImm("int64", 1)))
- _check_json_roundtrip(pv)
+def test_prim_value_helper_from_python_scalar():
+ int_value = rx.prim_value(1)
+ assert isinstance(int_value, tirx.IntImm)
+ tvm.ir.assert_structural_equal(int_value.ty, tvm.ir.PrimType("int64"))
+ assert int_value.value == 1
+ np_int_value = rx.prim_value(np.int32(2))
+ assert isinstance(np_int_value, tirx.IntImm)
+ tvm.ir.assert_structural_equal(np_int_value.ty, tvm.ir.PrimType("int64"))
+ assert np_int_value.value == 2
+
+ float_value = rx.prim_value(1.0)
+ assert isinstance(float_value, tirx.FloatImm)
+ tvm.ir.assert_structural_equal(float_value.ty, tvm.ir.PrimType("float64"))
+ assert float_value.value == 1.0
+
+ np_float_value = rx.prim_value(np.float32(1.5))
+ assert isinstance(np_float_value, tirx.FloatImm)
+ tvm.ir.assert_structural_equal(np_float_value.ty, tvm.ir.PrimType("float64"))
+ assert np_float_value.value == 1.5
-def test_prim_value_with_var():
- n = tirx.Var("n", "int64")
- pv = rx.PrimValue(n)
- assert pv.value.same_as(n)
- tvm.ir.assert_structural_equal(pv.ty, tvm.ir.PrimType("int64"))
- _check_equal(pv, rx.PrimValue(n))
- _check_json_roundtrip(pv)
+def test_prim_value_helper_preserves_prim_expr():
+ float_imm = tirx.FloatImm("float32", 1.0)
+ assert rx.prim_value(float_imm).same_as(float_imm)
+ assert R.prim_value(float_imm).same_as(float_imm)
-def test_prim_value_with_expr():
n = tirx.Var("n", "int64")
- pv = rx.PrimValue(n + 1)
- tvm.ir.assert_structural_equal(pv.ty, tvm.ir.PrimType("int64"))
- _check_equal(pv, rx.PrimValue(n + 1))
- _check_json_roundtrip(pv)
+ expr = n + 1
+ assert rx.prim_value(n).same_as(n)
+ assert rx.prim_value(expr).same_as(expr)
+
+
+def test_prim_value_helper_rejects_relax_expr():
+ with pytest.raises(TypeError, match="Cannot convert"):
+ rx.prim_value(rx.Var("x"))
def test_string_imm():
diff --git a/tests/python/relax/test_expr_functor.py b/tests/python/relax/test_expr_functor.py
index d3fc8bc9fb..ede70ebd06 100644
--- a/tests/python/relax/test_expr_functor.py
+++ b/tests/python/relax/test_expr_functor.py
@@ -36,7 +36,7 @@ from tvm.relax.expr import (
GlobalVar,
If,
MatchCast,
- PrimValue,
+ PrimExpr,
SeqExpr,
ShapeExpr,
StringImm,
@@ -141,8 +141,8 @@ class ASTPrinter(PyExprVisitor):
self.visit_expr(op.tuple_value)
self.log.pop_scope()
- def visit_prim_value_(self, op: PrimValue) -> None:
- self.log.add("PrimValue")
+ def visit_prim_expr_(self, op: PrimExpr) -> None:
+ self.log.add("PrimExpr")
def visit_string_imm_(self, op: StringImm) -> None:
self.log.add("StringImm")
@@ -262,9 +262,9 @@ class ASTPostPrinterMutator(PyExprMutator):
self.log.add("TupleGetItem")
return op
- def visit_prim_value_(self, op: PrimValue) -> Expr:
+ def visit_prim_expr_(self, op: PrimExpr) -> Expr:
op = self.visit_expr_post_order(op)
- self.log.add("PrimValue")
+ self.log.add("PrimExpr")
return op
def visit_string_imm_(self, op: StringImm) -> Expr:
@@ -428,6 +428,12 @@ def test_shape_expr():
basic_check(x, "ShapeExpr", "ShapeExpr")
+def test_prim_expr():
+ basic_check(tvm.tirx.IntImm("int64", 1), "PrimExpr", "PrimExpr")
+ basic_check(tvm.tirx.FloatImm("float32", 1.0), "PrimExpr", "PrimExpr")
+ basic_check(m + n, "PrimExpr", "PrimExpr")
+
+
def test_call():
call_node = relax.op.add(x, y)
basic_check(
diff --git a/tests/python/relax/test_frontend_nn_op.py b/tests/python/relax/test_frontend_nn_op.py
index 4f4faf3caa..f40c883393 100644
--- a/tests/python/relax/test_frontend_nn_op.py
+++ b/tests/python/relax/test_frontend_nn_op.py
@@ -645,7 +645,7 @@ def test_tensor_ir_op():
# including the output tensor arguments
#
# TODO(Lunderberg): Update
- # `tvm.relax.frontend.nn.op.tensor_ir_op` to use `PrimValue`
+ # `tvm.relax.frontend.nn.op.tensor_ir_op` to use `PrimExpr`
# instead of `tir_vars`, so that the order can be consistent
# between the function definition and the arguments in
# `op.tensor_ir_op`.
diff --git a/tests/python/relax/test_op_manipulate.py b/tests/python/relax/test_op_manipulate.py
index 6f87f056df..e3168d5115 100644
--- a/tests/python/relax/test_op_manipulate.py
+++ b/tests/python/relax/test_op_manipulate.py
@@ -246,13 +246,10 @@ def test_reshape_infer_ty_inference_not_deducible():
def test_reshape_new_shape_not_tuple():
- m = tirx.Var("m", "int64")
x = relax.Var("x", R.Tensor((2, 3, 4, 5), "float32"))
with pytest.raises(TypeError):
relax.op.reshape(x, 120)
- with pytest.raises(TypeError):
- relax.op.reshape(x, m)
def test_reshape_infer_ty_new_shape_not_integer():
@@ -3448,7 +3445,7 @@ def test_one_hot_infer_ty():
i0 = relax.Var("indices", R.Tensor((3,), "int32"))
_check_inference(
bb,
- relax.op.one_hot(i0, relax.PrimValue(1.0), relax.PrimValue(0.0), 5),
+ relax.op.one_hot(i0, tirx.FloatImm("float32", 1.0), tirx.FloatImm("float32", 0.0), 5),
relax.TensorType((3, 5), "float32"),
)
@@ -3456,7 +3453,7 @@ def test_one_hot_infer_ty():
i1 = relax.Var("indices", R.Tensor((2, 2), "int32"))
_check_inference(
bb,
- relax.op.one_hot(i1, relax.PrimValue(1), relax.PrimValue(0), 3, axis=1),
+ relax.op.one_hot(i1, tirx.IntImm("int64", 1), tirx.IntImm("int64", 0), 3, axis=1),
relax.TensorType((2, 3, 2), "int64"),
)
@@ -3465,7 +3462,7 @@ def test_one_hot_infer_ty():
i2 = relax.Var("indices", R.Tensor((n,), "int32"))
_check_inference(
bb,
- relax.op.one_hot(i2, relax.PrimValue(1.0), relax.PrimValue(0.0), 4),
+ relax.op.one_hot(i2, tirx.FloatImm("float32", 1.0), tirx.FloatImm("float32", 0.0), 4),
relax.TensorType((n, 4), "float32"),
)
@@ -3473,24 +3470,30 @@ def test_one_hot_infer_ty():
i3 = relax.Var("indices", R.Tensor("int32"))
_check_inference(
bb,
- relax.op.one_hot(i3, relax.PrimValue(1.0), relax.PrimValue(0.0), 6),
+ relax.op.one_hot(i3, tirx.FloatImm("float32", 1.0), tirx.FloatImm("float32", 0.0), 6),
relax.TensorType(dtype="float32"),
)
# Test case 5: With different on_value and off_value dtypes
i3 = relax.Var("indices", R.Tensor((2, 3), "int32"))
with pytest.raises(tvm.error.InternalError):
- bb.normalize(relax.op.one_hot(i3, relax.PrimValue(1.0), relax.PrimValue(0), 5))
+ bb.normalize(
+ relax.op.one_hot(i3, tirx.FloatImm("float32", 1.0), tirx.IntImm("int64", 0), 5)
+ )
# Test case 6: With invalid indices dtype
i4 = relax.Var("indices", R.Tensor((2, 3), "float32"))
with pytest.raises(TypeError):
- bb.normalize(relax.op.one_hot(i4, relax.PrimValue(1.0), relax.PrimValue(0.0), 5))
+ bb.normalize(
+ relax.op.one_hot(i4, tirx.FloatImm("float32", 1.0), tirx.FloatImm("float32", 0.0), 5)
+ )
# Test case 7: With invalid depth
i5 = relax.Var("indices", R.Tensor((2, 3), "int32"))
with pytest.raises(tvm.error.InternalError):
- bb.normalize(relax.op.one_hot(i5, relax.PrimValue(1.0), relax.PrimValue(0.0), -1))
+ bb.normalize(
+ relax.op.one_hot(i5, tirx.FloatImm("float32", 1.0), tirx.FloatImm("float32", 0.0), -1)
+ )
if __name__ == "__main__":
diff --git a/tests/python/relax/test_relax_operators.py b/tests/python/relax/test_relax_operators.py
index ea9953d2d8..df2aecf5f4 100644
--- a/tests/python/relax/test_relax_operators.py
+++ b/tests/python/relax/test_relax_operators.py
@@ -538,7 +538,7 @@ def test_scalar_tensor_as_branch_condition(exec_mode):
def test_prim_value_as_branch_condition(exec_mode):
- """The condition may be a PrimValue"""
+ """The condition may be a PrimExpr"""
@R.function
def func(condition: R.Prim("bool")):
diff --git a/tests/python/relax/test_relax_to_pyfunc_converter.py b/tests/python/relax/test_relax_to_pyfunc_converter.py
index cbefedabbe..6139d95760 100644
--- a/tests/python/relax/test_relax_to_pyfunc_converter.py
+++ b/tests/python/relax/test_relax_to_pyfunc_converter.py
@@ -950,7 +950,7 @@ class TestDLPackAndTupleSupport:
assert torch.allclose(result, expected)
def test_packed_function_with_primvalue_args(self):
- """Test packed function calls with PrimValue arguments."""
+ """Test packed function calls with PrimExpr arguments."""
# Register a test packed function
def test_packed_func(x, axis):
@@ -973,7 +973,7 @@ class TestDLPackAndTupleSupport:
result = converted_ir_mod.pyfuncs["test_dps"](x)
expected = x # Identity function
- assert torch.allclose(result, expected), "Packed function with PrimValue args failed"
+ assert torch.allclose(result, expected), "Packed function with PrimExpr args failed"
def test_mixed_tir_and_relax_operations(self):
"""Test mixed TIR and Relax operations in a single function."""
diff --git a/tests/python/relax/test_transform_adjust_matmul_order.py b/tests/python/relax/test_transform_adjust_matmul_order.py
index 1c00ef362d..b5f3155248 100644
--- a/tests/python/relax/test_transform_adjust_matmul_order.py
+++ b/tests/python/relax/test_transform_adjust_matmul_order.py
@@ -314,28 +314,24 @@ class TestDynamicWithBatchConcrete1LHSFirst(Base):
class Before:
@R.function
def main(
- x: R.Tensor(["batch_size", 1, 16]),
- A: R.Tensor([16, "lora_r"]),
- B: R.Tensor(["lora_r", 32]),
- ) -> R.Tensor(["batch_size", 1, 32]):
- batch_size = T.int64(4)
- lora_r = T.int64(16) # noqa: F841
+ x: R.Tensor([4, 1, 16]),
+ A: R.Tensor([16, 16]),
+ B: R.Tensor([16, 32]),
+ ) -> R.Tensor([4, 1, 32]):
weight: R.Tensor([16, 32]) = R.matmul(A, B)
- out: R.Tensor([batch_size, 1, 32]) = R.matmul(x, weight)
+ out: R.Tensor([4, 1, 32]) = R.matmul(x, weight)
return out
@I.ir_module
class Expected:
@R.function
def main(
- x: R.Tensor(["batch_size", 1, 16]),
- A: R.Tensor([16, "lora_r"]),
- B: R.Tensor(["lora_r", 32]),
- ) -> R.Tensor(["batch_size", 1, 32]):
- batch_size = T.int64(4)
- lora_r = T.int64(16)
- weight: R.Tensor([batch_size, 1, lora_r]) = R.matmul(x, A)
- out: R.Tensor([batch_size, 1, 32]) = R.matmul(weight, B)
+ x: R.Tensor([4, 1, 16]),
+ A: R.Tensor([16, 16]),
+ B: R.Tensor([16, 32]),
+ ) -> R.Tensor([4, 1, 32]):
+ weight: R.Tensor([4, 1, 16]) = R.matmul(x, A)
+ out: R.Tensor([4, 1, 32]) = R.matmul(weight, B)
return out
@@ -351,28 +347,24 @@ class TestDynamicWithBatchConcrete1RHSFirst(Base):
class Before:
@R.function
def main(
- x: R.Tensor(["batch_size", 1, 16]),
- A: R.Tensor([16, "lora_r"]),
- B: R.Tensor(["lora_r", 32]),
- ) -> R.Tensor(["batch_size", 1, 32]):
- batch_size = T.int64(64)
- lora_r = T.int64(16)
- weight: R.Tensor([batch_size, 1, lora_r]) = R.matmul(x, A)
- out: R.Tensor([batch_size, 1, 32]) = R.matmul(weight, B)
+ x: R.Tensor([64, 1, 16]),
+ A: R.Tensor([16, 16]),
+ B: R.Tensor([16, 32]),
+ ) -> R.Tensor([64, 1, 32]):
+ weight: R.Tensor([64, 1, 16]) = R.matmul(x, A)
+ out: R.Tensor([64, 1, 32]) = R.matmul(weight, B)
return out
@I.ir_module
class Expected:
@R.function
def main(
- x: R.Tensor(["batch_size", 1, 16]),
- A: R.Tensor([16, "lora_r"]),
- B: R.Tensor(["lora_r", 32]),
- ) -> R.Tensor(["batch_size", 1, 32]):
- batch_size = T.int64(64)
- lora_r = T.int64(16) # noqa: F841
+ x: R.Tensor([64, 1, 16]),
+ A: R.Tensor([16, 16]),
+ B: R.Tensor([16, 32]),
+ ) -> R.Tensor([64, 1, 32]):
weight: R.Tensor([16, 32]) = R.matmul(A, B)
- out: R.Tensor([batch_size, 1, 32]) = R.matmul(x, weight)
+ out: R.Tensor([64, 1, 32]) = R.matmul(x, weight)
return out
@@ -426,28 +418,24 @@ class TestDynamicWithBatchConcrete2RHSFirst(Base):
class Before:
@R.function
def main(
- x: R.Tensor(["batch_size", 16, 1]),
- A: R.Tensor([32, "lora_r"]),
- B: R.Tensor(["lora_r", 16]),
- ) -> R.Tensor(["batch_size", 32, 1]):
- batch_size = T.int64(4)
- lora_r = T.int64(16) # noqa: F841
+ x: R.Tensor([4, 16, 1]),
+ A: R.Tensor([32, 16]),
+ B: R.Tensor([16, 16]),
+ ) -> R.Tensor([4, 32, 1]):
weight: R.Tensor([32, 16]) = R.matmul(A, B)
- out: R.Tensor([batch_size, 32, 1]) = R.matmul(weight, x)
+ out: R.Tensor([4, 32, 1]) = R.matmul(weight, x)
return out
@I.ir_module
class Expected:
@R.function
def main(
- x: R.Tensor(["batch_size", 16, 1]),
- A: R.Tensor([32, "lora_r"]),
- B: R.Tensor(["lora_r", 16]),
- ) -> R.Tensor(["batch_size", 32, 1]):
- batch_size = T.int64(4)
- lora_r = T.int64(16)
- weight: R.Tensor([batch_size, lora_r, 1]) = R.matmul(B, x)
- out: R.Tensor([batch_size, 32, 1]) = R.matmul(A, weight)
+ x: R.Tensor([4, 16, 1]),
+ A: R.Tensor([32, 16]),
+ B: R.Tensor([16, 16]),
+ ) -> R.Tensor([4, 32, 1]):
+ weight: R.Tensor([4, 16, 1]) = R.matmul(B, x)
+ out: R.Tensor([4, 32, 1]) = R.matmul(A, weight)
return out
@@ -463,28 +451,24 @@ class TestDynamicWithBatchConcrete2LHSFirst(Base):
class Before:
@R.function
def main(
- x: R.Tensor(["batch_size", 16, 1]),
- A: R.Tensor([32, "lora_r"]),
- B: R.Tensor(["lora_r", 16]),
- ) -> R.Tensor(["batch_size", 32, 1]):
- batch_size = T.int64(64)
- lora_r = T.int64(16)
- weight: R.Tensor([batch_size, lora_r, 1]) = R.matmul(B, x)
- out: R.Tensor([batch_size, 32, 1]) = R.matmul(A, weight)
+ x: R.Tensor([64, 16, 1]),
+ A: R.Tensor([32, 16]),
+ B: R.Tensor([16, 16]),
+ ) -> R.Tensor([64, 32, 1]):
+ weight: R.Tensor([64, 16, 1]) = R.matmul(B, x)
+ out: R.Tensor([64, 32, 1]) = R.matmul(A, weight)
return out
@I.ir_module
class Expected:
@R.function
def main(
- x: R.Tensor(["batch_size", 16, 1]),
- A: R.Tensor([32, "lora_r"]),
- B: R.Tensor(["lora_r", 16]),
- ) -> R.Tensor(["batch_size", 32, 1]):
- batch_size = T.int64(64)
- lora_r = T.int64(16) # noqa: F841
+ x: R.Tensor([64, 16, 1]),
+ A: R.Tensor([32, 16]),
+ B: R.Tensor([16, 16]),
+ ) -> R.Tensor([64, 32, 1]):
weight: R.Tensor([32, 16]) = R.matmul(A, B)
- out: R.Tensor([batch_size, 32, 1]) = R.matmul(weight, x)
+ out: R.Tensor([64, 32, 1]) = R.matmul(weight, x)
return out
diff --git a/tests/python/relax/test_transform_lazy_transform_params.py b/tests/python/relax/test_transform_lazy_transform_params.py
index ceadd49b84..2ed1a179d9 100644
--- a/tests/python/relax/test_transform_lazy_transform_params.py
+++ b/tests/python/relax/test_transform_lazy_transform_params.py
@@ -1109,7 +1109,7 @@ def test_set_output_callback_with_inline_const():
"""fset_output may be called for inline objects
The return tuple may contain inline leaf nodes, such as
- `relax.PrimValue` or `relax.Constant`. A call to `fset_output`
+ `PrimExpr` or `relax.Constant`. A call to `fset_output`
must be generated, even though they do not have an associated
`relax.VarBinding`.
"""
diff --git a/tests/python/relax/test_tvmscript_parser.py b/tests/python/relax/test_tvmscript_parser.py
index e42b9bf89a..2c5a6e7e7c 100644
--- a/tests/python/relax/test_tvmscript_parser.py
+++ b/tests/python/relax/test_tvmscript_parser.py
@@ -1343,13 +1343,13 @@ def test_computed_prim_value_as_branch_condition():
N = func.params[0].ty.shape[0]
if_else = func.body.blocks[0].bindings[0].value
- assert isinstance(if_else.cond, relax.PrimValue)
- tvm.ir.assert_structural_equal(N % 16 == 0, if_else.cond.value)
+ assert isinstance(if_else.cond, tvm.tirx.PrimExpr)
+ tvm.ir.assert_structural_equal(N % 16 == 0, if_else.cond)
tvm.ir.assert_structural_equal(if_else.cond.ty, R.Prim("bool"))
def test_tir_expr_as_branch_condition():
- """Syntactic sugar, wrap PrimExpr as PrimValue"""
+ """Syntactic sugar, use PrimExpr directly"""
@R.function(private=True)
def sugared(x: R.Tensor(["N"], "float32")):
@@ -1415,13 +1415,13 @@ def test_computed_prim_value_as_assert_condition():
N = func.params[0].ty.shape[0]
assert_op = func.body.blocks[0].bindings[0].value
condition = assert_op.args[0]
- assert isinstance(condition, relax.PrimValue)
- tvm.ir.assert_structural_equal(N % 16 == 0, condition.value)
+ assert isinstance(condition, tvm.tirx.PrimExpr)
+ tvm.ir.assert_structural_equal(N % 16 == 0, condition)
tvm.ir.assert_structural_equal(condition.ty, R.Prim("bool"))
def test_tir_expr_as_assert_condition():
- """Syntactic sugar, wrap PrimExpr as PrimValue"""
+ """Syntactic sugar, use PrimExpr directly"""
@R.function(pure=False, private=True)
def sugared(x: R.Tensor(["N"], "float32")):
@@ -2296,6 +2296,18 @@ def test_function_symbolic_variables_are_annotated():
tvm.ir.assert_structural_equal(inferred_ty, expected)
+def test_constant_prim_expr_alias_is_not_symbolic_declaration():
+ """Constant PrimExpr locals are constants, not declarations."""
+
+ @R.function(private=True)
+ def func(A: R.Tensor([4], "float32")):
+ extent = T.int64(4)
+ output: R.Tensor([extent], "float32") = A
+ return output
+
+ tvm.ir.assert_structural_equal(func.ret_ty.shape.values[0], T.int64(4))
+
+
def test_conditional_may_use_symbolic_variables_from_function_scope():
"""Symbolic variables from function scope may be used in branch
diff --git a/tests/python/relax/test_tvmscript_printer_relax.py b/tests/python/relax/test_tvmscript_printer_relax.py
index c9c7f1a03b..a1a7caeab4 100644
--- a/tests/python/relax/test_tvmscript_printer_relax.py
+++ b/tests/python/relax/test_tvmscript_printer_relax.py
@@ -303,8 +303,33 @@ def test_func_type():
def test_prim_value():
- obj = relax.PrimValue(1)
- _assert_print(obj, "R.prim_value(1)")
+ obj = tirx.IntImm("int64", 1)
+ _assert_print(obj, "T.int64(1)")
+
+ @R.function
+ def func() -> R.Prim("int64"):
+ return R.prim_value(1)
+
+ _assert_print(
+ func,
+ """
+# from tvm.script import tirx as T
+# from tvm.tirx.layout import Axis
+# from tvm.script import relax as R
+
+@R.function
+def func() -> T.int64:
+ return 1""",
+ )
+
+ @R.function
+ def float_func() -> R.Prim("float32"):
+ return R.prim_value(T.float32(1.0))
+
+ float_script = float_func.script(verbose_expr=True)
+ assert "R.prim_value" not in float_script
+ assert "return T.float32(" in float_script
+ tvm.ir.assert_structural_equal(tvm.script.from_source(float_script), float_func)
def test_string_imm():
diff --git a/tests/python/relax/test_utils.py b/tests/python/relax/test_utils.py
index 1a15484ded..9ee05b7fdd 100644
--- a/tests/python/relax/test_utils.py
+++ b/tests/python/relax/test_utils.py
@@ -265,7 +265,6 @@ def test_structural_equal_with_distinct_recursive_lambda_function():
"bindings[0]",
"value",
"cond",
- "value",
"a",
]
diff --git a/tests/python/relax/test_vm_build.py b/tests/python/relax/test_vm_build.py
index 1f7904ca06..538388cc47 100644
--- a/tests/python/relax/test_vm_build.py
+++ b/tests/python/relax/test_vm_build.py
@@ -615,9 +615,9 @@ def test_vm_relax_multiple_symbolic_prim_value(exec_mode):
@pytest.mark.xfail(reason="Current support for R.Prim with known value is primarily for int64")
@pytest.mark.parametrize("exec_mode", EXEC_MODE)
def test_vm_relax_prim_value_fp32(exec_mode):
- """A PrimValue may be R.prim('float32')
+ """A PrimExpr may be R.prim('float32')
- Unlike shape tuples, which must contain int64, a PrimValue may be
+ Unlike shape tuples, which must contain int64, a PrimExpr may be
any type that can be represented as a single primitive value.
"""
diff --git a/tests/python/relax/test_vm_codegen_only.py b/tests/python/relax/test_vm_codegen_only.py
index 3597b407bb..5c83f5dbf3 100644
--- a/tests/python/relax/test_vm_codegen_only.py
+++ b/tests/python/relax/test_vm_codegen_only.py
@@ -286,14 +286,14 @@ def test_shape_check_builtin(exec_mode):
@pytest.mark.parametrize("exec_mode", EXEC_MODE)
def test_prim_value(exec_mode):
@tvm.script.ir_module
- class TestVMPrimValue:
+ class TestVMPrimExpr:
@R.function
def main():
R.func_attr({"global_symbol": "main"})
ret = R.prim_value(T.int64(1))
return ret
- mod = TestVMPrimValue
+ mod = TestVMPrimExpr
target = tvm.target.Target("llvm", host="llvm")
ex = codegen(mod, target, exec_mode)
vm = relax.VirtualMachine(ex, tvm.cpu())