vm.py 6.06 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
# License .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.
17
# pylint: disable=no-else-return, unidiomatic-typecheck, undefined-variable, invalid-name
18 19 20 21 22
"""
The Relay Virtual Vachine.

Implements a Python interface to compiling and executing on the Relay VM.
"""
23 24
import numpy as np

25 26
import tvm
from . import _vm
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
from . import vmobj as _obj
from .interpreter import Executor


def _update_target(target):
    target = target if target else tvm.target.current_target()
    if target is None:
        raise ValueError("Target is not set in env or passed as argument.")

    tgts = {}
    if isinstance(target, (str, tvm.target.Target)):
        dev_type = tvm.expr.IntImm("int32", tvm.nd.context(str(target)).device_type)
        tgts[dev_type] = tvm.target.create(target)
    elif isinstance(target, dict):
        for dev, tgt in target.items():
            dev_type = tvm.expr.IntImm("int32", tvm.nd.context(dev).device_type)
            tgts[dev_type] = tvm.target.create(tgt)
    else:
        raise TypeError("target is expected to be str, tvm.target.Target, " +
                        "or dict of str to str/tvm.target.Target, but received " +
                        "{}".format(type(target)))
    return tgts
49 50

def _convert(arg, cargs):
51 52 53
    if isinstance(arg, (np.ndarray, tvm.nd.NDArray)):
        cargs.append(_obj.tensor_object(arg))
    elif isinstance(arg, (tuple, list)):
54 55 56
        field_args = []
        for field in arg:
            _convert(field, field_args)
57
        cargs.append(_obj.tuple_object(field_args))
58 59 60 61 62 63 64 65 66 67 68
    else:
        raise "unsupported type"

def convert(args):
    cargs = []
    for arg in args:
        _convert(arg, cargs)

    return cargs


69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
class VirtualMachine(object):
    """Relay VM runtime."""
    def __init__(self, mod):
        self.mod = mod
        self._init = self.mod["init"]
        self._invoke = self.mod["invoke"]

    def init(self, ctx):
        """Initialize the context in the VM.

        Parameters
        ----------
        ctx : :py:class:`TVMContext`
            The runtime context to run the code on.
        """
        args = [ctx.device_type, ctx.device_id]
        self._init(*args)

    def invoke(self, func_name, *args):
        """Invoke a function.

        Parameters
        ----------
        func_name : str
            The name of the function.

        args : list[NDArray] or list[np.ndarray]
            The arguments to the function.

        Returns
        -------
        result : Object
            The output.
        """
        cargs = convert(args)
        return self._invoke(func_name, *cargs)

    def run(self, *args):
        """Run the main function.

        Parameters
        ----------
        args : list[NDArray] or list[np.ndarray]
            The arguments to the function.

        Returns
        -------
        result : Object
            The output.
        """
        return self.invoke("main", *args)


class VMCompiler(object):
    """Build Relay module to run on VM runtime."""
    def __init__(self):
        self.mod = _vm._VMCompiler()
        self._compile = self.mod["compile"]
        self._get_vm = self.mod["get_vm"]

    def compile(self, mod, target=None, target_host=None):
        """
        Parameters
        ----------
        mod : relay.Module
            The Relay module to build.

        target : str, :any:`tvm.target.Target`, or dict of str(i.e.
            device/context name) to str/tvm.target.Target, optional
            For heterogeneous compilation, it is a dictionary indicating context
            to target mapping. For homogeneous compilation, it is a build target.

        target_host : str or :any:`tvm.target.Target`, optional
            Host compilation target, if target is device.
            When TVM compiles device specific program such as CUDA,
            we also need host(CPU) side code to interact with the driver
            to setup the dimensions and parameters correctly.
            target_host is used to specify the host side codegen target.
            By default, llvm is used if it is enabled,
            otherwise a stackvm intepreter is used.

        Returns
        -------
        vm : VirtualMachine
            The VM runtime.
        """
        target = _update_target(target)
        self._compile(mod, target, target_host)
        return VirtualMachine(self._get_vm())
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180


class VMExecutor(Executor):
    """
    An implementation of the executor interface for
    the Relay VM.

    Useful interface for experimentation and debugging
    the VM can also be used directly from the API.
    supported by `tvm.relay.vm`.

    Parameters
    ----------
    mod : :py:class:`~tvm.relay.module.Module`
        The module to support the execution.

    ctx : :py:class:`TVMContext`
        The runtime context to run the code on.

    target : :py:class:`Target`
        The target option to build the function.
    """
    def __init__(self, mod, ctx, target):
181 182
        if mod is None:
            raise RuntimeError("Must provide module to get VM executor.")
183 184 185
        self.mod = mod
        self.ctx = ctx
        self.target = target
186 187 188
        compiler = VMCompiler()
        self.vm = compiler.compile(mod, target)
        self.vm.init(ctx)
189

190
    def _make_executor(self, expr=None):
191
        assert expr is None
192
        main = self.mod["main"]
193 194 195

        def _vm_wrapper(*args, **kwargs):
            args = self._convert_args(main, args, kwargs)
196
            return self.vm.run(*args)
197 198

        return _vm_wrapper