comaniac commented on a change in pull request #8702:
URL: https://github.com/apache/tvm/pull/8702#discussion_r698716858



##########
File path: python/tvm/contrib/pipeline_executor.py
##########
@@ -0,0 +1,395 @@
+# 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.
+"""Pipeline executor that executes a series of modules in a pipeline 
fashion."""
+import json
+import tvm._ffi
+from tvm import relay
+from tvm.contrib import graph_executor
+
+
+def pipeline_executor_enabled():
+    """check if pipeline executor is enabled.
+
+    Return
+    -------
+    enable: bool
+        Return pipeline executor is enabled or not.
+    """
+    return tvm._ffi.get_global_func("tvm.pipeline_executor.create",
+                                    allow_missing=True) is not None
+
+
+def build(pipe_configs):
+    """build module list that can use for pipeline execution.
+
+    Parameters
+    ----------
+    mod_n_configs: Dict[IRModule, Dict[str, Any]]
+        build configuration informaton, structure like following.
+        {IRModule: {"target":target,
+                    "target_host":target_host,
+                    "params":params,
+                    "mod_name"mod_name,
+                    "build":build}}
+
+    Returns
+    -------
+    ret: List[IRModule]
+        list of IRModule
+    string_config: Dict[int, Dict[str, any]]
+        pipeline configuration
+    """
+    mods = {}
+    mod_n_configs = pipe_configs.get_config()
+    config_len = len(mod_n_configs)
+    string_config = [{} for _ in range(config_len)]
+    #for _, (ir_mod, mod_config) in enumerate(mod_n_configs.items()):
+    for ir_mod, mod_config in mod_n_configs.items():
+        mconf = mod_config["pipeline"].copy()
+        mod_indx = mconf["mod_indx"] - 1
+        # Get mod device config
+        dev = mod_config["dev"]
+        target = mod_config["target"]
+        build_func = relay.build
+        # if there is a self defined build function then use it.
+        if "build" in mod_config and mod_config["build"]:
+            build_func = mod_config["build"]
+
+        # build IRModule
+        mod = build_func(
+            ir_mod,
+            target,
+            params=mod_config["params"],
+            target_host=mod_config["target_host"],
+            mod_name=mod_config["mod_name"],
+        )
+
+        mconf["dev"] = "{},{}".format(dev.device_type, dev.device_id)
+        # Create pipeline configuration
+        string_config[mod_indx] = mconf
+        # associate mod with device
+        mods[mod] = {"dev": dev}
+
+    # return PipeModuleConfig
+    return PipeModuleConfig(mods, string_config)
+
+
+def create(pipe_mod_config):
+    """Create a pipeline runtime executor.
+
+    Parameters
+    ----------
+
+    pipe_mod_config : PipeModuleConfig
+        class to storage IRModule list and pipeline configuration.
+
+    Returns
+    -------
+    submodule : PipelineModule
+        Runtime pipeline module.
+    """
+
+    return PipelineModule(pipe_mod_config)
+
+class PipelineModule(object):
+    """Wrapper runtime module. This is a thin wrapper of the underlying TVM 
module.
+
+    Parameters
+    ----------
+    pipeline_mods : List[GraphModule]
+        The internal tvm module that holds the actual graph functions.
+    pipeline_config : Dict[IRModule, Dict[str, Any]]
+        modules and modules dependency configuration informaiton.
+    """
+
+    def __init__(self, pipe_mod_config):
+        self.pipeline_mods_ = pipe_mod_config.pipeline_mods_
+        self.mod_config_ = pipe_mod_config.mods_config_
+        mods, config = self.graph_executor_create(self.pipeline_mods_, 
self.mod_config_)
+        assert pipeline_executor_enabled(), \
+              "Pipeline executor is not enabled. Please \
+              re-build TVM with USE_PIPELINE_EXECUTOR=ON"
+        pipelinecreate = 
tvm._ffi.get_global_func("tvm.pipeline_executor.create",
+                                                  allow_missing=False)
+        assert pipelinecreate
+        module = pipelinecreate(mods, config)
+
+        self.module_ = module
+
+    def graph_executor_create(self, pipeline_mods, mod_config):
+        """Create graph_executor list and return string format config.
+
+        Parameters
+        ----------
+
+        pipeline_mods : List[IRModule]
+          list of IRModule
+
+        mod_config : Dict[int, Dict[str, Any]]
+            modules and modules dependency configuration informaiton.
+
+        Returns
+        -------
+        mods : List[GraphModule]
+            Runtime graph module.
+
+       mod_config : str
+           mods configuration
+        """
+
+        mods = []
+        for pipeline_mod in pipeline_mods:
+            mod = graph_executor.GraphModule(
+                pipeline_mod["default"](pipeline_mods[pipeline_mod]["dev"])
+            )
+            mods.append(mod.module)
+
+        return mods, json.dumps(mod_config)
+
+
+class PipelineConfig(object):
+    """Pipeline Configuration Class, in this class there are 2 internal class,
+    first is Module which use to represent Module, second is Interface which 
use
+    to represent Module input/output and Pipeline Module input/output, by 
setting
+    dependency relation between Interfaces this class can build the module
+    connection relation.
+
+    The class Hierarchical as following.
+         PipelineConfig ---> ModuleWrapper ---> Interface(input/output)
+    """
+
+    class ModuleWrapper:
+        """The class use use to represent Module and storage module index and
+        Interface information.
+        """
+
+        class Interface:

Review comment:
       After reviewing this class carefully, I feel `Binding` might be a more 
precise term, because this class basically describes how an input/output of 
this module should come/go.

##########
File path: python/tvm/contrib/pipeline_executor.py
##########
@@ -0,0 +1,395 @@
+# 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.
+"""Pipeline executor that executes a series of modules in a pipeline 
fashion."""
+import json
+import tvm._ffi
+from tvm import relay
+from tvm.contrib import graph_executor
+
+
+def pipeline_executor_enabled():
+    """check if pipeline executor is enabled.
+
+    Return
+    -------
+    enable: bool
+        Return pipeline executor is enabled or not.
+    """
+    return tvm._ffi.get_global_func("tvm.pipeline_executor.create",
+                                    allow_missing=True) is not None
+
+
+def build(pipe_configs):
+    """build module list that can use for pipeline execution.
+
+    Parameters
+    ----------
+    mod_n_configs: Dict[IRModule, Dict[str, Any]]
+        build configuration informaton, structure like following.
+        {IRModule: {"target":target,
+                    "target_host":target_host,
+                    "params":params,
+                    "mod_name"mod_name,
+                    "build":build}}
+
+    Returns
+    -------
+    ret: List[IRModule]
+        list of IRModule
+    string_config: Dict[int, Dict[str, any]]
+        pipeline configuration
+    """
+    mods = {}
+    mod_n_configs = pipe_configs.get_config()
+    config_len = len(mod_n_configs)
+    string_config = [{} for _ in range(config_len)]
+    #for _, (ir_mod, mod_config) in enumerate(mod_n_configs.items()):
+    for ir_mod, mod_config in mod_n_configs.items():
+        mconf = mod_config["pipeline"].copy()
+        mod_indx = mconf["mod_indx"] - 1
+        # Get mod device config
+        dev = mod_config["dev"]
+        target = mod_config["target"]
+        build_func = relay.build
+        # if there is a self defined build function then use it.
+        if "build" in mod_config and mod_config["build"]:
+            build_func = mod_config["build"]
+
+        # build IRModule
+        mod = build_func(
+            ir_mod,
+            target,
+            params=mod_config["params"],
+            target_host=mod_config["target_host"],
+            mod_name=mod_config["mod_name"],
+        )
+
+        mconf["dev"] = "{},{}".format(dev.device_type, dev.device_id)
+        # Create pipeline configuration
+        string_config[mod_indx] = mconf
+        # associate mod with device
+        mods[mod] = {"dev": dev}
+
+    # return PipeModuleConfig
+    return PipeModuleConfig(mods, string_config)
+
+
+def create(pipe_mod_config):
+    """Create a pipeline runtime executor.
+
+    Parameters
+    ----------
+
+    pipe_mod_config : PipeModuleConfig
+        class to storage IRModule list and pipeline configuration.
+
+    Returns
+    -------
+    submodule : PipelineModule
+        Runtime pipeline module.
+    """
+
+    return PipelineModule(pipe_mod_config)
+
+class PipelineModule(object):
+    """Wrapper runtime module. This is a thin wrapper of the underlying TVM 
module.
+
+    Parameters
+    ----------
+    pipeline_mods : List[GraphModule]
+        The internal tvm module that holds the actual graph functions.
+    pipeline_config : Dict[IRModule, Dict[str, Any]]
+        modules and modules dependency configuration informaiton.
+    """
+
+    def __init__(self, pipe_mod_config):
+        self.pipeline_mods_ = pipe_mod_config.pipeline_mods_
+        self.mod_config_ = pipe_mod_config.mods_config_
+        mods, config = self.graph_executor_create(self.pipeline_mods_, 
self.mod_config_)
+        assert pipeline_executor_enabled(), \
+              "Pipeline executor is not enabled. Please \
+              re-build TVM with USE_PIPELINE_EXECUTOR=ON"
+        pipelinecreate = 
tvm._ffi.get_global_func("tvm.pipeline_executor.create",
+                                                  allow_missing=False)
+        assert pipelinecreate
+        module = pipelinecreate(mods, config)
+
+        self.module_ = module
+
+    def graph_executor_create(self, pipeline_mods, mod_config):
+        """Create graph_executor list and return string format config.
+
+        Parameters
+        ----------
+
+        pipeline_mods : List[IRModule]
+          list of IRModule
+
+        mod_config : Dict[int, Dict[str, Any]]
+            modules and modules dependency configuration informaiton.
+
+        Returns
+        -------
+        mods : List[GraphModule]
+            Runtime graph module.
+
+       mod_config : str
+           mods configuration
+        """
+
+        mods = []
+        for pipeline_mod in pipeline_mods:
+            mod = graph_executor.GraphModule(
+                pipeline_mod["default"](pipeline_mods[pipeline_mod]["dev"])
+            )
+            mods.append(mod.module)
+
+        return mods, json.dumps(mod_config)
+
+
+class PipelineConfig(object):
+    """Pipeline Configuration Class, in this class there are 2 internal class,
+    first is Module which use to represent Module, second is Interface which 
use
+    to represent Module input/output and Pipeline Module input/output, by 
setting
+    dependency relation between Interfaces this class can build the module
+    connection relation.
+
+    The class Hierarchical as following.
+         PipelineConfig ---> ModuleWrapper ---> Interface(input/output)
+    """
+
+    class ModuleWrapper:
+        """The class use use to represent Module and storage module index and
+        Interface information.
+        """
+
+        class Interface:
+            """The class that use to storage module connection information.
+               There are 2 types Interface Input:1 Output:2
+            Parameters
+            ----------
+
+            owner : ModuleWrapper
+                The class that own this interface, in such class there are
+                Module information like index, module name
+
+            itype : integer
+                Interface type, 1 is input interface, 2 is output interface
+
+            name : str/integer
+                Interface name, for input that is string for example "data0"
+                for output that is integer for example 0.
+            """
+
+            def __init__(self, owner, itype, name):
+                self.owner_ = owner
+                self.itype_ = itype
+                self.name_ = str(name)
+                self.dependent_ = []

Review comment:
       1. We don't add `_` suffix in Python and should not. These variables are 
