This is an automated email from the ASF dual-hosted git repository.

csullivan pushed a commit to branch unity
in repository https://gitbox.apache.org/repos/asf/tvm.git


The following commit(s) were added to refs/heads/unity by this push:
     new a0e0390f0b [Unity] RealizeVDevice pass (#15636)
a0e0390f0b is described below

commit a0e0390f0ba9ee7dc14a8cc1192d55208c0ea0bf
Author: Yong Wu <[email protected]>
AuthorDate: Tue Sep 5 11:00:57 2023 -0700

    [Unity] RealizeVDevice pass (#15636)
    
    This pr adds RealizeVDevice pass as mentioned in #15101
    
    * [Unity] RealizeVDevice pass
    
    * Replace hint_on_device with to_vdevice in pass
    
    * Add sugar to to_vdevice
---
 include/tvm/relax/attrs/op.h                       |  10 +
 include/tvm/relax/transform.h                      |   6 +
 python/tvm/relax/op/base.py                        |  22 +-
 python/tvm/relax/transform/transform.py            |  12 +
 python/tvm/script/ir_builder/relax/ir.py           |  64 +++-
 src/relax/op/op.cc                                 |  40 ++-
 src/relax/transform/realize_vdevice.cc             | 296 ++++++++++++++++++
 src/script/printer/relax/call.cc                   |  51 ++++
 tests/python/relax/test_relax_operators.py         |  12 +-
 .../python/relax/test_transform_realize_vdevice.py | 330 +++++++++++++++++++++
 .../relax/test_tvmscript_parser_op_manipulate.py   |  29 +-
 11 files changed, 856 insertions(+), 16 deletions(-)

diff --git a/include/tvm/relax/attrs/op.h b/include/tvm/relax/attrs/op.h
index f33f3a9701..e419a42111 100644
--- a/include/tvm/relax/attrs/op.h
+++ b/include/tvm/relax/attrs/op.h
@@ -65,6 +65,16 @@ struct ToVDeviceAttrs : public 
tvm::AttrsNode<ToVDeviceAttrs> {
   }
 };  // struct ToVDeviceAttrs
 
+/*! \brief Attributes used in hint_on_device */
+struct HintOnDeviceAttrs : public tvm::AttrsNode<HintOnDeviceAttrs> {
+  int32_t dev_type;
+  int32_t dev_id;
+  TVM_DECLARE_ATTRS(HintOnDeviceAttrs, "relax.attrs.HintOnDeviceAttrs") {
+    TVM_ATTR_FIELD(dev_type).describe("The device type where the data is 
supposed to be executed.");
+    TVM_ATTR_FIELD(dev_id).describe("The device id.");
+  }
+};  // struct HintOnDeviceAttrs
+
 }  // namespace relax
 }  // namespace tvm
 
diff --git a/include/tvm/relax/transform.h b/include/tvm/relax/transform.h
index a6ef9ad7ad..0922126b78 100644
--- a/include/tvm/relax/transform.h
+++ b/include/tvm/relax/transform.h
@@ -242,6 +242,12 @@ TVM_DLL Pass FoldDataflowBlockOutput();
  */
 TVM_DLL Pass LegalizeOps(Optional<Map<String, PackedFunc>> cmap, bool 
enable_warning = false);
 
