Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Relay][VM] Port VM, VM compiler, and Object into python #3391

Merged
merged 12 commits into from
Jul 16, 2019
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
update
icemelon committed Jul 15, 2019
commit 3126fc13d5ccf2eefb954b9fbc325e949eb9ff3b
1 change: 0 additions & 1 deletion python/tvm/__init__.py
Original file line number Diff line number Diff line change
@@ -43,7 +43,6 @@
from . import ndarray as nd
from .ndarray import context, cpu, gpu, opencl, cl, vulkan, metal, mtl
from .ndarray import vpi, rocm, opengl, ext_dev
from . import object

from ._ffi.runtime_ctypes import TypeCode, TVMType
from ._ffi.ndarray import TVMContext
1 change: 1 addition & 0 deletions python/tvm/relay/__init__.py
Original file line number Diff line number Diff line change
@@ -34,6 +34,7 @@
from . import param_dict
from . import feature
from .backend import vm
from .backend import vmobj

# Root operators
from .op import Op
20 changes: 20 additions & 0 deletions python/tvm/relay/backend/_vmobj.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# 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.
"""The VM Object FFI namespace."""
from tvm._ffi.function import _init_api

_init_api("_vmobj", __name__)
2 changes: 1 addition & 1 deletion python/tvm/relay/backend/interpreter.py
Original file line number Diff line number Diff line change
@@ -243,7 +243,7 @@ def evaluate(self, expr=None, binds=None):
assert not analysis.free_vars(expr)

if isinstance(expr, (Function, GlobalVar)):
return self._make_executor(expr)
return self._make_executor(expr)

# normal expression evaluated by running a function.
func = Function([], expr)
109 changes: 30 additions & 79 deletions python/tvm/relay/backend/vm.py
Original file line number Diff line number Diff line change
@@ -23,9 +23,10 @@
import numpy as np

import tvm
from . import _vm
from . import vmobj as _obj
from .. import transform
from ..expr import GlobalVar, Expr
from . import _vm
from .interpreter import Executor


@@ -48,6 +49,24 @@ def _update_target(target):
"{}".format(type(target)))
return tgts

def _convert(arg, cargs):
if isinstance(arg, (np.ndarray, tvm.nd.NDArray)):
cargs.append(_obj.tensor_object(arg))
elif isinstance(arg, (tuple, list)):
field_args = []
for field in arg:
_convert(field, field_args)
cargs.append(_obj.tuple_object(field_args))
else:
raise "unsupported type"

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

return cargs


class VirtualMachine(object):
"""Relay VM runtime."""
@@ -102,7 +121,6 @@ def run(self, *args):
return self.invoke("main", *args)



class BuildModule(object):
"""Build Relay module to run on VM runtime."""
def __init__(self):
@@ -141,80 +159,6 @@ def compile(self, mod, target=None, target_host=None):
return VirtualMachine(self._get_vm())


def optimize(mod):
"""Perform several optimizations on a module before executing it in the
Relay virtual machine.

Parameters
----------
mod : tvm.relay.Module
The module to optimize.

Returns
-------
ret : tvm.relay.Module
The optimized module.
"""
main_func = mod["main"]

opt_passes = []
if not main_func.params and isinstance(main_func.body, GlobalVar):
opt_passes.append(transform.EtaExpand())

opt_passes = opt_passes + [
transform.SimplifyInference(),
transform.FuseOps(),
transform.InferType()
]

seq = transform.Sequential(opt_passes)
return seq(mod)

def _convert(arg, cargs):
if isinstance(arg, np.ndarray):
tensor = _vm._Tensor(tvm.nd.array(arg))
cargs.append(tensor)
elif isinstance(arg, tvm.nd.NDArray):
tensor = _vm._Tensor(arg)
cargs.append(tensor)
elif isinstance(arg, tuple):
field_args = []
for field in arg:
_convert(field, field_args)
cargs.append(_vm._Tuple(*field_args))
else:
raise "unsupported type"

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

return cargs

def _eval_vm(mod, ctx, *args):
"""
Evaluate a module on a given context with the provided arguments.

Parameters
----------
mod: relay.Module
The module to optimize, will execute its entry_func.

ctx: tvm.Context
The TVM context to execute on.

args: List[tvm.NDArray, np.ndarray]
The arguments to evaluate.
"""
mod = optimize(mod)
args = list(args)
assert isinstance(args, list)
cargs = convert(args)

result = _vm._evaluate_vm(mod, ctx.device_type, ctx.device_id, *cargs)
return result

class VMExecutor(Executor):
"""
An implementation of the executor interface for
@@ -236,20 +180,27 @@ class VMExecutor(Executor):
The target option to build the function.
"""
def __init__(self, mod, ctx, target):
assert mod is not None
icemelon marked this conversation as resolved.
Show resolved Hide resolved
self.mod = mod
self.ctx = ctx
self.target = target
build_mod = BuildModule()
self.vm = build_mod.compile(mod, target)
self.vm.init(ctx)