public after all.
   2.  `self.itype` -> `self.io_type`.
   3.  `self.name = str(name)` -> `self.name = str(name) if io_type == "input" 
else f"output({name})"`.
   4. `self.dependent` -> `self.bindings`.

##########
File path: python/tvm/contrib/pipeline_executor.py
##########
@@ -0,0 +1,395 @@
+# 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.
+"""Pipeline executor that executes a series of modules in a pipeline 
fashion."""
+import json
+import tvm._ffi
+from tvm import relay
+from tvm.contrib import graph_executor
+
+
+def pipeline_executor_enabled():
+    """check if pipeline executor is enabled.
+
+    Return
+    -------
+    enable: bool
+        Return pipeline executor is enabled or not.
+    """
+    return tvm._ffi.get_global_func("tvm.pipeline_executor.create",
+                                    allow_missing=True) is not None
+
+
+def build(pipe_configs):
+    """build module list that can use for pipeline execution.
+
+    Parameters
+    ----------
+    mod_n_configs: Dict[IRModule, Dict[str, Any]]
+        build configuration informaton, structure like following.
+        {IRModule: {"target":target,
+                    "target_host":target_host,
+                    "params":params,
+                    "mod_name"mod_name,
+                    "build":build}}
+
+    Returns
+    -------
+    ret: List[IRModule]
+        list of IRModule
+    string_config: Dict[int, Dict[str, any]]
+        pipeline configuration
+    """
+    mods = {}
+    mod_n_configs = pipe_configs.get_config()
+    config_len = len(mod_n_configs)
+    string_config = [{} for _ in range(config_len)]
+    #for _, (ir_mod, mod_config) in enumerate(mod_n_configs.items()):
+    for ir_mod, mod_config in mod_n_configs.items():
+        mconf = mod_config["pipeline"].copy()
+        mod_indx = mconf["mod_indx"] - 1
+        # Get mod device config
+        dev = mod_config["dev"]
+        target = mod_config["target"]
+        build_func = relay.build
+        # if there is a self defined build function then use it.
+        if "build" in mod_config and mod_config["build"]:
+            build_func = mod_config["build"]
+
+        # build IRModule
+        mod = build_func(
+            ir_mod,
+            target,
+            params=mod_config["params"],
+            target_host=mod_config["target_host"],
+            mod_name=mod_config["mod_name"],
+        )
+
+        mconf["dev"] = "{},{}".format(dev.device_type, dev.device_id)
+        # Create pipeline configuration
+        string_config[mod_indx] = mconf
+        # associate mod with device
+        mods[mod] = {"dev": dev}
+
+    # return PipeModuleConfig
+    return PipeModuleConfig(mods, string_config)
+
+
+def create(pipe_mod_config):
+    """Create a pipeline runtime executor.
+
+    Parameters
+    ----------
+
+    pipe_mod_config : PipeModuleConfig
+        class to storage IRModule list and pipeline configuration.
+
+    Returns
+    -------
+    submodule : PipelineModule
+        Runtime pipeline module.
+    """
+
+    return PipelineModule(pipe_mod_config)
+
+class PipelineModule(object):
+    """Wrapper runtime module. This is a thin wrapper of the underlying TVM 
module.
+
+    Parameters
+    ----------
+    pipeline_mods : List[GraphModule]
+        The internal tvm module that holds the actual graph functions.
+    pipeline_config : Dict[IRModule, Dict[str, Any]]
+        modules and modules dependency configuration informaiton.
+    """
+
+    def __init__(self, pipe_mod_config):
+        self.pipeline_mods_ = pipe_mod_config.pipeline_mods_
+        self.mod_config_ = pipe_mod_config.mods_config_
+        mods, config = self.graph_executor_create(self.pipeline_mods_, 
self.mod_config_)
+        assert pipeline_executor_enabled(), \
+              "Pipeline executor is not enabled. Please \
+              re-build TVM with USE_PIPELINE_EXECUTOR=ON"
+        pipelinecreate = 
tvm._ffi.get_global_func("tvm.pipeline_executor.create",
+                                                  allow_missing=False)
+        assert pipelinecreate
+        module = pipelinecreate(mods, config)
+
+        self.module_ = module
+
+    def graph_executor_create(self, pipeline_mods, mod_config):
+        """Create graph_executor list and return string format config.
+
+        Parameters
+        ----------
+
+        pipeline_mods : List[IRModule]
+          list of IRModule
+
+        mod_config : Dict[int, Dict[str, Any]]
+            modules and modules dependency configuration informaiton.
+
+        Returns
+        -------
+        mods : List[GraphModule]
+            Runtime graph module.
+
+       mod_config : str
+           mods configuration
+        """
+
+        mods = []
+        for pipeline_mod in pipeline_mods:
+            mod = graph_executor.GraphModule(
+                pipeline_mod["default"](pipeline_mods[pipeline_mod]["dev"])
+            )
+            mods.append(mod.module)
+
+        return mods, json.dumps(mod_config)
+
+
+class PipelineConfig(object):
+    """Pipeline Configuration Class, in this class there are 2 internal class,
+    first is Module which use to represent Module, second is Interface which 
use
+    to represent Module input/output and Pipeline Module input/output, by 
setting
+    dependency relation between Interfaces this class can build the module
+    connection relation.
+
+    The class Hierarchical as following.
+         PipelineConfig ---> ModuleWrapper ---> Interface(input/output)
+    """
+
+    class ModuleWrapper:
+        """The class use use to represent Module and storage module index and
+        Interface information.
+        """
+
+        class Interface:
+            """The class that use to storage module connection information.
+               There are 2 types Interface Input:1 Output:2
+            Parameters
+            ----------
+
+            owner : ModuleWrapper
+                The class that own this interface, in such class there are
+                Module information like index, module name
+
+            itype : integer
+                Interface type, 1 is input interface, 2 is output interface
+
+            name : str/integer
+                Interface name, for input that is string for example "data0"
+                for output that is integer for example 0.
+            """
+
+            def __init__(self, owner, itype, name):
+                self.owner_ = owner
+                self.itype_ = itype
+                self.name_ = str(name)
+                self.dependent_ = []
+
+            def get_name(self):
+                mname = ""
+                if self.owner_:

Review comment:
       By your declaration, owner cannot be None.

##########
File path: python/tvm/contrib/pipeline_executor.py
##########
@@ -0,0 +1,395 @@
+# 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.
+"""Pipeline executor that executes a series of modules in a pipeline 
fashion."""
+import json
+import tvm._ffi
+from tvm import relay
+from tvm.contrib import graph_executor
+
+
+def pipeline_executor_enabled():
+    """check if pipeline executor is enabled.
+
+    Return
+    -------
+    enable: bool
+        Return pipeline executor is enabled or not.
+    """
+    return tvm._ffi.get_global_func("tvm.pipeline_executor.create",
+                                    allow_missing=True) is not None
+
+
+def build(pipe_configs):
+    """build module list that can use for pipeline execution.
+
+    Parameters
+    ----------
+    mod_n_configs: Dict[IRModule, Dict[str, Any]]
+        build configuration informaton, structure like following.
+        {IRModule: {"target":target,
+                    "target_host":target_host,
+                    "params":params,
+                    "mod_name"mod_name,
+                    "build":build}}
+
+    Returns
+    -------
+    ret: List[IRModule]
+        list of IRModule
+    string_config: Dict[int, Dict[str, any]]
+        pipeline configuration
+    """
+    mods = {}
+    mod_n_configs = pipe_configs.get_config()
+    config_len = len(mod_n_configs)
+    string_config = [{} for _ in range(config_len)]
+    #for _, (ir_mod, mod_config) in enumerate(mod_n_configs.items()):
+    for ir_mod, mod_config in mod_n_configs.items():
+        mconf = mod_config["pipeline"].copy()
+        mod_indx = mconf["mod_indx"] - 1
+        # Get mod device config
+        dev = mod_config["dev"]
+        target = mod_config["target"]
+        build_func = relay.build
+        # if there is a self defined build function then use it.
+        if "build" in mod_config and mod_config["build"]:
+            build_func = mod_config["build"]
+
+        # build IRModule
+        mod = build_func(
+            ir_mod,
+            target,
+            params=mod_config["params"],
+            target_host=mod_config["target_host"],
+            mod_name=mod_config["mod_name"],
+        )
+
+        mconf["dev"] = "{},{}".format(dev.device_type, dev.device_id)
+        # Create pipeline configuration
+        string_config[mod_indx] = mconf
+        # associate mod with device
+        mods[mod] = {"dev": dev}
+
+    # return PipeModuleConfig
+    return PipeModuleConfig(mods, string_config)
+
+
+def create(pipe_mod_config):
+    """Create a pipeline runtime executor.
+
+    Parameters
+    ----------
+
+    pipe_mod_config : PipeModuleConfig
+        class to storage IRModule list and pipeline configuration.
+
+    Returns
+    -------
+    submodule : PipelineModule
+        Runtime pipeline module.
+    """
+
+    return PipelineModule(pipe_mod_config)
+
+class PipelineModule(object):
+    """Wrapper runtime module. This is a thin wrapper of the underlying TVM 
module.
+
+    Parameters
+    ----------
+    pipeline_mods : List[GraphModule]
+        The internal tvm module that holds the actual graph functions.
+    pipeline_config : Dict[IRModule, Dict[str, Any]]
+        modules and modules dependency configuration informaiton.
+    """
+
+    def __init__(self, pipe_mod_config):
+        self.pipeline_mods_ = pipe_mod_config.pipeline_mods_
+        self.mod_config_ = pipe_mod_config.mods_config_
+        mods, config = self.graph_executor_create(self.pipeline_mods_, 
self.mod_config_)
+        assert pipeline_executor_enabled(), \
+              "Pipeline executor is not enabled. Please \
+              re-build TVM with USE_PIPELINE_EXECUTOR=ON"
+        pipelinecreate = 
tvm._ffi.get_global_func("tvm.pipeline_executor.create",
+                                                  allow_missing=False)
+        assert pipelinecreate
+        module = pipelinecreate(mods, config)
+
+        self.module_ = module
+
+    def graph_executor_create(self, pipeline_mods, mod_config):
+        """Create graph_executor list and return string format config.
+
+        Parameters
+        ----------
+
+        pipeline_mods : List[IRModule]
+          list of IRModule
+
+        mod_config : Dict[int, Dict[str, Any]]
+            modules and modules dependency configuration informaiton.
+
+        Returns
+        -------
+        mods : List[GraphModule]
+            Runtime graph module.
+
+       mod_config : str
+           mods configuration
+        """
+
+        mods = []
+        for pipeline_mod in pipeline_mods:
+            mod = graph_executor.GraphModule(
+                pipeline_mod["default"](pipeline_mods[pipeline_mod]["dev"])
+            )
+            mods.append(mod.module)
+
+        return mods, json.dumps(mod_config)
+
+
+class PipelineConfig(object):
+    """Pipeline Configuration Class, in this class there are 2 internal class,
+    first is Module which use to represent Module, second is Interface which 
use
+    to represent Module input/output and Pipeline Module input/output, by 
setting
+    dependency relation between Interfaces this class can build the module
+    connection relation.
+
+    The class Hierarchical as following.
+         PipelineConfig ---> ModuleWrapper ---> Interface(input/output)
+    """
+
+    class ModuleWrapper:
+        """The class use use to represent Module and storage module index and
+        Interface information.
+        """
+
+        class Interface:
+            """The class that use to storage module connection information.
+               There are 2 types Interface Input:1 Output:2
+            Parameters
+            ----------
+
+            owner : ModuleWrapper
+                The class that own this interface, in such class there are
+                Module information like index, module name
+
+            itype : integer
+                Interface type, 1 is input interface, 2 is output interface
+
+            name : str/integer
+                Interface name, for input that is string for example "data0"
+                for output that is integer for example 0.
+            """
+
+            def __init__(self, owner, itype, name):
+                self.owner_ = owner
+                self.itype_ = itype
+                self.name_ = str(name)
+                self.dependent_ = []
+
+            def get_name(self):
+                mname = ""
+                if self.owner_:
+                    mname = self.owner_.name_
+
+                return mname, self.name_
+
+            def get_owner_indx(self):
+                return self.owner_.indx_
+
+            def get_dependent_str(self):
+                name = ""
+                for dependent in self.dependent_:
+                    mname, dname = dependent.get_name()
+                    name = name + (mname + ":output(" + dname if self.itype_ 
== 2 else "")
+                    name = name + (")" if self.itype_ == 2 else mname + ":" + 
dname)
+                return name
+
+            def add_dependent(self, dependent):
+                """
+                # check if the dependency setting correct.
+                # correct connection are following
+                # 1. global input to module input
+                # 2. module output to next module input
+                # 3. module output to global output
+                """
+                owner_indx = self.get_owner_indx()
+                dep_owner_indx = dependent.get_owner_indx()
+                assert owner_indx != dep_owner_indx, f"can not set self as 
dependent."
+                assert not (
+                    owner_indx > dep_owner_indx
+                    and not (dependent.itype_ == 2 and dep_owner_indx == 0)
+                ), f"dependent only can be next module interface or global 
output."
+                assert not (
+                    owner_indx == 0 and dependent.itype_ != 1
+                ), f"global input only can set dependent with module input."
+
+                self.dependent_.append(dependent)