+/*!
+ * \brief Propagate virtual device information.
+ * \return The Pass.
+ */
+TVM_DLL Pass RealizeVDevice();
+
 /*!
  * \brief Lift transformation of the parameters of a function.
  *
diff --git a/python/tvm/relax/op/base.py b/python/tvm/relax/op/base.py
index 1d49c00ea8..ea6fd0a651 100644
--- a/python/tvm/relax/op/base.py
+++ b/python/tvm/relax/op/base.py
@@ -702,7 +702,7 @@ def to_vdevice(data, dst_vdevice) -> Expr:
     data : Expr
         The tensor to be copied.
 
-    dst_device : Union[:py:class:`Device`, str]
+    dst_device : VDevice
         The destination device where the data is copied to.
 
     Returns
@@ -711,3 +711,23 @@ def to_vdevice(data, dst_vdevice) -> Expr:
         The copied result.
     """
     return _ffi_api.to_vdevice(data, dst_vdevice)  # type: ignore
+
+
+def hint_on_device(data, dst_vdevice) -> Expr:
+    """It provides a hint specifying the device on which the input data should 
be executed.
+    This hint is utilized by RealizeVDevice to propagate the virtual device."
+
+    Parameters
+    ----------
+    data : Expr
+        The tensor to be copied.
+
+    dst_device : VDevice
+        The destination device where the data is supposed to be executed.
+
+    Returns
+    -------
+    result : Expr
+        The result.
+    """
+    return _ffi_api.hint_on_device(data, dst_vdevice)  # type: ignore
diff --git a/python/tvm/relax/transform/transform.py 
b/python/tvm/relax/transform/transform.py
index 5f107315a5..aff73167e4 100644
--- a/python/tvm/relax/transform/transform.py
+++ b/python/tvm/relax/transform/transform.py
@@ -829,6 +829,18 @@ def LegalizeOps(
     return _ffi_api.LegalizeOps(customize_legalize_map, enable_warning)  # 
type: ignore
 
 
+def RealizeVDevice() -> tvm.ir.transform.Pass:
+    """Propagate virtual device information.
+
+    Returns
+    -------
+    ret : tvm.transform.Pass
+        The registered pass
+    """
+
+    return _ffi_api.RealizeVDevice()  # type: ignore
+
+
 def MetaScheduleApplyDatabase(
     work_dir: Optional[str] = None, enable_warning: bool = False
 ) -> tvm.ir.transform.Pass:
diff --git a/python/tvm/script/ir_builder/relax/ir.py 
b/python/tvm/script/ir_builder/relax/ir.py
index 8aff0960dc..5c53836851 100644
--- a/python/tvm/script/ir_builder/relax/ir.py
+++ b/python/tvm/script/ir_builder/relax/ir.py
@@ -24,8 +24,8 @@ from typing import Any, Dict, List, Optional, Tuple, Union, 
Callable
 
 import tvm
 from tvm import DataType, relax
-from tvm.ir import PrimExpr
-from ..ir import decl_function
+from tvm.ir import PrimExpr, VDevice
+from ..ir import decl_function, lookup_vdevice
 from tvm.relax import Call, Expr, ExternFunc, TupleGetItem, ShapeExpr, Var, 
VarBinding, const
 from tvm.relax.utils import gen_call_tir_inputs
 
@@ -81,6 +81,7 @@ from tvm.relax.op import (
     grad,
     greater,
     greater_equal,
+    hint_on_device,
     image,
     invoke_closure,
     invoke_pure_closure,
@@ -140,7 +141,6 @@ from tvm.relax.op import (
     tanh,
     erf,
     tile,
-    to_vdevice,
     tril,
     triu,
     unique,
@@ -152,6 +152,22 @@ from tvm.relax.op import (
     nn,
     ccl,
 )
+
+from tvm.runtime.ndarray import (
+    cpu,
+    cuda,
+    device,
+    gpu,
+    rocm,
+    opencl,
+    metal,
+    vpi,
+    vulkan,
+    ext_dev,
+    hexagon,
+    webgpu,
+)
+
 from tvm.relax.op.builtin import stop_lift_params
 from tvm.relax.struct_info import StructInfo
 from tvm.relax.utils import args_converter
@@ -167,6 +183,35 @@ py_tuple = tuple
 py_str = str
 
 
+################################ Device ################################
+
+
+def to_vdevice(data: Expr, dst_vdevice: Union[py_str, VDevice]) -> Expr:
+    """Copy data to the destination device.
+
+    Parameters
+    ----------
+    data : Expr
+        The tensor to be copied.
+
+    dst_device : Union[py_str, VDevice]
+        The destination device where the data is copied to.
+
+    Returns
+    -------
+    result : Expr
+        The copied result.
+    """
+    if isinstance(dst_vdevice, py_str):
+        if ":" in dst_vdevice:
+            split_vdev = dst_vdevice.split(":")
+            dst_vdevice = lookup_vdevice(split_vdev[0], int(split_vdev[1]))
+        else:
+            dst_vdevice = lookup_vdevice(dst_vdevice, 0)
+
+    return tvm.relax.op.to_vdevice(data, dst_vdevice)
+
+
 ############################### Function ################################
 
 
@@ -617,10 +662,13 @@ __all__ = [
     "cos",
     "cosh",
     "const",
+    "cpu",
+    "cuda",
     "cumsum",
     "einsum",
     "scatter_elements",
     "dataflow",
+    "device",
     "divide",
     "dtype",
     "emit",
@@ -631,6 +679,7 @@ __all__ = [
     "ewise_fma",
     "exp",
     "expand_dims",
+    "ext_dev",
     "flatten",
     "flip",
     "floor",
@@ -642,9 +691,12 @@ __all__ = [
     "func_ret_struct_info",
     "func_ret_value",
     "function",
+    "gpu",
     "grad",
     "greater",
     "greater_equal",
+    "hexagon",
+    "hint_on_device",
     "image",
     "invoke_closure",
     "invoke_pure_closure",
@@ -666,6 +718,7 @@ __all__ = [
     "maximum",
     "mean",
     "memory",
+    "metal",
     "min",
     "minimum",
     "multiply",
@@ -674,6 +727,7 @@ __all__ = [
     "null_value",
     "ones",
     "ones_like",
+    "opencl",
     "output",
     "permute_dims",
     "power",
@@ -684,6 +738,7 @@ __all__ = [
     "reshape",
     "tensor_to_shape",
     "shape_to_tensor",
+    "rocm",
     "round",
     "rsqrt",
     "shape",
@@ -716,6 +771,9 @@ __all__ = [
     "unique",
     "variance",
     "vm",
+    "vpi",
+    "vulkan",
+    "webgpu",
     "where",
     "wrap_param",
     "zeros",
diff --git a/src/relax/op/op.cc b/src/relax/op/op.cc
index 1f4f7d5c34..326a219ed5 100644
--- a/src/relax/op/op.cc
+++ b/src/relax/op/op.cc
@@ -873,7 +873,12 @@ StructInfo InferToVDeviceStructInfo(const Call& call, 
const BlockBuilder& ctx) {
   ICHECK(call->args.size() == 1);
   ICHECK(call->args[0]->struct_info_.defined());
   TensorStructInfo data_sinfo = GetUnaryInputTensorStructInfo(call, ctx);
-  return data_sinfo;
+  auto attrs = call->attrs.as<ToVDeviceAttrs>();
+  VDevice vdev = attrs->dst_vdevice;
+  if (data_sinfo->shape.defined()) {
+    return TensorStructInfo(data_sinfo->shape.value(), data_sinfo->dtype, 
vdev, data_sinfo->span);
+  }
+  return TensorStructInfo(data_sinfo->dtype, data_sinfo->ndim, vdev, 
data_sinfo->span);
 }
 
 RELAY_REGISTER_OP("relax.to_vdevice")
@@ -883,16 +888,41 @@ RELAY_REGISTER_OP("relax.to_vdevice")
     .set_attr<FInferStructInfo>("FInferStructInfo", InferToVDeviceStructInfo)
     .set_attr<Bool>("FPurity", Bool(true));
 
-Expr MakeToVDevice(Expr data, VDevice dst_vdevice) {
+Expr MakeToVDevice(Expr data, VDevice dst_vdev) {
   static const Op& op = Op::Get("relax.to_vdevice");
-  // TODO(@yongwww): replace Attr with TensorStructInfo
   ObjectPtr<ToVDeviceAttrs> attrs = make_object<ToVDeviceAttrs>();
-  attrs->dst_vdevice = dst_vdevice;
-
+  attrs->dst_vdevice = dst_vdev;
   return Call(op, {data}, Attrs(attrs), {});
 }
 
 TVM_REGISTER_GLOBAL("relax.op.to_vdevice").set_body_typed(MakeToVDevice);
 
+// hint_on_device
+TVM_REGISTER_NODE_TYPE(HintOnDeviceAttrs);
+
+StructInfo InferHintOnDeviceStructInfo(const Call& call, const BlockBuilder& 
ctx) {
+  ICHECK(call->args.size() == 1);
+  ICHECK(call->args[0]->struct_info_.defined());
+  TensorStructInfo data_sinfo = GetUnaryInputTensorStructInfo(call, ctx);
+  return data_sinfo;
+}
+
+RELAY_REGISTER_OP("relax.hint_on_device")
+    .set_num_inputs(1)
+    .set_attrs_type<HintOnDeviceAttrs>()
+    .add_argument("data", "Expr", "The input expression")
+    .set_attr<FInferStructInfo>("FInferStructInfo", 
InferHintOnDeviceStructInfo)
+    .set_attr<Bool>("FPurity", Bool(true));
+
+Expr MakeHintOnDevice(Expr data, Device device) {
+  static const Op& op = Op::Get("relax.hint_on_device");
+  ObjectPtr<HintOnDeviceAttrs> attrs = make_object<HintOnDeviceAttrs>();
+  attrs->dev_type = static_cast<int32_t>(device.device_type);
+  attrs->dev_id = device.device_id;
+  return Call(op, {data}, Attrs(attrs), {});
+}
+
+TVM_REGISTER_GLOBAL("relax.op.hint_on_device").set_body_typed(MakeHintOnDevice);
+
 }  // namespace relax
 }  // namespace tvm
diff --git a/src/relax/transform/realize_vdevice.cc 
b/src/relax/transform/realize_vdevice.cc
new file mode 100644
index 0000000000..ec02efa996
--- /dev/null
+++ b/src/relax/transform/realize_vdevice.cc
@@ -0,0 +1,296 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/*!
+ * \file tvm/relax/transform/realize_vdevice.cc
+ * \brief Propagate virtual device information.
+ */
+#include <tvm/relax/analysis.h>
+#include <tvm/relax/attrs/op.h>
+#include <tvm/relax/expr_functor.h>
+#include <tvm/relax/transform.h>
+
+namespace tvm {
+namespace relax {
+
+void UpdateTensorStructInfo(Expr expr, StructInfo struct_info) {
+  if (auto* tensor_sinfo = expr->struct_info_.as<TensorStructInfoNode>()) {
+    auto* new_tensor_sinfo = struct_info.as<TensorStructInfoNode>();
+    if (new_tensor_sinfo != nullptr && new_tensor_sinfo->vdevice.defined() &&
+        !tensor_sinfo->vdevice.defined()) {
+      expr->struct_info_ = struct_info;
+      expr->checked_type_ = GetStaticType(struct_info);
+    }
+  }
+}
+
+void AddVDeviceToStuctInfo(Expr expr, VDevice vdevice) {
+  auto* tinfo = GetStructInfoAs<TensorStructInfoNode>(expr);
+  if (tinfo != nullptr) {
+    if (tinfo->shape.defined()) {
+      UpdateTensorStructInfo(
+          expr, TensorStructInfo(tinfo->shape.value(), tinfo->dtype, vdevice, 
tinfo->span));
+    } else {
+      UpdateTensorStructInfo(expr,
+                             TensorStructInfo(tinfo->dtype, tinfo->ndim, 
vdevice, tinfo->span));
+    }
+  }
+}
+
+class VDeviceRealizer : public ExprMutator {
+ public:
+  explicit VDeviceRealizer(const IRModule& mod) : ExprMutator(mod), 
mod_(std::move(mod)) {}
+
+  IRModule Run() {
+    for (const auto& [gv, func] : mod_->functions) {
+      if (func->IsInstance<FunctionNode>()) {
+        auto updated_func = Downcast<Function>(this->VisitExpr(func));
+        builder_->UpdateFunction(gv, Downcast<BaseFunc>(updated_func));
+      }
+    }
+    return builder_->GetContextIRModule();
+  }
+
+ private:
+  using ExprMutator::VisitExpr_;
+
+  void AddToVDeviceMap(Expr expr, VDevice vdevice) {
+    ICHECK((vdevice_map_.count(expr) == 0) || (vdevice_map_[expr] == vdevice))
+        << "Conflicted vdevice found.";
+    vdevice_map_.Set(expr, vdevice);
+  }
+
+  Expr VisitExpr(const Expr& expr) {
+    auto visited_expr = ExprMutator::VisitExpr(expr);
+    if (vdevice_map_.count(visited_expr)) {
+      AddVDeviceToStuctInfo(visited_expr, vdevice_map_[visited_expr]);
+    }
+    return visited_expr;
+  }
+
+  Expr VisitExpr_(const FunctionNode* op) final {
+    Function func = GetRef<Function>(op);
+    auto* finfo = GetStructInfoAs<FuncStructInfoNode>(func);
+    if (finfo != nullptr) {
+      StructInfo ret = finfo->ret;
+      auto* tinfo = finfo->ret.as<TensorStructInfoNode>();
+      if (tinfo != nullptr && tinfo->vdevice.defined()) {
+        AddToVDeviceMap(op->body, tinfo->vdevice.value());
+      }
+    }
+    Function visited_func = Downcast<Function>(this->VisitExprPostOrder_(op));
+    return visited_func;
+  }
+
+  Expr VisitExpr_(const SeqExprNode* op) final {
+    SeqExpr seq_expr = GetRef<SeqExpr>(op);
+    if (vdevice_map_.count(seq_expr)) {
+      AddToVDeviceMap(seq_expr->body, vdevice_map_[seq_expr]);
+    }
+    SeqExpr visited_seqexpr = Downcast<SeqExpr>(this->VisitExprPostOrder_(op));
+    return visited_seqexpr;
+  }
+
+  BindingBlock VisitBindingBlock_(const BindingBlockNode* block) {
+    builder_->BeginBindingBlock();
+    for (size_t i = block->bindings.size(); i > 0; --i) {
+      this->VisitBinding(block->bindings[i - 1]);
+    }
+    for (size_t i = bindings_.size(); i > 0; --i) {
+      builder_->EmitNormalized(bindings_[i - 1]);
+    }
+    bindings_.clear();
+    return builder_->EndBlock();
+  }
+
+  BindingBlock VisitBindingBlock_(const DataflowBlockNode* block) {
+    builder_->BeginDataflowBlock();
+    for (size_t i = block->bindings.size(); i > 0; --i) {
+      this->VisitBinding(block->bindings[i - 1]);
+    }
+    for (size_t i = bindings_.size(); i > 0; --i) {
+      builder_->EmitNormalized(bindings_[i - 1]);
+    }
+    bindings_.clear();
+    return builder_->EndBlock();
+  }
+
+  void VisitBinding_(const VarBindingNode* binding) {
+    if (vdevice_map_.count(binding->var)) {
+      AddToVDeviceMap(binding->value, vdevice_map_[binding->var]);
+      AddVDeviceToStuctInfo(binding->var, vdevice_map_[binding->var]);
+    }
+    auto* tinfo = GetStructInfoAs<TensorStructInfoNode>(binding->var);
+    if (tinfo != nullptr && tinfo->vdevice.defined()) {
+      AddToVDeviceMap(binding->value, tinfo->vdevice.value());
+    }
+    UpdateTensorStructInfo(binding->value, GetStructInfo(binding->var));
+    Expr new_value = this->VisitExpr(binding->value);
+    if (!binding->var->struct_info_.defined()) {
+      UpdateTensorStructInfo(binding->var, GetStructInfo(new_value));
+    }
+
+    if (new_value.same_as(binding->value)) {
+      bindings_.push_back(GetRef<VarBinding>(binding));
+    } else {
+      bindings_.push_back(VarBinding(binding->var, new_value));
+    }
+  }
+
+  Expr VisitExpr_(const CallNode* call) final {
+    // Record the vdevice information of each arguments of call
+    if (auto* sinfo = call->struct_info_.as<TensorStructInfoNode>()) {
+      if (sinfo->vdevice.defined() && call->op != to_vdevice_op_) {
+        Array<Expr> call_args;
+        for (Expr arg : call->args) {
+          AddToVDeviceMap(arg, sinfo->vdevice.value());
+        }
+      }
+    }
+    return Downcast<Call>(ExprMutator::VisitExpr_(call));
+  }
+
+  /*! \brief The context IRModule. */
+  IRModule mod_;
+  /*! \brief The bindings in reverse ordering. */
+  Array<Binding> bindings_;
+  /*! \brief The virtual device map. */
+  Map<Expr, VDevice> vdevice_map_;
+
+  const Op& to_vdevice_op_ = Op::Get("relax.to_vdevice");
+};
+
+class HintOnDeviceRemover : public ExprMutator {
+ public:
+  explicit HintOnDeviceRemover(const IRModule& mod) : ExprMutator(mod), 
mod_(std::move(mod)) {}
+
+  IRModule Run() {
+    for (const auto& [gv, func] : mod_->functions) {
+      if (func->IsInstance<FunctionNode>()) {
+        auto updated_func = Downcast<Function>(this->VisitExpr(func));
+        builder_->UpdateFunction(gv, Downcast<BaseFunc>(updated_func));
+      }
+    }
+    return builder_->GetContextIRModule();
+  }
+
+ private:
+  using ExprMutator::VisitExpr_;
+
+  void AddToVDeviceMap(Expr expr, VDevice vdevice) {
+    ICHECK((vdevice_map_.count(expr) == 0) || (vdevice_map_[expr] == vdevice))
+        << "Conflicted vdevice found.";
+    vdevice_map_.Set(expr, vdevice);
+  }
+
+  VDevice LookupVDevice(int32_t device_type, int32_t device_id) {
+    Array<GlobalInfo> vdevices = mod_->global_infos["vdevice"];
+    if (vdevices.empty() || device_id < 0 || static_cast<size_t>(device_id) >= 
vdevices.size()) {
+      LOG(FATAL) << "ValueError: The target VDevice in the GlobalInfos was not 
found.";
+    }
+    for (auto vdev : vdevices) {
+      auto vdevice = Downcast<VDevice>(vdev);
+      int dev_type = vdevice->target->GetTargetDeviceType();
+      if (dev_type == device_type && vdevice->vdevice_id == device_id) {
+        return vdevice;
+      }
+    }
+    LOG(WARNING) << "The specified device was not found in the global_infos";
+    return VDevice();
+  }
+
+  Expr VisitExpr(const Expr& expr) {
+    auto visited_expr = ExprMutator::VisitExpr(expr);
+    if (vdevice_map_.count(visited_expr)) {
+      AddVDeviceToStuctInfo(visited_expr, vdevice_map_[visited_expr]);
+    }
+    return visited_expr;
+  }
+
+  void VisitBinding_(const VarBindingNode* binding) {
+    Expr new_value = this->VisitExpr(binding->value);
+    UpdateTensorStructInfo(binding->var, GetStructInfo(new_value));
+    if (new_value.same_as(binding->value)) {
+      builder_->EmitNormalized(GetRef<VarBinding>(binding));
+    } else {
+      builder_->EmitNormalized(VarBinding(binding->var, new_value));
+    }
+  }
+
+  Expr VisitExpr_(const CallNode* call) final {
+    // Replace hint_on_device with to_vdevice
+    if (call->op == hint_on_device_op_) {
+      // Find out the vdevice from global_infos
+      Expr data = call->args[0];
+      auto attrs = call->attrs.as<HintOnDeviceAttrs>();
+      int32_t device_type = attrs->dev_type;
+      int32_t device_id = attrs->dev_id;
+      VDevice dst_vdev = LookupVDevice(device_type, device_id);
+      // Insert to_vdevice if input are on different device
+      auto* tinfo = GetStructInfoAs<TensorStructInfoNode>(data);
+      if (tinfo != nullptr) {
+        if (!tinfo->vdevice.defined()) {
+          // Remove hint_on_device
+          AddVDeviceToStuctInfo(data, dst_vdev);
+          AddToVDeviceMap(data, dst_vdev);
+          return data;
+        } else if (tinfo->vdevice.value() != dst_vdev) {
+          // Call to_vdevice
+          ObjectPtr<ToVDeviceAttrs> attrs = make_object<ToVDeviceAttrs>();
+          attrs->dst_vdevice = dst_vdev;
+          auto new_call = Call(to_vdevice_op_, {data}, Attrs(attrs), {});
+          AddToVDeviceMap(new_call, dst_vdev);
+          return new_call;
+        }
+      }
+    }
+
+    auto visited_call = ExprMutator::VisitExpr_(call);
+    visited_call->struct_info_ = NullOpt;
+    return builder_->Normalize(visited_call);
+  }
+
+  /*! \brief The context IRModule. */
+  IRModule mod_;
+  /*! \brief The virtual device map. */
+  Map<Expr, VDevice> vdevice_map_;
+
+  const Op& hint_on_device_op_ = Op::Get("relax.hint_on_device");
+  const Op& to_vdevice_op_ = Op::Get("relax.to_vdevice");
+};
+
+namespace transform {
+
+Pass RealizeVDevice() {
+  runtime::TypedPackedFunc<IRModule(IRModule, PassContext)> pass_func = 
[=](IRModule mod,
+                                                                            
PassContext pc) {
+    IRModule new_mod = HintOnDeviceRemover(mod).Run();
+    return VDeviceRealizer(new_mod).Run();
+  };
+  return CreateModulePass(/*pass_function=*/pass_func,
+                          /*opt_level=*/0,
+                          /*pass_name=*/"RealizeVDevice",
+                          /*required=*/{});
+}
+
+TVM_REGISTER_GLOBAL("relax.transform.RealizeVDevice").set_body_typed(RealizeVDevice);
+
+}  // namespace transform
+}  // namespace relax
+}  // namespace tvm
diff --git a/src/script/printer/relax/call.cc b/src/script/printer/relax/call.cc
index 2fa289e069..dc57ca3184 100644
--- a/src/script/printer/relax/call.cc
+++ b/src/script/printer/relax/call.cc
@@ -184,6 +184,49 @@ Optional<ExprDoc> PrintAssertOp(const relax::Call& n, 
const ObjectPath& n_p, con
   return Relax(d, "assert_op")->Call(args, {"format"}, {second_arg});
 }
 