<<<<<<< HEAD
def _make_executor(self, expr=None):
expr = expr if expr else self.mod
assert expr, "either expr or self.mod should be not null."
if isinstance(expr, Expr):
self.mod["main"] = expr
main = self.mod["main"]

=======
def _make_executor(self):
main = self.mod[self.mod.entry_func]
>>>>>>> update
def _vm_wrapper(*args, **kwargs):
args = self._convert_args(main, args, kwargs)
print(type(args[0]))
return _eval_vm(self.mod, self.ctx, *args)

return self.vm.run(*args)
return _vm_wrapper
83 changes: 74 additions & 9 deletions python/tvm/object.py → python/tvm/relay/backend/vmobj.py
Original file line number Diff line number Diff line change
@@ -15,11 +15,12 @@
# specific language governing permissions and limitations
# under the License.
"""TVM Runtime Object API."""
from __future__ import absolute_import as _abs
import numpy as _np

from ._ffi.function import _init_api
from ._ffi.object import ObjectBase, ObjectTag, register_object

_init_api("tvm.object", __name__)
from tvm._ffi.object import ObjectBase, ObjectTag, register_object
from tvm import ndarray as _nd
from . import _vmobj

icemelon marked this conversation as resolved.
Show resolved Hide resolved
@register_object
class TensorObject(ObjectBase):
@@ -40,11 +41,11 @@ def __init__(self, handle):
A tensor object.
"""
super(TensorObject, self).__init__(handle)
self.data = GetTensorData(self)
self.data = _vmobj.GetTensorData(self)

def asnumpy(self):
"""Convert data to numpy array
n

Returns
-------
np_arr : numpy.ndarray
@@ -72,13 +73,77 @@ def __init__(self, handle):
A tensor object.
icemelon marked this conversation as resolved.
Show resolved Hide resolved
"""
super(DatatypeObject, self).__init__(handle)
self.tag = GetDatatypeTag(self)
self.num_fields = GetDatatypeNumberOfFields(self)
self.tag = _vmobj.GetDatatypeTag(self)
self.num_fields = _vmobj.GetDatatypeNumberOfFields(self)

def __getitem__(self, idx):
idx = idx + self.num_fields if idx < 0 else idx
assert 0 <= idx < self.num_fields
return GetDatatypeFields(self, idx)
return _vmobj.GetDatatypeFields(self, idx)

def __len__(self):
return self.num_fields


def tensor_object(arr, ctx=_nd.cpu(0)):
"""Create a tensor object from source arr.

Parameters
----------
arr : numpy.ndarray or tvm.nd.NDArray
The source array.

ctx : TVMContext, optional
The device context to create the array

Returns
-------
ret : TensorObject
The created object.
"""
if isinstance(arr, _np.ndarray):
tensor = _vmobj.Tensor(_nd.array(arr, ctx))
elif isinstance(arr, _nd.NDArray):
tensor = _vmobj.Tensor(arr)
else:
raise RuntimeError("Unsupported type for tensor object.")
return tensor


def tuple_object(fields):
"""Create a datatype object from source tuple.

Parameters
----------
fields : list[Object] or tuple[Object]
The source tuple.

Returns
-------
ret : DatatypeObject
The created object.
"""
for f in fields:
assert isinstance(f, ObjectBase)
return _vmobj.Tuple(*fields)


def datatype_object(tag, fields):
"""Create a datatype object from tag and source fields.

Parameters
----------
tag : int
The tag of datatype.

fields : list[Object] or tuple[Object]
The source tuple.

Returns
-------
ret : DatatypeObject
The created object.
"""
for f in fields:
assert isinstance(f, ObjectBase)
return _vmobj.Datatype(tag, *fields)
8 changes: 8 additions & 0 deletions python/tvm/relay/transform.py
Original file line number Diff line number Diff line change
@@ -530,6 +530,14 @@ def CanonicalizeCast():


def LambdaLift():
"""
Lift the closure to global function.

Returns
-------
ret : tvm.relay.Pass
The registered pass that lifts the lambda function.
"""
return _transform.LambdaLift()


3 changes: 2 additions & 1 deletion src/relay/backend/vm/compiler.cc
Original file line number Diff line number Diff line change
@@ -761,7 +761,8 @@ class VMBuildModule : public runtime::ModuleNode {
protected:
Module OptimizeModule(const Module& mod) {
// TODO(@icemelon9): check number of targets and build config, add more optimization pass
transform::Sequential seq({transform::ToANormalForm(),
transform::Sequential seq({transform::SimplifyInference(),
transform::ToANormalForm(),
transform::InlinePrimitives(),
transform::LambdaLift(),
transform::InlinePrimitives(),
Loading