Review comment:
       In general you need to raise exceptions instead of `assert` in this 
function. `assert` is usually used for internal error that developers should be 
aware of. In this case, these errors are triggered by incorrect user behaviors.
   
   Meanwhile, there are two points for the user message:
   1. Use capital in the first word.
   2. No need to add a period at the end.
   
   ```suggestion
               def add_binding(self, binding):
                   """Check if the binding is legal by looking at the following:
                   1. Cannot bind to the module itself.
                   2. Can only bind to later stage modules or global outputs.
                   3. module output to global output.
                   """
                   owner_indx = self.get_owner_indx()
                   dep_owner_indx = binding.get_owner_indx()
                   if owner_indx == dep_owner_indx:
                       raise RuntimeError(f"Illegal binding: {self.name} cannot 
bind to the same module")
                   if owner_indx < dep_owner_indx:
                       raise Runtimeerror(f"Illegal binding: {self.name} cannot 
bind to {binding.name} before it")              
                   if dependent.io_type == "output" and dep_owner_indx == 0: # 
Cannot understand this rule.
                       raise RuntimeError(f"...")
                   if owner_indx == 0 and binding.io_type != "input": # Cannot 
understand this rule either.
                       raise RuntimeError(f"...")
   
                   self.bindings.append(binding)
   ```
   
   I'm not sure if I changed the conditions correctly as I cannot understand 
some of them. Please check if the conditions are correct or not.

##########
File path: python/tvm/contrib/pipeline_executor.py
##########
@@ -0,0 +1,395 @@
+# 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.
+"""Pipeline executor that executes a series of modules in a pipeline 
fashion."""
+import json
+import tvm._ffi
+from tvm import relay
+from tvm.contrib import graph_executor
+
+
+def pipeline_executor_enabled():
+    """check if pipeline executor is enabled.
+
+    Return
+    -------
+    enable: bool
+        Return pipeline executor is enabled or not.
+    """
+    return tvm._ffi.get_global_func("tvm.pipeline_executor.create",
+                                    allow_missing=True) is not None
+
+
+def build(pipe_configs):
+    """build module list that can use for pipeline execution.
+
+    Parameters
+    ----------
+    mod_n_configs: Dict[IRModule, Dict[str, Any]]
+        build configuration informaton, structure like following.
+        {IRModule: {"target":target,
+                    "target_host":target_host,
+                    "params":params,
+                    "mod_name"mod_name,
+                    "build":build}}
+
+    Returns
+    -------
+    ret: List[IRModule]
+        list of IRModule
+    string_config: Dict[int, Dict[str, any]]
+        pipeline configuration
+    """
+    mods = {}
+    mod_n_configs = pipe_configs.get_config()
+    config_len = len(mod_n_configs)
+    string_config = [{} for _ in range(config_len)]
+    #for _, (ir_mod, mod_config) in enumerate(mod_n_configs.items()):
+    for ir_mod, mod_config in mod_n_configs.items():
+        mconf = mod_config["pipeline"].copy()
+        mod_indx = mconf["mod_indx"] - 1
+        # Get mod device config
+        dev = mod_config["dev"]
+        target = mod_config["target"]
+        build_func = relay.build
+        # if there is a self defined build function then use it.
+        if "build" in mod_config and mod_config["build"]:
+            build_func = mod_config["build"]
+
+        # build IRModule
+        mod = build_func(
+            ir_mod,
+            target,
+            params=mod_config["params"],
+            target_host=mod_config["target_host"],
+            mod_name=mod_config["mod_name"],
+        )
+
+        mconf["dev"] = "{},{}".format(dev.device_type, dev.device_id)
+        # Create pipeline configuration
+        string_config[mod_indx] = mconf
+        # associate mod with device
+        mods[mod] = {"dev": dev}
+
+    # return PipeModuleConfig
+    return PipeModuleConfig(mods, string_config)
+
+
+def create(pipe_mod_config):
+    """Create a pipeline runtime executor.
+
+    Parameters
+    ----------
+
+    pipe_mod_config : PipeModuleConfig
+        class to storage IRModule list and pipeline configuration.
+
+    Returns
+    -------
+    submodule : PipelineModule
+        Runtime pipeline module.
+    """
+
+    return PipelineModule(pipe_mod_config)
+
+class PipelineModule(object):
+    """Wrapper runtime module. This is a thin wrapper of the underlying TVM 
module.
+
+    Parameters
+    ----------
+    pipeline_mods : List[GraphModule]
+        The internal tvm module that holds the actual graph functions.
+    pipeline_config : Dict[IRModule, Dict[str, Any]]
+        modules and modules dependency configuration informaiton.
+    """
+
+    def __init__(self, pipe_mod_config):
+        self.pipeline_mods_ = pipe_mod_config.pipeline_mods_
+        self.mod_config_ = pipe_mod_config.mods_config_
+        mods, config = self.graph_executor_create(self.pipeline_mods_, 
self.mod_config_)
+        assert pipeline_executor_enabled(), \
+              "Pipeline executor is not enabled. Please \
+              re-build TVM with USE_PIPELINE_EXECUTOR=ON"
+        pipelinecreate = 
tvm._ffi.get_global_func("tvm.pipeline_executor.create",
+                                                  allow_missing=False)
+        assert pipelinecreate
+        module = pipelinecreate(mods, config)
+
+        self.module_ = module
+
+    def graph_executor_create(self, pipeline_mods, mod_config):
+        """Create graph_executor list and return string format config.
+
+        Parameters
+        ----------
+
+        pipeline_mods : List[IRModule]
+          list of IRModule
+
+        mod_config : Dict[int, Dict[str, Any]]
+            modules and modules dependency configuration informaiton.
+
+        Returns
+        -------
+        mods : List[GraphModule]
+            Runtime graph module.
+
+       mod_config : str
+           mods configuration
+        """
+
+        mods = []
+        for pipeline_mod in pipeline_mods:
+            mod = graph_executor.GraphModule(
+                pipeline_mod["default"](pipeline_mods[pipeline_mod]["dev"])
+            )
+            mods.append(mod.module)
+
+        return mods, json.dumps(mod_config)
+
+
+class PipelineConfig(object):
+    """Pipeline Configuration Class, in this class there are 2 internal class,
+    first is Module which use to represent Module, second is Interface which 
use
+    to represent Module input/output and Pipeline Module input/output, by 
setting
+    dependency relation between Interfaces this class can build the module
+    connection relation.
+
+    The class Hierarchical as following.
+         PipelineConfig ---> ModuleWrapper ---> Interface(input/output)
+    """
+
+    class ModuleWrapper:
+        """The class use use to represent Module and storage module index and
+        Interface information.
+        """
+
+        class Interface:
+            """The class that use to storage module connection information.
+               There are 2 types Interface Input:1 Output:2
+            Parameters
+            ----------
+
+            owner : ModuleWrapper
+                The class that own this interface, in such class there are
+                Module information like index, module name
+
+            itype : integer
+                Interface type, 1 is input interface, 2 is output interface
+
+            name : str/integer
+                Interface name, for input that is string for example "data0"
+                for output that is integer for example 0.
+            """
+
+            def __init__(self, owner, itype, name):
+                self.owner_ = owner
+                self.itype_ = itype
+                self.name_ = str(name)
+                self.dependent_ = []
+
+            def get_name(self):
+                mname = ""
+                if self.owner_:
+                    mname = self.owner_.name_
+
+                return mname, self.name_
+
+            def get_owner_indx(self):
+                return self.owner_.indx_
+
+            def get_dependent_str(self):
+                name = ""
+                for dependent in self.dependent_:
+                    mname, dname = dependent.get_name()
+                    name = name + (mname + ":output(" + dname if self.itype_ 
== 2 else "")
+                    name = name + (")" if self.itype_ == 2 else mname + ":" + 
dname)
+                return name
+
+            def add_dependent(self, dependent):
+                """
+                # check if the dependency setting correct.
+                # correct connection are following
+                # 1. global input to module input
+                # 2. module output to next module input
+                # 3. module output to global output
+                """
+                owner_indx = self.get_owner_indx()
+                dep_owner_indx = dependent.get_owner_indx()
+                assert owner_indx != dep_owner_indx, f"can not set self as 
dependent."
+                assert not (
+                    owner_indx > dep_owner_indx
+                    and not (dependent.itype_ == 2 and dep_owner_indx == 0)
+                ), f"dependent only can be next module interface or global 
output."
+                assert not (
+                    owner_indx == 0 and dependent.itype_ != 1
+                ), f"global input only can set dependent with module input."
+
+                self.dependent_.append(dependent)
+
+        def __init__(self, indx=0):
+            self.indx_ = indx
+            self.name_ = "mod" + str(indx) if indx else ""
+            self.interfaces_ = {1: {}, 2: {}}

Review comment:
       ```suggestion
               self.input_bindings = {}
               self.output_bindings = {}
   ```