+Optional<ExprDoc> PrintHintOnDevice(const relax::Call& n, const ObjectPath& 
n_p,
+                                    const IRDocsifier& d) {
+  static const Op& hint_on_device_op = Op::Get("relax.hint_on_device");
+  if (!n->op.same_as(hint_on_device_op)) {
+    return NullOpt;
+  }
+  Array<ExprDoc> args;
+
+  args.push_back(PrintCallee(n->args[0], n_p->Attr("args")->ArrayIndex(0), d));
+  Array<String> kwargs_keys;
+  Array<ExprDoc> kwargs_values;
+  ICHECK(n->attrs.defined());
+  if (n->attrs.as<relax::HintOnDeviceAttrs>()) {
+    AttrPrinter printer(n_p->Attr("attrs"), d, &kwargs_keys, &kwargs_values);
+    const_cast<BaseAttrsNode*>(n->attrs.get())->VisitAttrs(&printer);
+    args.push_back(Relax(d, "device")->Call({}, kwargs_keys, kwargs_values));
+  }
+  return Relax(d, "hint_on_device")->Call(args);
+}
+
+Optional<ExprDoc> PrintToVDevice(const relax::Call& n, const ObjectPath& n_p,
+                                 const IRDocsifier& d) {
+  static const Op& to_vdevice_op = Op::Get("relax.to_vdevice");
+  if (!n->op.same_as(to_vdevice_op)) {
+    return NullOpt;
+  }
+  Array<ExprDoc> args;
+
+  args.push_back(PrintCallee(n->args[0], n_p->Attr("args")->ArrayIndex(0), d));
+  Array<String> kwargs_keys;
+  Array<ExprDoc> kwargs_values;
+  ICHECK(n->attrs.defined());
+  if (const auto* attrs = n->attrs.as<relax::ToVDeviceAttrs>()) {
+    VDevice vdev = attrs->dst_vdevice;
+    std::string dev_kind = vdev->target->kind->name;
+    int dev_index = FindVDeviceIndexByTargetKind(vdev, d);
+    kwargs_keys.push_back("dst_vdevice");
+    kwargs_values.push_back(
+        LiteralDoc::Str(dev_kind + ":" + std::to_string(dev_index), 
n_p->Attr("dst_vdevice")));
+  }
+  return Relax(d, "to_vdevice")->Call(args, kwargs_keys, kwargs_values);
+}
+
 Optional<ExprDoc> PrintRelaxPrint(const relax::Call& n, const ObjectPath& n_p,
                                   const IRDocsifier& d) {
   static const Op& print_op = Op::Get("relax.print");
@@ -214,6 +257,14 @@ TVM_STATIC_IR_FUNCTOR(IRDocsifier, vtable)
           if (Optional<ExprDoc> doc = PrintAssertOp(n, n_p, d)) {
             return doc.value();
           }
+          // Special case: hint_on_device
+          if (Optional<ExprDoc> doc = PrintHintOnDevice(n, n_p, d)) {
+            return doc.value();
+          }
+          // Special case: to_vdevice
+          if (Optional<ExprDoc> doc = PrintToVDevice(n, n_p, d)) {
+            return doc.value();
+          }
           // Special case: print
           if (Optional<ExprDoc> doc = PrintRelaxPrint(n, n_p, d)) {
             return doc.value();
diff --git a/tests/python/relax/test_relax_operators.py 
b/tests/python/relax/test_relax_operators.py
index e0904477d4..06a319abb3 100644
--- a/tests/python/relax/test_relax_operators.py
+++ b/tests/python/relax/test_relax_operators.py
@@ -23,7 +23,7 @@ import tvm
 import tvm.testing
 from tvm import relax
 from tvm._ffi.base import TVMError
-from tvm.script import relax as R, tir as T
+from tvm.script import ir as I, relax as R, tir as T
 
 
 @tvm.script.ir_module
@@ -43,7 +43,6 @@ def run_cpu(mod, func_name, *input):
 
 
 def test_unique():
-
     # TODO(prakalp): also add test for compiling and running on cuda device.
     data_numpy = np.random.randint(0, 16, (16, 16))
     data = tvm.nd.array(data_numpy)
@@ -270,12 +269,19 @@ def test_op_to_device():
 def test_op_to_vdevice():
     @tvm.script.ir_module
     class ToVDevice:
+        I.module_global_infos({"vdevice": [I.vdevice("llvm")]})
+
         @R.function
         def to_vdev(x: R.Tensor((3, 4), "float32")):
             dst_vdev = tvm.ir.VDevice("llvm", 0, "global")
-            ret = R.to_vdevice(x, dst_vdev)
+            ret = R.to_vdevice(x, "llvm")
             return ret
 
+    np.random.seed(0)
+    arr = np.random.rand(3, 4).astype("float32")
+    copy_found = run_cpu(ToVDevice, "to_vdev", tvm.nd.array(arr))
+    assert (copy_found.numpy() == arr).all()
+
 
 if __name__ == "__main__":
     tvm.testing.main()
diff --git a/tests/python/relax/test_transform_realize_vdevice.py 
b/tests/python/relax/test_transform_realize_vdevice.py
new file mode 100644
index 0000000000..f8d99eb3b5
--- /dev/null
+++ b/tests/python/relax/test_transform_realize_vdevice.py
@@ -0,0 +1,330 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Test eliminate common subexpr pass"""
+import tvm
+import tvm.testing
+from tvm.ir import VDevice
+from tvm.relax.transform import RealizeVDevice
+from tvm.script.parser import ir as I, relax as R, tir as T
+
+
+def verify(input, expected):
+    tvm.ir.assert_structural_equal(RealizeVDevice()(input), expected)
+
+
+vdevices = [
+    VDevice("llvm"),
+    VDevice("cuda", 0),
+    VDevice("metal", 0, "global"),
+    VDevice("cuda -arch=sm_80", 0),
+]
+
+
+def test_dataflow_binding():
+    @I.ir_module
+    class Input:
+        I.module_attrs({"attr": 10})
+        I.module_global_infos(
+            {
+                "vdevice": [
+                    I.vdevice("llvm"),
+                    I.vdevice("cuda", 0),
+                    I.vdevice("metal", 0, "global"),
+                    I.vdevice("cuda -arch=sm_80", 0),
+                ]
+            }
+        )
+
+        @R.function
+        def foo(
+            x: R.Tensor((2, 3), "float32"),
+            y: R.Tensor((2, 3), "float32"),
+            z: R.Tensor((2, 3), "float32"),
+        ) -> R.Tensor((2, 3), "float32"):
+            with R.dataflow():
+                x1 = x
+                y1 = y
+                x2 = x1
+                y2 = y1
+                lv0: R.Tensor((2, 3), "float32", "llvm") = R.add(x2, y2)
+                gv: R.Tensor((2, 3), "float32", "llvm") = R.multiply(lv0, z)
+                R.output(gv)
+            return gv
+
+    @I.ir_module
+    class Expect:
+        I.module_attrs({"attr": 10})
+        I.module_global_infos(
+            {
+                "vdevice": [
+                    I.vdevice("llvm"),
+                    I.vdevice("cuda", 0),
+                    I.vdevice("metal", 0, "global"),
+                    I.vdevice("cuda -arch=sm_80", 0),
+                ]
+            }
+        )
+
+        @R.function
+        def foo(
+            x: R.Tensor((2, 3), "float32", "llvm"),
+            y: R.Tensor((2, 3), "float32", "llvm"),
+            z: R.Tensor((2, 3), "float32", "llvm"),
+        ) -> R.Tensor((2, 3), "float32", "llvm"):
+            with R.dataflow():
+                x1: R.Tensor((2, 3), "float32", "llvm") = x
+                y1: R.Tensor((2, 3), "float32", "llvm") = y
+                x2: R.Tensor((2, 3), "float32", "llvm") = x1
+                y2: R.Tensor((2, 3), "float32", "llvm") = y1
+                lv0: R.Tensor((2, 3), "float32", "llvm") = R.add(x2, y2)
+                gv: R.Tensor((2, 3), "float32", "llvm") = R.multiply(lv0, z)
+                R.output(gv)
+            return gv
+
+    verify(Input, Expect)
+
+
+def test_binding():
+    @I.ir_module
+    class Input:
+        I.module_attrs({"attr": 10})
+        I.module_global_infos(
+            {
+                "vdevice": [
+                    I.vdevice("llvm"),
+                ]
+            }
+        )
+
+        @R.function
+        def foo(
+            x: R.Tensor((2, 3), "float32"),
+            y: R.Tensor((2, 3), "float32"),
+            z: R.Tensor((2, 3), "float32"),
+        ) -> R.Tensor((2, 3), "float32"):
+            x1 = x
+            y1 = y
+            x2 = x1
+            y2 = y1
+            s: R.Tensor((2, 3), "float32", "llvm") = R.add(x2, y2)
+            m = R.multiply(s, z)
+            return m
+
+    @I.ir_module
+    class Expect:
+        I.module_attrs({"attr": 10})
+        I.module_global_infos(
+            {
+                "vdevice": [
+                    I.vdevice("llvm"),
+                ]
+            }
+        )
+
+        @R.function
+        def foo(
+            x: R.Tensor((2, 3), "float32", "llvm"),
+            y: R.Tensor((2, 3), "float32", "llvm"),
+            z: R.Tensor((2, 3), "float32", "llvm"),
+        ) -> R.Tensor((2, 3), "float32", "llvm"):
+            x1: R.Tensor((2, 3), "float32", "llvm") = x
+            y1: R.Tensor((2, 3), "float32", "llvm") = y
+            x2: R.Tensor((2, 3), "float32", "llvm") = x1
+            y2: R.Tensor((2, 3), "float32", "llvm") = y1
+            s: R.Tensor((2, 3), "float32", "llvm") = R.add(x2, y2)
+            m: R.Tensor((2, 3), "float32", "llvm") = R.multiply(s, z)
+            return m
+
+    verify(Input, Expect)
+
+
+def test_func_ret():
+    @I.ir_module
+    class Input:
+        I.module_attrs({"attr": 10})
+        I.module_global_infos(
+            {
+                "vdevice": [
+                    I.vdevice("cuda"),
+                ]
+            }
+        )
+
+        @R.function
+        def foo(
+            x: R.Tensor((2, 3), "float32"),
+            y: R.Tensor((2, 3), "float32"),
+            z: R.Tensor((2, 3), "float32"),
+        ) -> R.Tensor((2, 3), "float32", "cuda"):
+            with R.dataflow():
+                lv0 = R.add(x, y)
+                gv = R.multiply(lv0, z)
+                R.output(gv)
+            return gv
+
+    @I.ir_module
+    class Expect:
+        I.module_attrs({"attr": 10})
+        I.module_global_infos(
+            {
+                "vdevice": [
+                    I.vdevice("cuda"),
+                ]
+            }
+        )
+
+        @R.function
+        def foo(
+            x: R.Tensor((2, 3), "float32", "cuda"),
+            y: R.Tensor((2, 3), "float32", "cuda"),
+            z: R.Tensor((2, 3), "float32", "cuda"),
+        ) -> R.Tensor((2, 3), "float32", "cuda"):
+            with R.dataflow():
+                lv0: R.Tensor((2, 3), "float32", "cuda") = R.add(x, y)
+                gv: R.Tensor((2, 3), "float32", "cuda") = R.multiply(lv0, z)
+                R.output(gv)
+            return gv
+
+    verify(Input, Expect)
+
+
+def test_multi_device():
+    @I.ir_module
+    class Input:
+        I.module_attrs({"attr": 10})
+        I.module_global_infos(
+            {
+                "vdevice": [
+                    I.vdevice("llvm"),
+                    I.vdevice("cuda", 0),
+                    I.vdevice("metal", 0, "global"),
+                    I.vdevice("cuda -arch=sm_80", 0),
+                ]
+            }
+        )
+
+        @R.function
+        def foo(
+            x: R.Tensor((2, 3), "float32"),
+            y: R.Tensor((2, 3), "float32"),
+            z: R.Tensor((2, 3), "float32"),
+        ) -> R.Tensor((2, 3), "float32", "cuda"):
+            with R.dataflow():
+                lv0: R.Tensor((2, 3), "float32", "llvm") = R.add(x, y)
+                lv1 = R.to_vdevice(lv0, "cuda")
+                lv2 = R.add(z, z)
+                gv: R.Tensor((2, 3), "float32", "cuda") = R.multiply(lv1, lv2)
+                R.output(gv)
+            return gv
+
+    @I.ir_module
+    class Expect:
+        I.module_attrs({"attr": 10})
+        I.module_global_infos(
+            {
+                "vdevice": [
+                    I.vdevice("llvm"),
+                    I.vdevice("cuda", 0),
+                    I.vdevice("metal", 0, "global"),
+                    I.vdevice("cuda -arch=sm_80", 0),
+                ]
+            }
+        )
+
+        @R.function
+        def foo(
+            x: R.Tensor((2, 3), "float32", "llvm"),
+            y: R.Tensor((2, 3), "float32", "llvm"),
+            z: R.Tensor((2, 3), "float32", "cuda"),
+        ) -> R.Tensor((2, 3), "float32", "cuda"):
+            with R.dataflow():
+                lv0: R.Tensor((2, 3), "float32", "llvm") = R.add(x, y)
+                lv1: R.Tensor((2, 3), "float32", "cuda") = R.to_vdevice(lv0, 
"cuda")
+                lv2: R.Tensor((2, 3), "float32", "cuda") = R.add(z, z)
+                gv: R.Tensor((2, 3), "float32", "cuda") = R.multiply(lv1, lv2)
+                R.output(gv)
+            return gv
+
+    verify(Input, Expect)
+
+
+def test_insert_to_vdevice():
+    @I.ir_module
+    class Input:
+        I.module_attrs({"attr": 10})
+        I.module_global_infos(
+            {
+                "vdevice": [
+                    I.vdevice("llvm"),
+                    I.vdevice("cuda", 0),
+                    I.vdevice("metal", 0, "global"),
+                    I.vdevice("cuda -arch=sm_80", 0),
+                ]
+            }
+        )
+
+        @R.function
+        def foo(
+            x: R.Tensor((2, 3), "float32"),
+            y: R.Tensor((2, 3), "float32"),
+            z: R.Tensor((2, 3), "float32"),
+        ) -> R.Tensor((2, 3), "float32"):
+            with R.dataflow():
+                lv0 = R.hint_on_device(y, tvm.cpu())
+                lv1 = R.add(x, lv0)
+                lv2 = R.hint_on_device(lv1, tvm.cuda())
+                lv3 = R.add(lv2, lv2)
+                lv4 = R.hint_on_device(z, tvm.cuda())
+                gv = R.multiply(lv3, lv4)
+                R.output(gv)
+            return gv
+
+    @I.ir_module
+    class Expect:
+        I.module_attrs({"attr": 10})
+        I.module_global_infos(
+            {
+                "vdevice": [
+                    I.vdevice("llvm"),
+                    I.vdevice("cuda", 0),
+                    I.vdevice("metal", 0, "global"),
+                    I.vdevice("cuda -arch=sm_80", 0),
+                ]
+            }
+        )
+
+        @R.function
+        def foo(
+            x: R.Tensor((2, 3), "float32", "llvm"),
+            y: R.Tensor((2, 3), "float32", "llvm"),
+            z: R.Tensor((2, 3), "float32", "cuda"),
+        ) -> R.Tensor((2, 3), "float32", "cuda"):
+            with R.dataflow():
+                lv0: R.Tensor((2, 3), "float32", "llvm") = y
+                lv1: R.Tensor((2, 3), "float32", "llvm") = R.add(x, lv0)
+                lv2: R.Tensor((2, 3), "float32", "cuda") = R.to_vdevice(lv1, 
"cuda")
+                lv3: R.Tensor((2, 3), "float32", "cuda") = R.add(lv2, lv2)
+                lv4: R.Tensor((2, 3), "float32", "cuda") = z
+                gv: R.Tensor((2, 3), "float32", "cuda") = R.multiply(lv3, lv4)
+                R.output(gv)
+            return gv
+
+    verify(Input, Expect)
+
+
+if __name__ == "__main__":
+    tvm.testing.main()
diff --git a/tests/python/relax/test_tvmscript_parser_op_manipulate.py 
b/tests/python/relax/test_tvmscript_parser_op_manipulate.py
index 25f4f08520..694e7a688c 100644
--- a/tests/python/relax/test_tvmscript_parser_op_manipulate.py
+++ b/tests/python/relax/test_tvmscript_parser_op_manipulate.py
@@ -21,7 +21,7 @@ import tvm
 import tvm.script
 import tvm.testing
 from tvm import IRModule, relax
-from tvm.script import relax as R
+from tvm.script import relax as R, ir as I
 
 
 def _check(
@@ -404,15 +404,36 @@ def test_flip():
 
 
 def test_to_vdevice():
+    @I.ir_module
+    class ToVDevice:
+        I.module_global_infos({"vdevice": [I.vdevice("llvm")]})
+
+        @R.function
+        def foo(x: R.Tensor((), "int32")) -> R.Tensor((), "int32"):
+            tensor = R.to_vdevice(x, "llvm")
+            return tensor
+
+    x = relax.Var("x", R.Tensor((), "int32"))
+    bb = relax.BlockBuilder()
+    vdev = I.vdevice("llvm")
+    with bb.function("foo", (x,)):
+        tensor = bb.emit(relax.op.to_vdevice(x, vdev))
+        bb.emit_func_output(tensor)
+    bb.get().update_global_info("vdevice", [vdev])
+
+    _check(ToVDevice, bb.get())
+
+
+def test_hint_on_device():
     @R.function
     def foo(x: R.Tensor((), "int32")) -> R.Tensor((), "int32"):
-        tensor = R.to_vdevice(x, tvm.ir.VDevice("llvm", 0, "global"))
-        return tensor
+        r = R.hint_on_device(x, R.device(1, 0))
+        return r
 
     x = relax.Var("x", R.Tensor((), "int32"))
     bb = relax.BlockBuilder()
     with bb.function("foo", (x,)):
-        tensor = bb.emit(relax.op.to_vdevice(x, tvm.ir.VDevice("llvm", 0, 
"global")))
+        tensor = bb.emit(relax.op.hint_on_device(x, R.cpu()))
         bb.emit_func_output(tensor)
 
     _check(foo, bb.get()["foo"])


Reply via email to