##########
File path: python/tvm/contrib/pipeline_executor.py
##########
@@ -0,0 +1,395 @@
+# 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.
+"""Pipeline executor that executes a series of modules in a pipeline 
fashion."""
+import json
+import tvm._ffi
+from tvm import relay
+from tvm.contrib import graph_executor
+
+
+def pipeline_executor_enabled():
+    """check if pipeline executor is enabled.
+
+    Return
+    -------
+    enable: bool
+        Return pipeline executor is enabled or not.
+    """
+    return tvm._ffi.get_global_func("tvm.pipeline_executor.create",
+                                    allow_missing=True) is not None
+
+
+def build(pipe_configs):
+    """build module list that can use for pipeline execution.
+
+    Parameters
+    ----------
+    mod_n_configs: Dict[IRModule, Dict[str, Any]]
+        build configuration informaton, structure like following.
+        {IRModule: {"target":target,
+                    "target_host":target_host,
+                    "params":params,
+                    "mod_name"mod_name,
+                    "build":build}}
+
+    Returns
+    -------
+    ret: List[IRModule]
+        list of IRModule
+    string_config: Dict[int, Dict[str, any]]
+        pipeline configuration
+    """
+    mods = {}
+    mod_n_configs = pipe_configs.get_config()
+    config_len = len(mod_n_configs)
+    string_config = [{} for _ in range(config_len)]
+    #for _, (ir_mod, mod_config) in enumerate(mod_n_configs.items()):
+    for ir_mod, mod_config in mod_n_configs.items():
+        mconf = mod_config["pipeline"].copy()
+        mod_indx = mconf["mod_indx"] - 1
+        # Get mod device config
+        dev = mod_config["dev"]
+        target = mod_config["target"]
+        build_func = relay.build
+        # if there is a self defined build function then use it.
+        if "build" in mod_config and mod_config["build"]:
+            build_func = mod_config["build"]
+
+        # build IRModule
+        mod = build_func(
+            ir_mod,
+            target,
+            params=mod_config["params"],
+            target_host=mod_config["target_host"],
+            mod_name=mod_config["mod_name"],
+        )
+
+        mconf["dev"] = "{},{}".format(dev.device_type, dev.device_id)
+        # Create pipeline configuration
+        string_config[mod_indx] = mconf
+        # associate mod with device
+        mods[mod] = {"dev": dev}
+
+    # return PipeModuleConfig
+    return PipeModuleConfig(mods, string_config)
+
+
+def create(pipe_mod_config):
+    """Create a pipeline runtime executor.
+
+    Parameters
+    ----------
+
+    pipe_mod_config : PipeModuleConfig
+        class to storage IRModule list and pipeline configuration.
+
+    Returns
+    -------
+    submodule : PipelineModule
+        Runtime pipeline module.
+    """
+
+    return PipelineModule(pipe_mod_config)
+
+class PipelineModule(object):
+    """Wrapper runtime module. This is a thin wrapper of the underlying TVM 
module.
+
+    Parameters
+    ----------
+    pipeline_mods : List[GraphModule]
+        The internal tvm module that holds the actual graph functions.
+    pipeline_config : Dict[IRModule, Dict[str, Any]]
+        modules and modules dependency configuration informaiton.
+    """
+
+    def __init__(self, pipe_mod_config):
+        self.pipeline_mods_ = pipe_mod_config.pipeline_mods_
+        self.mod_config_ = pipe_mod_config.mods_config_
+        mods, config = self.graph_executor_create(self.pipeline_mods_, 
self.mod_config_)
+        assert pipeline_executor_enabled(), \
+              "Pipeline executor is not enabled. Please \
+              re-build TVM with USE_PIPELINE_EXECUTOR=ON"
+        pipelinecreate = 
tvm._ffi.get_global_func("tvm.pipeline_executor.create",
+                                                  allow_missing=False)
+        assert pipelinecreate
+        module = pipelinecreate(mods, config)
+
+        self.module_ = module
+
+    def graph_executor_create(self, pipeline_mods, mod_config):
+        """Create graph_executor list and return string format config.
+
+        Parameters
+        ----------
+
+        pipeline_mods : List[IRModule]
+          list of IRModule
+
+        mod_config : Dict[int, Dict[str, Any]]
+            modules and modules dependency configuration informaiton.
+
+        Returns
+        -------
+        mods : List[GraphModule]
+            Runtime graph module.
+
+       mod_config : str
+           mods configuration
+        """
+
+        mods = []
+        for pipeline_mod in pipeline_mods:
+            mod = graph_executor.GraphModule(
+                pipeline_mod["default"](pipeline_mods[pipeline_mod]["dev"])
+            )
+            mods.append(mod.module)
+
+        return mods, json.dumps(mod_config)
+
+
+class PipelineConfig(object):
+    """Pipeline Configuration Class, in this class there are 2 internal class,
+    first is Module which use to represent Module, second is Interface which 
use
+    to represent Module input/output and Pipeline Module input/output, by 
setting
+    dependency relation between Interfaces this class can build the module
+    connection relation.
+
+    The class Hierarchical as following.
+         PipelineConfig ---> ModuleWrapper ---> Interface(input/output)
+    """
+
+    class ModuleWrapper:
+        """The class use use to represent Module and storage module index and
+        Interface information.
+        """
+
+        class Interface:
+            """The class that use to storage module connection information.
+               There are 2 types Interface Input:1 Output:2
+            Parameters
+            ----------
+
+            owner : ModuleWrapper
+                The class that own this interface, in such class there are
+                Module information like index, module name
+
+            itype : integer
+                Interface type, 1 is input interface, 2 is output interface
+
+            name : str/integer
+                Interface name, for input that is string for example "data0"
+                for output that is integer for example 0.
+            """
+
+            def __init__(self, owner, itype, name):
+                self.owner_ = owner
+                self.itype_ = itype
+                self.name_ = str(name)
+                self.dependent_ = []
+
+            def get_name(self):
+                mname = ""
+                if self.owner_:
+                    mname = self.owner_.name_
+
+                return mname, self.name_
+
+            def get_owner_indx(self):
+                return self.owner_.indx_
+
+            def get_dependent_str(self):
+                name = ""
+                for dependent in self.dependent_:
+                    mname, dname = dependent.get_name()
+                    name = name + (mname + ":output(" + dname if self.itype_ 
== 2 else "")
+                    name = name + (")" if self.itype_ == 2 else mname + ":" + 
dname)
+                return name
+
+            def add_dependent(self, dependent):
+                """
+                # check if the dependency setting correct.
+                # correct connection are following
+                # 1. global input to module input
+                # 2. module output to next module input
+                # 3. module output to global output
+                """
+                owner_indx = self.get_owner_indx()
+                dep_owner_indx = dependent.get_owner_indx()
+                assert owner_indx != dep_owner_indx, f"can not set self as 
dependent."
+                assert not (
+                    owner_indx > dep_owner_indx
+                    and not (dependent.itype_ == 2 and dep_owner_indx == 0)
+                ), f"dependent only can be next module interface or global 
output."
+                assert not (
+                    owner_indx == 0 and dependent.itype_ != 1
+                ), f"global input only can set dependent with module input."
+
+                self.dependent_.append(dependent)
+
+        def __init__(self, indx=0):
+            self.indx_ = indx
+            self.name_ = "mod" + str(indx) if indx else ""
+            self.interfaces_ = {1: {}, 2: {}}
+            self.target_host_ = None
+            self.mod_name_ = "default"

Review comment:
       Can we just use `self.name`?

##########
File path: python/tvm/contrib/pipeline_executor.py
##########
@@ -0,0 +1,395 @@
+# 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.
+"""Pipeline executor that executes a series of modules in a pipeline 
fashion."""
+import json
+import tvm._ffi
+from tvm import relay
+from tvm.contrib import graph_executor
+
+
+def pipeline_executor_enabled():
+    """check if pipeline executor is enabled.
+
+    Return
+    -------
+    enable: bool
+        Return pipeline executor is enabled or not.
+    """
+    return tvm._ffi.get_global_func("tvm.pipeline_executor.create",
+                                    allow_missing=True) is not None
+
+
+def build(pipe_configs):
+    """build module list that can use for pipeline execution.
+
+    Parameters
+    ----------
+    mod_n_configs: Dict[IRModule, Dict[str, Any]]
+        build configuration informaton, structure like following.
+        {IRModule: {"target":target,
+                    "target_host":target_host,
+                    "params":params,
+                    "mod_name"mod_name,
+                    "build":build}}
+
+    Returns
+    -------
+    ret: List[IRModule]
+        list of IRModule
+    string_config: Dict[int, Dict[str, any]]
+        pipeline configuration
+    """
+    mods = {}
+    mod_n_configs = pipe_configs.get_config()
+    config_len = len(mod_n_configs)
+    string_config = [{} for _ in range(config_len)]
+    #for _, (ir_mod, mod_config) in enumerate(mod_n_configs.items()):
+    for ir_mod, mod_config in mod_n_configs.items():
+        mconf = mod_config["pipeline"].copy()
+        mod_indx = mconf["mod_indx"] - 1
+        # Get mod device config
+        dev = mod_config["dev"]
+        target = mod_config["target"]
+        build_func = relay.build
+        # if there is a self defined build function then use it.
+        if "build" in mod_config and mod_config["build"]:
+            build_func = mod_config["build"]
+
+        # build IRModule
+        mod = build_func(
+            ir_mod,
+            target,
+            params=mod_config["params"],
+            target_host=mod_config["target_host"],
+            mod_name=mod_config["mod_name"],
+        )
+
+        mconf["dev"] = "{},{}".format(dev.device_type, dev.device_id)
+        # Create pipeline configuration
+        string_config[mod_indx] = mconf
+        # associate mod with device
+        mods[mod] = {"dev": dev}
+
+    # return PipeModuleConfig
+    return PipeModuleConfig(mods, string_config)
+
+
+def create(pipe_mod_config):
+    """Create a pipeline runtime executor.
+
+    Parameters
+    ----------
+
+    pipe_mod_config : PipeModuleConfig
+        class to storage IRModule list and pipeline configuration.
+
+    Returns
+    -------
+    submodule : PipelineModule
+        Runtime pipeline module.
+    """
+
+    return PipelineModule(pipe_mod_config)
+
+class PipelineModule(object):
+    """Wrapper runtime module. This is a thin wrapper of the underlying TVM 
module.
+
+    Parameters
+    ----------
+    pipeline_mods : List[GraphModule]
+        The internal tvm module that holds the actual graph functions.
+    pipeline_config : Dict[IRModule, Dict[str, Any]]
+        modules and modules dependency configuration informaiton.
+    """
+
+    def __init__(self, pipe_mod_config):
+        self.pipeline_mods_ = pipe_mod_config.pipeline_mods_
+        self.mod_config_ = pipe_mod_config.mods_config_
+        mods, config = self.graph_executor_create(self.pipeline_mods_, 
self.mod_config_)
+        assert pipeline_executor_enabled(), \
+              "Pipeline executor is not enabled. Please \
+              re-build TVM with USE_PIPELINE_EXECUTOR=ON"
+        pipelinecreate = 
tvm._ffi.get_global_func("tvm.pipeline_executor.create",
+                                                  allow_missing=False)
+        assert pipelinecreate
+        module = pipelinecreate(mods, config)
+
+        self.module_ = module
+
+    def graph_executor_create(self, pipeline_mods, mod_config):
+        """Create graph_executor list and return string format config.
+
+        Parameters
+        ----------
+
+        pipeline_mods : List[IRModule]
+          list of IRModule
+
+        mod_config : Dict[int, Dict[str, Any]]
+            modules and modules dependency configuration informaiton.
+
+        Returns
+        -------
+        mods : List[GraphModule]
+            Runtime graph module.
+
+       mod_config : str
+           mods configuration
+        """
+
+        mods = []
+        for pipeline_mod in pipeline_mods:
+            mod = graph_executor.GraphModule(
+                pipeline_mod["default"](pipeline_mods[pipeline_mod]["dev"])
+            )
+            mods.append(mod.module)
+
+        return mods, json.dumps(mod_config)
+
+
+class PipelineConfig(object):
+    """Pipeline Configuration Class, in this class there are 2 internal class,
+    first is Module which use to represent Module, second is Interface which 
use
+    to represent Module input/output and Pipeline Module input/output, by 
setting
+    dependency relation between Interfaces this class can build the module
+    connection relation.
+
+    The class Hierarchical as following.
+         PipelineConfig ---> ModuleWrapper ---> Interface(input/output)
+    """
+
+    class ModuleWrapper:
+        """The class use use to represent Module and storage module index and
+        Interface information.
+        """
+
+        class Interface:
+            """The class that use to storage module connection information.
+               There are 2 types Interface Input:1 Output:2
+            Parameters
+            ----------
+
+            owner : ModuleWrapper
+                The class that own this interface, in such class there are
+                Module information like index, module name
+
+            itype : integer
+                Interface type, 1 is input interface, 2 is output interface
+
+            name : str/integer
+                Interface name, for input that is string for example "data0"
+                for output that is integer for example 0.
+            """
+
+            def __init__(self, owner, itype, name):
+                self.owner_ = owner
+                self.itype_ = itype
+                self.name_ = str(name)
+                self.dependent_ = []
+
+            def get_name(self):
+                mname = ""
+                if self.owner_:
+                    mname = self.owner_.name_
+
+                return mname, self.name_
+
+            def get_owner_indx(self):
+                return self.owner_.indx_
+
+            def get_dependent_str(self):
+                name = ""
+                for dependent in self.dependent_:
+                    mname, dname = dependent.get_name()
+                    name = name + (mname + ":output(" + dname if self.itype_ 
== 2 else "")
+                    name = name + (")" if self.itype_ == 2 else mname + ":" + 
dname)
+                return name

Review comment:
       ```suggestion
               def __repr__(self):
                   ret = "{}\n".format(self.name)
                   for binding in self.bindings:
                       mname, dname = binding.get_name()
                       ret += "|- {0}:{1}\n".format(mname, dname)
                   return name
   ```

##########
File path: python/tvm/contrib/pipeline_executor.py
##########
@@ -0,0 +1,395 @@
+# 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.
+"""Pipeline executor that executes a series of modules in a pipeline 
fashion."""
+import json
+import tvm._ffi
+from tvm import relay
+from tvm.contrib import graph_executor
+
+
+def pipeline_executor_enabled():
+    """check if pipeline executor is enabled.
+
+    Return
+    -------
+    enable: bool
+        Return pipeline executor is enabled or not.
+    """
+    return tvm._ffi.get_global_func("tvm.pipeline_executor.create",
+                                    allow_missing=True) is not None
+
+
+def build(pipe_configs):
+    """build module list that can use for pipeline execution.
+
+    Parameters
+    ----------
+    mod_n_configs: Dict[IRModule, Dict[str, Any]]
+        build configuration informaton, structure like following.
+        {IRModule: {"target":target,
+                    "target_host":target_host,
+                    "params":params,
+                    "mod_name"mod_name,
+                    "build":build}}
+
+    Returns
+    -------
+    ret: List[IRModule]
+        list of IRModule
+    string_config: Dict[int, Dict[str, any]]
+        pipeline configuration
+    """
+    mods = {}
+    mod_n_configs = pipe_configs.get_config()
+    config_len = len(mod_n_configs)
+    string_config = [{} for _ in range(config_len)]
+    #for _, (ir_mod, mod_config) in enumerate(mod_n_configs.items()):
+    for ir_mod, mod_config in mod_n_configs.items():
+        mconf = mod_config["pipeline"].copy()
+        mod_indx = mconf["mod_indx"] - 1
+        # Get mod device config
+        dev = mod_config["dev"]
+        target = mod_config["target"]
+        build_func = relay.build
+        # if there is a self defined build function then use it.
+        if "build" in mod_config and mod_config["build"]:
+            build_func = mod_config["build"]
+
+        # build IRModule
+        mod = build_func(
+            ir_mod,
+            target,
+            params=mod_config["params"],
+            target_host=mod_config["target_host"],
+            mod_name=mod_config["mod_name"],
+        )
+
+        mconf["dev"] = "{},{}".format(dev.device_type, dev.device_id)
+        # Create pipeline configuration
+        string_config[mod_indx] = mconf
+        # associate mod with device
+        mods[mod] = {"dev": dev}
+
+    # return PipeModuleConfig
+    return PipeModuleConfig(mods, string_config)
+
+
+def create(pipe_mod_config):
+    """Create a pipeline runtime executor.
+
+    Parameters
+    ----------
+
+    pipe_mod_config : PipeModuleConfig
+        class to storage IRModule list and pipeline configuration.
+
+    Returns
+    -------
+    submodule : PipelineModule
+        Runtime pipeline module.
+    """
+
+    return PipelineModule(pipe_mod_config)
+
+class PipelineModule(object):
+    """Wrapper runtime module. This is a thin wrapper of the underlying TVM 
module.
+
+    Parameters
+    ----------
+    pipeline_mods : List[GraphModule]
+        The internal tvm module that holds the actual graph functions.
+    pipeline_config : Dict[IRModule, Dict[str, Any]]
+        modules and modules dependency configuration informaiton.
+    """
+
+    def __init__(self, pipe_mod_config):
+        self.pipeline_mods_ = pipe_mod_config.pipeline_mods_
+        self.mod_config_ = pipe_mod_config.mods_config_
+        mods, config = self.graph_executor_create(self.pipeline_mods_, 
self.mod_config_)
+        assert pipeline_executor_enabled(), \
+              "Pipeline executor is not enabled. Please \
+              re-build TVM with USE_PIPELINE_EXECUTOR=ON"
+        pipelinecreate = 
tvm._ffi.get_global_func("tvm.pipeline_executor.create",
+                                                  allow_missing=False)
+        assert pipelinecreate
+        module = pipelinecreate(mods, config)
+
+        self.module_ = module
+
+    def graph_executor_create(self, pipeline_mods, mod_config):
+        """Create graph_executor list and return string format config.
+
+        Parameters
+        ----------
+
+        pipeline_mods : List[IRModule]
+          list of IRModule
+
+        mod_config : Dict[int, Dict[str, Any]]
+            modules and modules dependency configuration informaiton.
+
+        Returns
+        -------
+        mods : List[GraphModule]
+            Runtime graph module.
+
+       mod_config : str
+           mods configuration
+        """
+
+        mods = []
+        for pipeline_mod in pipeline_mods:
+            mod = graph_executor.GraphModule(
+                pipeline_mod["default"](pipeline_mods[pipeline_mod]["dev"])
+            )
+            mods.append(mod.module)
+
+        return mods, json.dumps(mod_config)
+
+
+class PipelineConfig(object):
+    """Pipeline Configuration Class, in this class there are 2 internal class,
+    first is Module which use to represent Module, second is Interface which 
use
+    to represent Module input/output and Pipeline Module input/output, by 
setting
+    dependency relation between Interfaces this class can build the module
+    connection relation.
+
+    The class Hierarchical as following.
+         PipelineConfig ---> ModuleWrapper ---> Interface(input/output)
+    """
+
+    class ModuleWrapper:
+        """The class use use to represent Module and storage module index and
+        Interface information.
+        """
+
+        class Interface:
+            """The class that use to storage module connection information.
+               There are 2 types Interface Input:1 Output:2
+            Parameters
+            ----------
+
+            owner : ModuleWrapper
+                The class that own this interface, in such class there are
+                Module information like index, module name
+
+            itype : integer
+                Interface type, 1 is input interface, 2 is output interface
+
+            name : str/integer
+                Interface name, for input that is string for example "data0"
+                for output that is integer for example 0.
+            """
+
+            def __init__(self, owner, itype, name):
+                self.owner_ = owner
+                self.itype_ = itype
+                self.name_ = str(name)
+                self.dependent_ = []
+
+            def get_name(self):
+                mname = ""
+                if self.owner_:
+                    mname = self.owner_.name_
+
+                return mname, self.name_
+
+            def get_owner_indx(self):
+                return self.owner_.indx_
+
+            def get_dependent_str(self):
+                name = ""
+                for dependent in self.dependent_:
+                    mname, dname = dependent.get_name()
+                    name = name + (mname + ":output(" + dname if self.itype_ 
== 2 else "")
+                    name = name + (")" if self.itype_ == 2 else mname + ":" + 
dname)
+                return name
+
+            def add_dependent(self, dependent):
+                """
+                # check if the dependency setting correct.
+                # correct connection are following
+                # 1. global input to module input
+                # 2. module output to next module input
+                # 3. module output to global output
+                """
+                owner_indx = self.get_owner_indx()
+                dep_owner_indx = dependent.get_owner_indx()
+                assert owner_indx != dep_owner_indx, f"can not set self as 
dependent."
+                assert not (
+                    owner_indx > dep_owner_indx
+                    and not (dependent.itype_ == 2 and dep_owner_indx == 0)
+                ), f"dependent only can be next module interface or global 
output."
+                assert not (
+                    owner_indx == 0 and dependent.itype_ != 1
+                ), f"global input only can set dependent with module input."
+
+                self.dependent_.append(dependent)
+
+        def __init__(self, indx=0):

Review comment:
       index.

##########
File path: python/tvm/contrib/pipeline_executor.py
##########
@@ -0,0 +1,395 @@
+# 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.
+"""Pipeline executor that executes a series of modules in a pipeline 
fashion."""
+import json
+import tvm._ffi
+from tvm import relay
+from tvm.contrib import graph_executor
+
+
+def pipeline_executor_enabled():
+    """check if pipeline executor is enabled.
+
+    Return
+    -------
+    enable: bool
+        Return pipeline executor is enabled or not.
+    """
+    return tvm._ffi.get_global_func("tvm.pipeline_executor.create",
+                                    allow_missing=True) is not None
+
+
+def build(pipe_configs):
+    """build module list that can use for pipeline execution.
+
+    Parameters
+    ----------
+    mod_n_configs: Dict[IRModule, Dict[str, Any]]
+        build configuration informaton, structure like following.
+        {IRModule: {"target":target,
+                    "target_host":target_host,
+                    "params":params,
+                    "mod_name"mod_name,
+                    "build":build}}
+
+    Returns
+    -------
+    ret: List[IRModule]
+        list of IRModule
+    string_config: Dict[int, Dict[str, any]]
+        pipeline configuration
+    """
+    mods = {}
+    mod_n_configs = pipe_configs.get_config()
+    config_len = len(mod_n_configs)
+    string_config = [{} for _ in range(config_len)]
+    #for _, (ir_mod, mod_config) in enumerate(mod_n_configs.items()):
+    for ir_mod, mod_config in mod_n_configs.items():
+        mconf = mod_config["pipeline"].copy()
+        mod_indx = mconf["mod_indx"] - 1
+        # Get mod device config
+        dev = mod_config["dev"]
+        target = mod_config["target"]
+        build_func = relay.build
+        # if there is a self defined build function then use it.
+        if "build" in mod_config and mod_config["build"]:
+            build_func = mod_config["build"]
+
+        # build IRModule
+        mod = build_func(
+            ir_mod,
+            target,
+            params=mod_config["params"],
+            target_host=mod_config["target_host"],
+            mod_name=mod_config["mod_name"],
+        )
+
+        mconf["dev"] = "{},{}".format(dev.device_type, dev.device_id)
+        # Create pipeline configuration
+        string_config[mod_indx] = mconf
+        # associate mod with device
+        mods[mod] = {"dev": dev}
+
+    # return PipeModuleConfig
+    return PipeModuleConfig(mods, string_config)
+
+
+def create(pipe_mod_config):
+    """Create a pipeline runtime executor.
+
+    Parameters
+    ----------
+
+    pipe_mod_config : PipeModuleConfig
+        class to storage IRModule list and pipeline configuration.
+
+    Returns
+    -------
+    submodule : PipelineModule
+        Runtime pipeline module.
+    """
+
+    return PipelineModule(pipe_mod_config)
+
+class PipelineModule(object):
+    """Wrapper runtime module. This is a thin wrapper of the underlying TVM 
module.
+
+    Parameters
+    ----------
+    pipeline_mods : List[GraphModule]
+        The internal tvm module that holds the actual graph functions.
+    pipeline_config : Dict[IRModule, Dict[str, Any]]
+        modules and modules dependency configuration informaiton.
+    """
+
+    def __init__(self, pipe_mod_config):
+        self.pipeline_mods_ = pipe_mod_config.pipeline_mods_
+        self.mod_config_ = pipe_mod_config.mods_config_
+        mods, config = self.graph_executor_create(self.pipeline_mods_, 
self.mod_config_)
+        assert pipeline_executor_enabled(), \
+              "Pipeline executor is not enabled. Please \
+              re-build TVM with USE_PIPELINE_EXECUTOR=ON"
+        pipelinecreate = 
tvm._ffi.get_global_func("tvm.pipeline_executor.create",
+                                                  allow_missing=False)
+        assert pipelinecreate
+        module = pipelinecreate(mods, config)
+
+        self.module_ = module
+
+    def graph_executor_create(self, pipeline_mods, mod_config):
+        """Create graph_executor list and return string format config.
+
+        Parameters
+        ----------
+
+        pipeline_mods : List[IRModule]
+          list of IRModule
+
+        mod_config : Dict[int, Dict[str, Any]]
+            modules and modules dependency configuration informaiton.
+
+        Returns
+        -------
+        mods : List[GraphModule]
+            Runtime graph module.
+
+       mod_config : str
+           mods configuration
+        """
+
+        mods = []
+        for pipeline_mod in pipeline_mods:
+            mod = graph_executor.GraphModule(
+                pipeline_mod["default"](pipeline_mods[pipeline_mod]["dev"])
+            )
+            mods.append(mod.module)
+
+        return mods, json.dumps(mod_config)
+
+
+class PipelineConfig(object):
+    """Pipeline Configuration Class, in this class there are 2 internal class,
+    first is Module which use to represent Module, second is Interface which 
use
+    to represent Module input/output and Pipeline Module input/output, by 
setting
+    dependency relation between Interfaces this class can build the module
+    connection relation.
+
+    The class Hierarchical as following.
+         PipelineConfig ---> ModuleWrapper ---> Interface(input/output)
+    """
+
+    class ModuleWrapper:
+        """The class use use to represent Module and storage module index and
+        Interface information.
+        """
+
+        class Interface:
+            """The class that use to storage module connection information.
+               There are 2 types Interface Input:1 Output:2
+            Parameters
+            ----------
+
+            owner : ModuleWrapper
+                The class that own this interface, in such class there are
+                Module information like index, module name
+
+            itype : integer
+                Interface type, 1 is input interface, 2 is output interface

Review comment:
       This is confusing in terms of its name and value.
   Suggestion:
   ```
   io_type: str
       The type of this binding. It can be either "input" or "output".
   ```
   

##########
File path: python/tvm/contrib/pipeline_executor.py
##########
@@ -0,0 +1,395 @@
+# 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.
+"""Pipeline executor that executes a series of modules in a pipeline 
fashion."""
+import json
+import tvm._ffi
+from tvm import relay
+from tvm.contrib import graph_executor
+
+
+def pipeline_executor_enabled():
+    """check if pipeline executor is enabled.
+
+    Return
+    -------
+    enable: bool
+        Return pipeline executor is enabled or not.
+    """
+    return tvm._ffi.get_global_func("tvm.pipeline_executor.create",
+                                    allow_missing=True) is not None
+
+
+def build(pipe_configs):
+    """build module list that can use for pipeline execution.
+
+    Parameters
+    ----------
+    mod_n_configs: Dict[IRModule, Dict[str, Any]]
+        build configuration informaton, structure like following.
+        {IRModule: {"target":target,
+                    "target_host":target_host,
+                    "params":params,
+                    "mod_name"mod_name,
+                    "build":build}}
+
+    Returns
+    -------
+    ret: List[IRModule]
+        list of IRModule
+    string_config: Dict[int, Dict[str, any]]
+        pipeline configuration
+    """
+    mods = {}
+    mod_n_configs = pipe_configs.get_config()
+    config_len = len(mod_n_configs)
+    string_config = [{} for _ in range(config_len)]
+    #for _, (ir_mod, mod_config) in enumerate(mod_n_configs.items()):
+    for ir_mod, mod_config in mod_n_configs.items():
+        mconf = mod_config["pipeline"].copy()
+        mod_indx = mconf["mod_indx"] - 1
+        # Get mod device config
+        dev = mod_config["dev"]
+        target = mod_config["target"]
+        build_func = relay.build
+        # if there is a self defined build function then use it.
+        if "build" in mod_config and mod_config["build"]:
+            build_func = mod_config["build"]
+
+        # build IRModule
+        mod = build_func(
+            ir_mod,
+            target,
+            params=mod_config["params"],
+            target_host=mod_config["target_host"],
+            mod_name=mod_config["mod_name"],
+        )
+
+        mconf["dev"] = "{},{}".format(dev.device_type, dev.device_id)
+        # Create pipeline configuration
+        string_config[mod_indx] = mconf
+        # associate mod with device
+        mods[mod] = {"dev": dev}
+
+    # return PipeModuleConfig
+    return PipeModuleConfig(mods, string_config)
+
+
+def create(pipe_mod_config):
+    """Create a pipeline runtime executor.
+
+    Parameters
+    ----------
+
+    pipe_mod_config : PipeModuleConfig
+        class to storage IRModule list and pipeline configuration.
+
+    Returns
+    -------
+    submodule : PipelineModule
+        Runtime pipeline module.
+    """
+
+    return PipelineModule(pipe_mod_config)
+
+class PipelineModule(object):
+    """Wrapper runtime module. This is a thin wrapper of the underlying TVM 
module.
+
+    Parameters
+    ----------
+    pipeline_mods : List[GraphModule]
+        The internal tvm module that holds the actual graph functions.
+    pipeline_config : Dict[IRModule, Dict[str, Any]]
+        modules and modules dependency configuration informaiton.
+    """
+
+    def __init__(self, pipe_mod_config):
+        self.pipeline_mods_ = pipe_mod_config.pipeline_mods_
+        self.mod_config_ = pipe_mod_config.mods_config_
+        mods, config = self.graph_executor_create(self.pipeline_mods_, 
self.mod_config_)
+        assert pipeline_executor_enabled(), \
+              "Pipeline executor is not enabled. Please \
+              re-build TVM with USE_PIPELINE_EXECUTOR=ON"
+        pipelinecreate = 
tvm._ffi.get_global_func("tvm.pipeline_executor.create",
+                                                  allow_missing=False)
+        assert pipelinecreate
+        module = pipelinecreate(mods, config)
+
+        self.module_ = module
+
+    def graph_executor_create(self, pipeline_mods, mod_config):
+        """Create graph_executor list and return string format config.
+
+        Parameters
+        ----------
+
+        pipeline_mods : List[IRModule]
+          list of IRModule
+
+        mod_config : Dict[int, Dict[str, Any]]
+            modules and modules dependency configuration informaiton.
+
+        Returns
+        -------
+        mods : List[GraphModule]
+            Runtime graph module.
+
+       mod_config : str
+           mods configuration
+        """
+
+        mods = []
+        for pipeline_mod in pipeline_mods:
+            mod = graph_executor.GraphModule(
+                pipeline_mod["default"](pipeline_mods[pipeline_mod]["dev"])
+            )
+            mods.append(mod.module)
+
+        return mods, json.dumps(mod_config)
+
+
+class PipelineConfig(object):
+    """Pipeline Configuration Class, in this class there are 2 internal class,
+    first is Module which use to represent Module, second is Interface which 
use
+    to represent Module input/output and Pipeline Module input/output, by 
setting
+    dependency relation between Interfaces this class can build the module
+    connection relation.
+
+    The class Hierarchical as following.
+         PipelineConfig ---> ModuleWrapper ---> Interface(input/output)
+    """
+
+    class ModuleWrapper:
+        """The class use use to represent Module and storage module index and
+        Interface information.
+        """
+
+        class Interface:
+            """The class that use to storage module connection information.
+               There are 2 types Interface Input:1 Output:2
+            Parameters
+            ----------
+
+            owner : ModuleWrapper
+                The class that own this interface, in such class there are
+                Module information like index, module name
+
+            itype : integer
+                Interface type, 1 is input interface, 2 is output interface
+
+            name : str/integer
+                Interface name, for input that is string for example "data0"
+                for output that is integer for example 0.
+            """
+
+            def __init__(self, owner, itype, name):
+                self.owner_ = owner
+                self.itype_ = itype
+                self.name_ = str(name)
+                self.dependent_ = []
+
+            def get_name(self):
+                mname = ""
+                if self.owner_:
+                    mname = self.owner_.name_
+
+                return mname, self.name_
+
+            def get_owner_indx(self):
+                return self.owner_.indx_
+
+            def get_dependent_str(self):
+                name = ""
+                for dependent in self.dependent_:
+                    mname, dname = dependent.get_name()
+                    name = name + (mname + ":output(" + dname if self.itype_ 
== 2 else "")
+                    name = name + (")" if self.itype_ == 2 else mname + ":" + 
dname)
+                return name
+
+            def add_dependent(self, dependent):
+                """
+                # check if the dependency setting correct.
+                # correct connection are following
+                # 1. global input to module input
+                # 2. module output to next module input
+                # 3. module output to global output
+                """
+                owner_indx = self.get_owner_indx()
+                dep_owner_indx = dependent.get_owner_indx()
+                assert owner_indx != dep_owner_indx, f"can not set self as 
dependent."
+                assert not (
+                    owner_indx > dep_owner_indx
+                    and not (dependent.itype_ == 2 and dep_owner_indx == 0)
+                ), f"dependent only can be next module interface or global 
output."
+                assert not (
+                    owner_indx == 0 and dependent.itype_ != 1
+                ), f"global input only can set dependent with module input."
+
+                self.dependent_.append(dependent)
+
+        def __init__(self, indx=0):
+            self.indx_ = indx
+            self.name_ = "mod" + str(indx) if indx else ""

Review comment:
       What's the problem with `mod0`?  You need a docstring for this 
constructor.
   ```suggestion
               self.name = "mod{}".format(str(index) if index else "")
   ```

##########
File path: python/tvm/contrib/pipeline_executor.py
##########
@@ -0,0 +1,395 @@
+# 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.
+"""Pipeline executor that executes a series of modules in a pipeline 
fashion."""
+import json
+import tvm._ffi
+from tvm import relay
+from tvm.contrib import graph_executor
+
+
+def pipeline_executor_enabled():
+    """check if pipeline executor is enabled.
+
+    Return
+    -------
+    enable: bool
+        Return pipeline executor is enabled or not.
+    """
+    return tvm._ffi.get_global_func("tvm.pipeline_executor.create",
+                                    allow_missing=True) is not None
+
+
+def build(pipe_configs):
+    """build module list that can use for pipeline execution.
+
+    Parameters
+    ----------
+    mod_n_configs: Dict[IRModule, Dict[str, Any]]
+        build configuration informaton, structure like following.
+        {IRModule: {"target":target,
+                    "target_host":target_host,
+                    "params":params,
+                    "mod_name"mod_name,
+                    "build":build}}
+
+    Returns
+    -------
+    ret: List[IRModule]
+        list of IRModule
+    string_config: Dict[int, Dict[str, any]]
+        pipeline configuration
+    """
+    mods = {}
+    mod_n_configs = pipe_configs.get_config()
+    config_len = len(mod_n_configs)
+    string_config = [{} for _ in range(config_len)]
+    #for _, (ir_mod, mod_config) in enumerate(mod_n_configs.items()):
+    for ir_mod, mod_config in mod_n_configs.items():
+        mconf = mod_config["pipeline"].copy()
+        mod_indx = mconf["mod_indx"] - 1
+        # Get mod device config
+        dev = mod_config["dev"]
+        target = mod_config["target"]
+        build_func = relay.build
+        # if there is a self defined build function then use it.
+        if "build" in mod_config and mod_config["build"]:
+            build_func = mod_config["build"]
+
+        # build IRModule
+        mod = build_func(
+            ir_mod,
+            target,
+            params=mod_config["params"],
+            target_host=mod_config["target_host"],
+            mod_name=mod_config["mod_name"],
+        )
+
+        mconf["dev"] = "{},{}".format(dev.device_type, dev.device_id)
+        # Create pipeline configuration
+        string_config[mod_indx] = mconf
+        # associate mod with device
+        mods[mod] = {"dev": dev}
+
+    # return PipeModuleConfig
+    return PipeModuleConfig(mods, string_config)
+
+
+def create(pipe_mod_config):
+    """Create a pipeline runtime executor.
+
+    Parameters
+    ----------
+
+    pipe_mod_config : PipeModuleConfig
+        class to storage IRModule list and pipeline configuration.
+
+    Returns
+    -------
+    submodule : PipelineModule
+        Runtime pipeline module.
+    """
+
+    return PipelineModule(pipe_mod_config)
+
+class PipelineModule(object):
+    """Wrapper runtime module. This is a thin wrapper of the underlying TVM 
module.
+
+    Parameters
+    ----------
+    pipeline_mods : List[GraphModule]
+        The internal tvm module that holds the actual graph functions.
+    pipeline_config : Dict[IRModule, Dict[str, Any]]
+        modules and modules dependency configuration informaiton.
+    """
+
+    def __init__(self, pipe_mod_config):
+        self.pipeline_mods_ = pipe_mod_config.pipeline_mods_
+        self.mod_config_ = pipe_mod_config.mods_config_
+        mods, config = self.graph_executor_create(self.pipeline_mods_, 
self.mod_config_)
+        assert pipeline_executor_enabled(), \
+              "Pipeline executor is not enabled. Please \
+              re-build TVM with USE_PIPELINE_EXECUTOR=ON"
+        pipelinecreate = 
tvm._ffi.get_global_func("tvm.pipeline_executor.create",
+                                                  allow_missing=False)
+        assert pipelinecreate
+        module = pipelinecreate(mods, config)
+
+        self.module_ = module
+
+    def graph_executor_create(self, pipeline_mods, mod_config):
+        """Create graph_executor list and return string format config.
+
+        Parameters
+        ----------
+
+        pipeline_mods : List[IRModule]
+          list of IRModule
+
+        mod_config : Dict[int, Dict[str, Any]]
+            modules and modules dependency configuration informaiton.
+
+        Returns
+        -------
+        mods : List[GraphModule]
+            Runtime graph module.
+
+       mod_config : str
+           mods configuration
+        """
+
+        mods = []
+        for pipeline_mod in pipeline_mods:
+            mod = graph_executor.GraphModule(
+                pipeline_mod["default"](pipeline_mods[pipeline_mod]["dev"])
+            )
+            mods.append(mod.module)
+
+        return mods, json.dumps(mod_config)
+
+
+class PipelineConfig(object):
+    """Pipeline Configuration Class, in this class there are 2 internal class,
+    first is Module which use to represent Module, second is Interface which 
use
+    to represent Module input/output and Pipeline Module input/output, by 
setting
+    dependency relation between Interfaces this class can build the module
+    connection relation.
+
+    The class Hierarchical as following.
+         PipelineConfig ---> ModuleWrapper ---> Interface(input/output)

Review comment:
       Update the docstring accordingly. I would focus on the functionality 
instead of implementation. For example:
   
   ```
   The wrapper of each module to be pipelined. The wrapper mainly includes the 
module itself as well as
   the binding that represents the connections of this module's inputs and 
outputs to other modules.
   ```

##########
File path: python/tvm/contrib/pipeline_executor.py
##########
@@ -0,0 +1,395 @@
+# 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.
+"""Pipeline executor that executes a series of modules in a pipeline 
fashion."""
+import json
+import tvm._ffi
+from tvm import relay
+from tvm.contrib import graph_executor
+
+
+def pipeline_executor_enabled():
+    """check if pipeline executor is enabled.
+
+    Return
+    -------
+    enable: bool
+        Return pipeline executor is enabled or not.
+    """
+    return tvm._ffi.get_global_func("tvm.pipeline_executor.create",
+                                    allow_missing=True) is not None
+
+
+def build(pipe_configs):
+    """build module list that can use for pipeline execution.
+
+    Parameters
+    ----------
+    mod_n_configs: Dict[IRModule, Dict[str, Any]]
+        build configuration informaton, structure like following.
+        {IRModule: {"target":target,
+                    "target_host":target_host,
+                    "params":params,
+                    "mod_name"mod_name,
+                    "build":build}}
+
+    Returns
+    -------
+    ret: List[IRModule]
+        list of IRModule
+    string_config: Dict[int, Dict[str, any]]
+        pipeline configuration
+    """
+    mods = {}
+    mod_n_configs = pipe_configs.get_config()
+    config_len = len(mod_n_configs)
+    string_config = [{} for _ in range(config_len)]
+    #for _, (ir_mod, mod_config) in enumerate(mod_n_configs.items()):
+    for ir_mod, mod_config in mod_n_configs.items():
+        mconf = mod_config["pipeline"].copy()
+        mod_indx = mconf["mod_indx"] - 1
+        # Get mod device config
+        dev = mod_config["dev"]
+        target = mod_config["target"]
+        build_func = relay.build
+        # if there is a self defined build function then use it.
+        if "build" in mod_config and mod_config["build"]:
+            build_func = mod_config["build"]
+
+        # build IRModule
+        mod = build_func(
+            ir_mod,
+            target,
+            params=mod_config["params"],
+            target_host=mod_config["target_host"],
+            mod_name=mod_config["mod_name"],
+        )
+
+        mconf["dev"] = "{},{}".format(dev.device_type, dev.device_id)
+        # Create pipeline configuration
+        string_config[mod_indx] = mconf
+        # associate mod with device
+        mods[mod] = {"dev": dev}
+
+    # return PipeModuleConfig
+    return PipeModuleConfig(mods, string_config)
+
+
+def create(pipe_mod_config):
+    """Create a pipeline runtime executor.
+
+    Parameters
+    ----------
+
+    pipe_mod_config : PipeModuleConfig
+        class to storage IRModule list and pipeline configuration.
+
+    Returns
+    -------
+    submodule : PipelineModule
+        Runtime pipeline module.
+    """
+
+    return PipelineModule(pipe_mod_config)
+
+class PipelineModule(object):
+    """Wrapper runtime module. This is a thin wrapper of the underlying TVM 
module.
+
+    Parameters
+    ----------
+    pipeline_mods : List[GraphModule]
+        The internal tvm module that holds the actual graph functions.
+    pipeline_config : Dict[IRModule, Dict[str, Any]]
+        modules and modules dependency configuration informaiton.
+    """
+
+    def __init__(self, pipe_mod_config):
+        self.pipeline_mods_ = pipe_mod_config.pipeline_mods_
+        self.mod_config_ = pipe_mod_config.mods_config_
+        mods, config = self.graph_executor_create(self.pipeline_mods_, 
self.mod_config_)
+        assert pipeline_executor_enabled(), \
+              "Pipeline executor is not enabled. Please \
+              re-build TVM with USE_PIPELINE_EXECUTOR=ON"
+        pipelinecreate = 
tvm._ffi.get_global_func("tvm.pipeline_executor.create",
+                                                  allow_missing=False)
+        assert pipelinecreate
+        module = pipelinecreate(mods, config)
+
+        self.module_ = module
+
+    def graph_executor_create(self, pipeline_mods, mod_config):
+        """Create graph_executor list and return string format config.
+
+        Parameters
+        ----------
+
+        pipeline_mods : List[IRModule]
+          list of IRModule
+
+        mod_config : Dict[int, Dict[str, Any]]
+            modules and modules dependency configuration informaiton.
+
+        Returns
+        -------
+        mods : List[GraphModule]
+            Runtime graph module.
+
+       mod_config : str
+           mods configuration
+        """
+
+        mods = []
+        for pipeline_mod in pipeline_mods:
+            mod = graph_executor.GraphModule(
+                pipeline_mod["default"](pipeline_mods[pipeline_mod]["dev"])
+            )
+            mods.append(mod.module)
+
+        return mods, json.dumps(mod_config)
+
+
+class PipelineConfig(object):
+    """Pipeline Configuration Class, in this class there are 2 internal class,
+    first is Module which use to represent Module, second is Interface which 
use
+    to represent Module input/output and Pipeline Module input/output, by 
setting
+    dependency relation between Interfaces this class can build the module
+    connection relation.
+
+    The class Hierarchical as following.
+         PipelineConfig ---> ModuleWrapper ---> Interface(input/output)
+    """
+
+    class ModuleWrapper:
+        """The class use use to represent Module and storage module index and
+        Interface information.
+        """
+
+        class Interface:
+            """The class that use to storage module connection information.
+               There are 2 types Interface Input:1 Output:2
+            Parameters
+            ----------
+
+            owner : ModuleWrapper
+                The class that own this interface, in such class there are
+                Module information like index, module name
+
+            itype : integer
+                Interface type, 1 is input interface, 2 is output interface
+
+            name : str/integer
+                Interface name, for input that is string for example "data0"
+                for output that is integer for example 0.
+            """
+
+            def __init__(self, owner, itype, name):
+                self.owner_ = owner
+                self.itype_ = itype
+                self.name_ = str(name)
+                self.dependent_ = []
+
+            def get_name(self):
+                mname = ""
+                if self.owner_:
+                    mname = self.owner_.name_
+
+                return mname, self.name_
+
+            def get_owner_indx(self):
+                return self.owner_.indx_
+
+            def get_dependent_str(self):
+                name = ""
+                for dependent in self.dependent_:
+                    mname, dname = dependent.get_name()
+                    name = name + (mname + ":output(" + dname if self.itype_ 
== 2 else "")
+                    name = name + (")" if self.itype_ == 2 else mname + ":" + 
dname)
+                return name
+
+            def add_dependent(self, dependent):
+                """
+                # check if the dependency setting correct.
+                # correct connection are following
+                # 1. global input to module input
+                # 2. module output to next module input
+                # 3. module output to global output
+                """
+                owner_indx = self.get_owner_indx()
+                dep_owner_indx = dependent.get_owner_indx()
+                assert owner_indx != dep_owner_indx, f"can not set self as 
dependent."
+                assert not (
+                    owner_indx > dep_owner_indx
+                    and not (dependent.itype_ == 2 and dep_owner_indx == 0)
+                ), f"dependent only can be next module interface or global 
output."
+                assert not (
+                    owner_indx == 0 and dependent.itype_ != 1
+                ), f"global input only can set dependent with module input."
+
+                self.dependent_.append(dependent)
+
+        def __init__(self, indx=0):
+            self.indx_ = indx
+            self.name_ = "mod" + str(indx) if indx else ""
+            self.interfaces_ = {1: {}, 2: {}}
+            self.target_host_ = None
+            self.mod_name_ = "default"
+            self.build_func_ = None
+            self.params_ = None
+            self.target_ = None
+            self.dev_ = None
+
+
+        def get_interface(self, itype, name):
+            if name not in self.interfaces_[itype]:
+                self.interfaces_[itype][name] = self.Interface(self, itype, 
name)
+
+            return self.interfaces_[itype][name]
+
+        def input(self, name):
+            return self.get_interface(1, name)
+
+        def output(self, index):
+            return self.get_interface(2, index)
+
+        def set_target_host(self, host):
+            self.target_host_ = host
+
+        def set_mod_name(self, name):
+            self.mod_name_ = name
+
+        def set_build_func(self, build_func):
+            self.build_func_ = build_func
+
+        def set_params(self, params):
+            self.params_ = params
+
+        def set_target(self, target):
+            self.target_ = target
+
+        def set_dev(self, dev):
+            self.dev_ = dev
+
+    def __init__(self, mods):
+        self.pipe_module_name_ = "pipeline_module"
+        self.mod_wrapper = {m: self.ModuleWrapper(i + 1) for m, i in zip(mods, 
range(len(mods)))}
+        self.mod_wrapper[self.pipe_module_name_] = self.ModuleWrapper(0)

Review comment:
       As I mentioned before, I don't think we need to enforce the pipeline 
inputs to be the inputs of the first module. For example, we should support:
   
   ```
   data0 -> mod0 -> mod1 -> output
   data1 -------------|
   ```

##########
File path: python/tvm/contrib/pipeline_executor.py
##########
@@ -0,0 +1,395 @@
+# 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.
+"""Pipeline executor that executes a series of modules in a pipeline 
fashion."""
+import json
+import tvm._ffi
+from tvm import relay
+from tvm.contrib import graph_executor
+
+
+def pipeline_executor_enabled():
+    """check if pipeline executor is enabled.
+
+    Return
+    -------
+    enable: bool
+        Return pipeline executor is enabled or not.
+    """
+    return tvm._ffi.get_global_func("tvm.pipeline_executor.create",
+                                    allow_missing=True) is not None
+
+
+def build(pipe_configs):
+    """build module list that can use for pipeline execution.
+
+    Parameters
+    ----------
+    mod_n_configs: Dict[IRModule, Dict[str, Any]]
+        build configuration informaton, structure like following.
+        {IRModule: {"target":target,
+                    "target_host":target_host,
+                    "params":params,
+                    "mod_name"mod_name,
+                    "build":build}}
+
+    Returns
+    -------
+    ret: List[IRModule]
+        list of IRModule
+    string_config: Dict[int, Dict[str, any]]
+        pipeline configuration
+    """
+    mods = {}
+    mod_n_configs = pipe_configs.get_config()
+    config_len = len(mod_n_configs)
+    string_config = [{} for _ in range(config_len)]
+    #for _, (ir_mod, mod_config) in enumerate(mod_n_configs.items()):
+    for ir_mod, mod_config in mod_n_configs.items():
+        mconf = mod_config["pipeline"].copy()
+        mod_indx = mconf["mod_indx"] - 1
+        # Get mod device config
+        dev = mod_config["dev"]
+        target = mod_config["target"]
+        build_func = relay.build
+        # if there is a self defined build function then use it.
+        if "build" in mod_config and mod_config["build"]:
+            build_func = mod_config["build"]
+
+        # build IRModule
+        mod = build_func(
+            ir_mod,
+            target,
+            params=mod_config["params"],
+            target_host=mod_config["target_host"],
+            mod_name=mod_config["mod_name"],
+        )
+
+        mconf["dev"] = "{},{}".format(dev.device_type, dev.device_id)
+        # Create pipeline configuration
+        string_config[mod_indx] = mconf
+        # associate mod with device
+        mods[mod] = {"dev": dev}
+
+    # return PipeModuleConfig
+    return PipeModuleConfig(mods, string_config)
+
+
+def create(pipe_mod_config):
+    """Create a pipeline runtime executor.
+
+    Parameters
+    ----------
+
+    pipe_mod_config : PipeModuleConfig
+        class to storage IRModule list and pipeline configuration.
+
+    Returns
+    -------
+    submodule : PipelineModule
+        Runtime pipeline module.
+    """
+
+    return PipelineModule(pipe_mod_config)
+
+class PipelineModule(object):
+    """Wrapper runtime module. This is a thin wrapper of the underlying TVM 
module.
+
+    Parameters
+    ----------
+    pipeline_mods : List[GraphModule]
+        The internal tvm module that holds the actual graph functions.
+    pipeline_config : Dict[IRModule, Dict[str, Any]]
+        modules and modules dependency configuration informaiton.
+    """
+
+    def __init__(self, pipe_mod_config):
+        self.pipeline_mods_ = pipe_mod_config.pipeline_mods_
+        self.mod_config_ = pipe_mod_config.mods_config_
+        mods, config = self.graph_executor_create(self.pipeline_mods_, 
self.mod_config_)
+        assert pipeline_executor_enabled(), \
+              "Pipeline executor is not enabled. Please \
+              re-build TVM with USE_PIPELINE_EXECUTOR=ON"
+        pipelinecreate = 
tvm._ffi.get_global_func("tvm.pipeline_executor.create",
+                                                  allow_missing=False)
+        assert pipelinecreate
+        module = pipelinecreate(mods, config)
+
+        self.module_ = module
+
+    def graph_executor_create(self, pipeline_mods, mod_config):
+        """Create graph_executor list and return string format config.
+
+        Parameters
+        ----------
+
+        pipeline_mods : List[IRModule]
+          list of IRModule
+
+        mod_config : Dict[int, Dict[str, Any]]
+            modules and modules dependency configuration informaiton.
+
+        Returns
+        -------
+        mods : List[GraphModule]
+            Runtime graph module.
+
+       mod_config : str
+           mods configuration
+        """
+
+        mods = []
+        for pipeline_mod in pipeline_mods:
+            mod = graph_executor.GraphModule(
+                pipeline_mod["default"](pipeline_mods[pipeline_mod]["dev"])
+            )
+            mods.append(mod.module)
+
+        return mods, json.dumps(mod_config)
+
+
+class PipelineConfig(object):
+    """Pipeline Configuration Class, in this class there are 2 internal class,
+    first is Module which use to represent Module, second is Interface which 
use
+    to represent Module input/output and Pipeline Module input/output, by 
setting
+    dependency relation between Interfaces this class can build the module
+    connection relation.
+
+    The class Hierarchical as following.
+         PipelineConfig ---> ModuleWrapper ---> Interface(input/output)
+    """
+
+    class ModuleWrapper:
+        """The class use use to represent Module and storage module index and
+        Interface information.
+        """
+
+        class Interface:
+            """The class that use to storage module connection information.
+               There are 2 types Interface Input:1 Output:2
+            Parameters
+            ----------
+
+            owner : ModuleWrapper
+                The class that own this interface, in such class there are
+                Module information like index, module name
+
+            itype : integer
+                Interface type, 1 is input interface, 2 is output interface
+
+            name : str/integer
+                Interface name, for input that is string for example "data0"
+                for output that is integer for example 0.
+            """
+
+            def __init__(self, owner, itype, name):
+                self.owner_ = owner
+                self.itype_ = itype
+                self.name_ = str(name)
+                self.dependent_ = []
+
+            def get_name(self):
+                mname = ""
+                if self.owner_:
+                    mname = self.owner_.name_
+
+                return mname, self.name_
+
+            def get_owner_indx(self):
+                return self.owner_.indx_
+
+            def get_dependent_str(self):
+                name = ""
+                for dependent in self.dependent_:
+                    mname, dname = dependent.get_name()
+                    name = name + (mname + ":output(" + dname if self.itype_ 
== 2 else "")
+                    name = name + (")" if self.itype_ == 2 else mname + ":" + 
dname)
+                return name
+
+            def add_dependent(self, dependent):
+                """
+                # check if the dependency setting correct.
+                # correct connection are following
+                # 1. global input to module input
+                # 2. module output to next module input
+                # 3. module output to global output
+                """
+                owner_indx = self.get_owner_indx()
+                dep_owner_indx = dependent.get_owner_indx()
+                assert owner_indx != dep_owner_indx, f"can not set self as 
dependent."
+                assert not (
+                    owner_indx > dep_owner_indx
+                    and not (dependent.itype_ == 2 and dep_owner_indx == 0)
+                ), f"dependent only can be next module interface or global 
output."
+                assert not (
+                    owner_indx == 0 and dependent.itype_ != 1
+                ), f"global input only can set dependent with module input."
+
+                self.dependent_.append(dependent)
+
+        def __init__(self, indx=0):
+            self.indx_ = indx
+            self.name_ = "mod" + str(indx) if indx else ""
+            self.interfaces_ = {1: {}, 2: {}}
+            self.target_host_ = None
+            self.mod_name_ = "default"
+            self.build_func_ = None
+            self.params_ = None
+            self.target_ = None
+            self.dev_ = None
+
+
+        def get_interface(self, itype, name):
+            if name not in self.interfaces_[itype]:
+                self.interfaces_[itype][name] = self.Interface(self, itype, 
name)
+
+            return self.interfaces_[itype][name]
+
+        def input(self, name):
+            return self.get_interface(1, name)
+
+        def output(self, index):
+            return self.get_interface(2, index)
+
+        def set_target_host(self, host):
+            self.target_host_ = host
+
+        def set_mod_name(self, name):
+            self.mod_name_ = name
+
+        def set_build_func(self, build_func):
+            self.build_func_ = build_func
+
+        def set_params(self, params):
+            self.params_ = params
+
+        def set_target(self, target):
+            self.target_ = target
+
+        def set_dev(self, dev):
+            self.dev_ = dev
+
+    def __init__(self, mods):
+        self.pipe_module_name_ = "pipeline_module"
+        self.mod_wrapper = {m: self.ModuleWrapper(i + 1) for m, i in zip(mods, 
range(len(mods)))}

Review comment:
       I feel this is a bit weird. It means when users specify 
`PipelineModuleConfig([mod0, mod1])`, they already specify the order. However, 
they still need to specify the connections later on. It would be better to have 
something like the following:
   
   ```
   config = PipelineModuleConfig()
   config[mod1].input("data0", config.pipeline_input("data0"))
   config[mod2].input("data0", config.pipeline_input("data1"))
   config[mod2].input("data1", config[mod2].output(0))
   config[mod2].output(0, config.pipeline_output(0))
   ```
   
   When `__getitem__` in pipeline module config sees a new module, it 
initializes its ModuleWrapper.
   
   The side effect of this approach is that we cannot check if a connection is 
legal when adding a new connection. However, we can still check that later when 
exporting the config by leveraging topological sort.




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscr...@tvm.apache.org

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


Reply via email to