Unverified Commit a1d50f0f authored by Lingfan Yu's avatar Lingfan Yu Committed by GitHub
Browse files

[Refactor] Rename before release (#261)

* include/dgl/runtime

* include

* src/runtime

* src/graph

* src/scheduler

* src

* clean up CMakeLists

* further clean up in cmake

* install commands

* python/dgl/_ffi/_cython

* python/dgl/_ffi/_ctypes

* python/dgl/_ffi

* python/dgl

* some fix

* copy right
parent aabba9d4
......@@ -4,20 +4,20 @@ from cpython cimport Py_INCREF, Py_DECREF
from numbers import Number, Integral
from ..base import string_types
from ..node_generic import convert_to_node, NodeGeneric
from ..runtime_ctypes import TVMType, TVMContext, TVMByteArray
from ..runtime_ctypes import DGLType, DGLContext, DGLByteArray
cdef void tvm_callback_finalize(void* fhandle):
cdef void dgl_callback_finalize(void* fhandle):
local_pyfunc = <object>(fhandle)
Py_DECREF(local_pyfunc)
cdef int tvm_callback(TVMValue* args,
cdef int dgl_callback(DGLValue* args,
int* type_codes,
int num_args,
TVMRetValueHandle ret,
DGLRetValueHandle ret,
void* fhandle) with gil:
cdef list pyargs
cdef TVMValue value
cdef DGLValue value
cdef int tcode
local_pyfunc = <object>(fhandle)
pyargs = []
......@@ -28,7 +28,7 @@ cdef int tvm_callback(TVMValue* args,
tcode == kFuncHandle or
tcode == kModuleHandle or
tcode > kExtBegin):
CALL(TVMCbArgToReturn(&value, tcode))
CALL(DGLCbArgToReturn(&value, tcode))
if tcode != kArrayHandle:
pyargs.append(make_ret(value, tcode))
......@@ -38,19 +38,19 @@ cdef int tvm_callback(TVMValue* args,
rv = local_pyfunc(*pyargs)
except Exception:
msg = traceback.format_exc()
TVMAPISetLastError(c_str(msg))
DGLAPISetLastError(c_str(msg))
return -1
if rv is not None:
if isinstance(rv, tuple):
raise ValueError("PackedFunction can only support one return value")
temp_args = []
make_arg(rv, &value, &tcode, temp_args)
CALL(TVMCFuncSetReturn(ret, &value, &tcode, 1))
CALL(DGLCFuncSetReturn(ret, &value, &tcode, 1))
return 0
def convert_to_tvm_func(object pyfunc):
"""Convert a python function to TVM function
def convert_to_dgl_func(object pyfunc):
"""Convert a python function to DGL function
Parameters
----------
......@@ -59,14 +59,14 @@ def convert_to_tvm_func(object pyfunc):
Returns
-------
tvmfunc: tvm.Function
The converted tvm function.
dglfunc: dgl.Function
The converted dgl function.
"""
cdef TVMFunctionHandle chandle
cdef DGLFunctionHandle chandle
Py_INCREF(pyfunc)
CALL(TVMFuncCreateFromCFunc(tvm_callback,
CALL(DGLFuncCreateFromCFunc(dgl_callback,
<void*>(pyfunc),
tvm_callback_finalize,
dgl_callback_finalize,
&chandle))
ret = _CLASS_FUNCTION(None, False)
(<FunctionBase>ret).chandle = chandle
......@@ -74,10 +74,10 @@ def convert_to_tvm_func(object pyfunc):
cdef inline int make_arg(object arg,
TVMValue* value,
DGLValue* value,
int* tcode,
list temp_args) except -1:
"""Pack arguments into c args tvm call accept"""
"""Pack arguments into c args dgl call accept"""
cdef unsigned long long ptr
if isinstance(arg, NodeBase):
value[0].v_handle = (<NodeBase>arg).chandle
......@@ -86,10 +86,10 @@ cdef inline int make_arg(object arg,
value[0].v_handle = (<NDArrayBase>arg).chandle
tcode[0] = (kNDArrayContainer if
not (<NDArrayBase>arg).c_is_view else kArrayHandle)
elif isinstance(arg, _TVM_COMPATS):
ptr = arg._tvm_handle
elif isinstance(arg, _DGL_COMPATS):
ptr = arg._dgl_handle
value[0].v_handle = (<void*>ptr)
tcode[0] = arg.__class__._tvm_tcode
tcode[0] = arg.__class__._dgl_tcode
elif isinstance(arg, (int, long)):
value[0].v_int64 = arg
tcode[0] = kInt
......@@ -107,17 +107,17 @@ cdef inline int make_arg(object arg,
elif isinstance(arg, Number):
value[0].v_float64 = arg
tcode[0] = kFloat
elif isinstance(arg, TVMType):
elif isinstance(arg, DGLType):
tstr = c_str(str(arg))
value[0].v_str = tstr
tcode[0] = kStr
temp_args.append(tstr)
elif isinstance(arg, TVMContext):
elif isinstance(arg, DGLContext):
value[0].v_ctx = (<DLContext*>(
<unsigned long long>ctypes.addressof(arg)))[0]
tcode[0] = kTVMContext
tcode[0] = kDGLContext
elif isinstance(arg, bytearray):
arr = TVMByteArray()
arr = DGLByteArray()
arr.data = ctypes.cast(
(ctypes.c_byte * len(arg)).from_buffer(arg),
ctypes.POINTER(ctypes.c_byte))
......@@ -146,7 +146,7 @@ cdef inline int make_arg(object arg,
value[0].v_handle = c_handle(arg)
tcode[0] = kHandle
elif callable(arg):
arg = convert_to_tvm_func(arg)
arg = convert_to_dgl_func(arg)
value[0].v_handle = (<FunctionBase>arg).chandle
tcode[0] = kFuncHandle
temp_args.append(arg)
......@@ -156,7 +156,7 @@ cdef inline int make_arg(object arg,
cdef inline bytearray make_ret_bytes(void* chandle):
handle = ctypes_handle(chandle)
arr = ctypes.cast(handle, ctypes.POINTER(TVMByteArray))[0]
arr = ctypes.cast(handle, ctypes.POINTER(DGLByteArray))[0]
size = arr.size
res = bytearray(size)
rptr = (ctypes.c_byte * size).from_buffer(res)
......@@ -164,7 +164,7 @@ cdef inline bytearray make_ret_bytes(void* chandle):
raise RuntimeError('memmove failed')
return res
cdef inline object make_ret(TVMValue value, int tcode):
cdef inline object make_ret(DGLValue value, int tcode):
"""convert result to return value."""
if tcode == kNodeHandle:
return make_ret_node(value.v_handle)
......@@ -182,16 +182,16 @@ cdef inline object make_ret(TVMValue value, int tcode):
return make_ret_bytes(value.v_handle)
elif tcode == kHandle:
return ctypes_handle(value.v_handle)
elif tcode == kTVMContext:
return TVMContext(value.v_ctx.device_type, value.v_ctx.device_id)
elif tcode == kDGLContext:
return DGLContext(value.v_ctx.device_type, value.v_ctx.device_id)
elif tcode == kModuleHandle:
return _CLASS_MODULE(ctypes_handle(value.v_handle))
elif tcode == kFuncHandle:
fobj = _CLASS_FUNCTION(None, False)
(<FunctionBase>fobj).chandle = value.v_handle
return fobj
elif tcode in _TVM_EXT_RET:
return _TVM_EXT_RET[tcode](ctypes_handle(value.v_handle))
elif tcode in _DGL_EXT_RET:
return _DGL_EXT_RET[tcode](ctypes_handle(value.v_handle))
raise ValueError("Unhandled type code %d" % tcode)
......@@ -199,21 +199,21 @@ cdef inline object make_ret(TVMValue value, int tcode):
cdef inline int FuncCall3(void* chandle,
tuple args,
int nargs,
TVMValue* ret_val,
DGLValue* ret_val,
int* ret_tcode) except -1:
cdef TVMValue[3] values
cdef DGLValue[3] values
cdef int[3] tcodes
nargs = len(args)
temp_args = []
for i in range(nargs):
make_arg(args[i], &values[i], &tcodes[i], temp_args)
CALL(TVMFuncCall(chandle, &values[0], &tcodes[0],
CALL(DGLFuncCall(chandle, &values[0], &tcodes[0],
nargs, ret_val, ret_tcode))
return 0
cdef inline int FuncCall(void* chandle,
tuple args,
TVMValue* ret_val,
DGLValue* ret_val,
int* ret_tcode) except -1:
cdef int nargs
nargs = len(args)
......@@ -221,14 +221,14 @@ cdef inline int FuncCall(void* chandle,
FuncCall3(chandle, args, nargs, ret_val, ret_tcode)
return 0
cdef vector[TVMValue] values
cdef vector[DGLValue] values
cdef vector[int] tcodes
values.resize(max(nargs, 1))
tcodes.resize(max(nargs, 1))
temp_args = []
for i in range(nargs):
make_arg(args[i], &values[i], &tcodes[i], temp_args)
CALL(TVMFuncCall(chandle, &values[0], &tcodes[0],
CALL(DGLFuncCall(chandle, &values[0], &tcodes[0],
nargs, ret_val, ret_tcode))
return 0
......@@ -238,7 +238,7 @@ cdef inline int ConstructorCall(void* constructor_handle,
tuple args,
void** handle) except -1:
"""Call contructor of a handle function"""
cdef TVMValue ret_val
cdef DGLValue ret_val
cdef int ret_tcode
FuncCall(constructor_handle, args, &ret_val, &ret_tcode)
assert ret_tcode == type_code
......@@ -247,7 +247,7 @@ cdef inline int ConstructorCall(void* constructor_handle,
cdef class FunctionBase:
cdef TVMFunctionHandle chandle
cdef DGLFunctionHandle chandle
cdef int is_global
cdef inline _set_handle(self, handle):
......@@ -278,10 +278,10 @@ cdef class FunctionBase:
def __dealloc__(self):
if self.is_global == 0:
CALL(TVMFuncFree(self.chandle))
CALL(DGLFuncFree(self.chandle))
def __call__(self, *args):
cdef TVMValue ret_val
cdef DGLValue ret_val
cdef int ret_tcode
FuncCall(self.chandle, args, &ret_val, &ret_tcode)
return make_ret(ret_val, ret_tcode)
......
from ..runtime_ctypes import TVMArrayHandle
from ..runtime_ctypes import DGLArrayHandle
cdef const char* _c_str_dltensor = "dltensor"
cdef const char* _c_str_used_dltensor = "used_dltensor"
......@@ -8,7 +8,7 @@ cdef void _c_dlpack_deleter(object pycaps):
cdef DLManagedTensor* dltensor
if pycapsule.PyCapsule_IsValid(pycaps, _c_str_dltensor):
dltensor = <DLManagedTensor*>pycapsule.PyCapsule_GetPointer(pycaps, _c_str_dltensor)
TVMDLManagedTensorCallDeleter(dltensor)
DGLDLManagedTensorCallDeleter(dltensor)
def _from_dlpack(object dltensor):
......@@ -16,7 +16,7 @@ def _from_dlpack(object dltensor):
cdef DLTensorHandle chandle
if pycapsule.PyCapsule_IsValid(dltensor, _c_str_dltensor):
ptr = <DLManagedTensor*>pycapsule.PyCapsule_GetPointer(dltensor, _c_str_dltensor)
CALL(TVMArrayFromDLPack(ptr, &chandle))
CALL(DGLArrayFromDLPack(ptr, &chandle))
# set name and destructor to be empty
pycapsule.PyCapsule_SetDestructor(dltensor, NULL)
pycapsule.PyCapsule_SetName(dltensor, _c_str_used_dltensor)
......@@ -36,7 +36,7 @@ cdef class NDArrayBase:
ptr = ctypes.cast(handle, ctypes.c_void_p).value
self.chandle = <DLTensor*>(ptr)
property _tvm_handle:
property _dgl_handle:
def __get__(self):
return <unsigned long long>self.chandle
......@@ -46,7 +46,7 @@ cdef class NDArrayBase:
return None
else:
return ctypes.cast(
<unsigned long long>self.chandle, TVMArrayHandle)
<unsigned long long>self.chandle, DGLArrayHandle)
def __set__(self, value):
self._set_handle(value)
......@@ -57,7 +57,7 @@ cdef class NDArrayBase:
def __dealloc__(self):
if self.c_is_view == 0:
CALL(TVMArrayFree(self.chandle))
CALL(DGLArrayFree(self.chandle))
def to_dlpack(self):
"""Produce an array from a DLPack Tensor without copying memory
......@@ -69,7 +69,7 @@ cdef class NDArrayBase:
cdef DLManagedTensor* dltensor
if self.c_is_view != 0:
raise ValueError("to_dlpack do not work with memory views")
CALL(TVMArrayToDLPack(self.chandle, &dltensor))
CALL(DGLArrayToDLPack(self.chandle, &dltensor))
return pycapsule.PyCapsule_New(dltensor, _c_str_dltensor, _c_dlpack_deleter)
......@@ -79,15 +79,15 @@ cdef c_make_array(void* chandle, is_view):
return ret
cdef _TVM_COMPATS = ()
cdef _DGL_COMPATS = ()
cdef _TVM_EXT_RET = {}
cdef _DGL_EXT_RET = {}
def _reg_extension(cls, fcreate):
global _TVM_COMPATS
_TVM_COMPATS += (cls,)
global _DGL_COMPATS
_DGL_COMPATS += (cls,)
if fcreate:
_TVM_EXT_RET[cls._tvm_tcode] = fcreate
_DGL_EXT_RET[cls._dgl_tcode] = fcreate
def _make_array(handle, is_view):
......
......@@ -18,7 +18,7 @@ cdef inline object make_ret_node(void* chandle):
cdef list node_type
cdef object cls
node_type = NODE_TYPE
CALL(TVMNodeGetTypeIndex(chandle, &tindex))
CALL(DGLNodeGetTypeIndex(chandle, &tindex))
if tindex < len(node_type):
cls = node_type[tindex]
if cls is not None:
......@@ -53,12 +53,12 @@ cdef class NodeBase:
self._set_handle(value)
def __dealloc__(self):
CALL(TVMNodeFree(self.chandle))
CALL(DGLNodeFree(self.chandle))
def __getattr__(self, name):
cdef TVMValue ret_val
cdef DGLValue ret_val
cdef int ret_type_code, ret_succ
CALL(TVMNodeGetAttr(self.chandle, c_str(name),
CALL(DGLNodeGetAttr(self.chandle, c_str(name),
&ret_val, &ret_type_code, &ret_succ))
if ret_succ == 0:
raise AttributeError(
......
......@@ -34,7 +34,7 @@ def _load_lib():
lib_path = libinfo.find_lib_path()
lib = ctypes.CDLL(lib_path[0], ctypes.RTLD_GLOBAL)
# DMatrix functions
lib.TVMGetLastError.restype = ctypes.c_char_p
lib.DGLGetLastError.restype = ctypes.c_char_p
return lib, os.path.basename(lib_path[0])
# version number
......@@ -60,7 +60,7 @@ def check_call(ret):
return value from API calls
"""
if ret != 0:
raise DGLError(py_str(_LIB.TVMGetLastError()))
raise DGLError(py_str(_LIB.DGLGetLastError()))
def c_str(string):
......
......@@ -15,31 +15,31 @@ try:
if sys.version_info >= (3, 0):
from ._cy3.core import _set_class_function, _set_class_module
from ._cy3.core import FunctionBase as _FunctionBase
from ._cy3.core import convert_to_tvm_func
from ._cy3.core import convert_to_dgl_func
else:
from ._cy2.core import _set_class_function, _set_class_module
from ._cy2.core import FunctionBase as _FunctionBase
from ._cy2.core import convert_to_tvm_func
from ._cy2.core import convert_to_dgl_func
except IMPORT_EXCEPT:
# pylint: disable=wrong-import-position
from ._ctypes.function import _set_class_function, _set_class_module
from ._ctypes.function import FunctionBase as _FunctionBase
from ._ctypes.function import convert_to_tvm_func
from ._ctypes.function import convert_to_dgl_func
FunctionHandle = ctypes.c_void_p
class Function(_FunctionBase):
"""The PackedFunc object.
Function plays an key role to bridge front and backend in TVM.
Function plays an key role to bridge front and backend in DGL.
Function provide a type-erased interface, you can call function with positional arguments.
The compiled module returns Function.
TVM backend also registers and exposes its API as Functions.
For example, the developer function exposed in tvm.ir_pass are actually
DGL backend also registers and exposes its API as Functions.
For example, the developer function exposed in dgl.ir_pass are actually
C++ functions that are registered as PackedFunc
The following are list of common usage scenario of tvm.Function.
The following are list of common usage scenario of dgl.Function.
- Automatic exposure of C++ API into python
- To call PackedFunc from python side
......@@ -48,8 +48,8 @@ class Function(_FunctionBase):
See Also
--------
tvm.register_func: How to register global function.
tvm.get_global_func: How to get global function.
dgl.register_func: How to register global function.
dgl.get_global_func: How to get global function.
"""
pass
......@@ -61,10 +61,10 @@ class ModuleBase(object):
def __init__(self, handle):
self.handle = handle
self._entry = None
self.entry_name = "__tvm_main__"
self.entry_name = "__dgl_main__"
def __del__(self):
check_call(_LIB.TVMModFree(self.handle))
check_call(_LIB.DGLModFree(self.handle))
@property
def entry_func(self):
......@@ -97,7 +97,7 @@ class ModuleBase(object):
The result function.
"""
ret_handle = FunctionHandle()
check_call(_LIB.TVMModGetFunction(
check_call(_LIB.DGLModGetFunction(
self.handle, c_str(name),
ctypes.c_int(query_imports),
ctypes.byref(ret_handle)))
......@@ -114,7 +114,7 @@ class ModuleBase(object):
module : Module
The other module.
"""
check_call(_LIB.TVMModImport(self.handle, module.handle))
check_call(_LIB.DGLModImport(self.handle, module.handle))
def __getitem__(self, name):
if not isinstance(name, string_types):
......@@ -152,18 +152,18 @@ def register_func(func_name, f=None, override=False):
The following code registers my_packed_func as global function.
Note that we simply get it back from global function table to invoke
it from python side. However, we can also invoke the same function
from C++ backend, or in the compiled TVM code.
from C++ backend, or in the compiled DGL code.
.. code-block:: python
targs = (10, 10.0, "hello")
@tvm.register_func
@dgl.register_func
def my_packed_func(*args):
assert(tuple(args) == targs)
return 10
# Get it out from global function table
f = tvm.get_global_func("my_packed_func")
assert isinstance(f, tvm.nd.Function)
f = dgl.get_global_func("my_packed_func")
assert isinstance(f, dgl.nd.Function)
y = f(*targs)
assert y == 10
"""
......@@ -178,8 +178,8 @@ def register_func(func_name, f=None, override=False):
def register(myf):
"""internal register function"""
if not isinstance(myf, Function):
myf = convert_to_tvm_func(myf)
check_call(_LIB.TVMFuncRegisterGlobal(
myf = convert_to_dgl_func(myf)
check_call(_LIB.DGLFuncRegisterGlobal(
c_str(func_name), myf.handle, ioverride))
return myf
if f:
......@@ -200,11 +200,11 @@ def get_global_func(name, allow_missing=False):
Returns
-------
func : tvm.Function
func : dgl.Function
The function to be returned, None if function is missing.
"""
handle = FunctionHandle()
check_call(_LIB.TVMFuncGetGlobal(c_str(name), ctypes.byref(handle)))
check_call(_LIB.DGLFuncGetGlobal(c_str(name), ctypes.byref(handle)))
if handle.value:
return Function(handle, False)
else:
......@@ -226,7 +226,7 @@ def list_global_func_names():
plist = ctypes.POINTER(ctypes.c_char_p)()
size = ctypes.c_uint()
check_call(_LIB.TVMFuncListGlobalNames(ctypes.byref(size),
check_call(_LIB.DGLFuncListGlobalNames(ctypes.byref(size),
ctypes.byref(plist)))
fnames = []
for i in range(size.value):
......@@ -241,7 +241,7 @@ def extract_ext_funcs(finit):
Parameters
----------
finit : ctypes function
a ctypes that takes signature of TVMExtensionDeclarer
a ctypes that takes signature of DGLExtensionDeclarer
Returns
-------
......@@ -251,7 +251,7 @@ def extract_ext_funcs(finit):
fdict = {}
def _list(name, func):
fdict[name] = func
myf = convert_to_tvm_func(_list)
myf = convert_to_dgl_func(_list)
ret = finit(myf.handle)
_ = myf
if ret != 0:
......
......@@ -19,10 +19,10 @@ def find_lib_path(name=None, search_path=None, optional=False):
"""
# See https://github.com/dmlc/tvm/issues/281 for some background.
# NB: This will either be the source directory (if TVM is run
# inplace) or the install directory (if TVM is installed).
# An installed TVM's curr_path will look something like:
# $PREFIX/lib/python3.6/site-packages/tvm/_ffi
# NB: This will either be the source directory (if DGL is run
# inplace) or the install directory (if DGL is installed).
# An installed DGL's curr_path will look something like:
# $PREFIX/lib/python3.6/site-packages/dgl/_ffi
ffi_dir = os.path.dirname(os.path.abspath(os.path.expanduser(__file__)))
source_dir = os.path.join(ffi_dir, "..", "..", "..")
install_lib_dir = os.path.join(ffi_dir, "..", "..", "..", "..")
......@@ -71,7 +71,7 @@ def find_lib_path(name=None, search_path=None, optional=False):
# try to find lib_dll_path
lib_found = [p for p in lib_dll_path if os.path.exists(p) and os.path.isfile(p)]
if not lib_found:
message = ('Cannot find the files.\n' +
'List of candidates:\n' +
......@@ -86,5 +86,5 @@ def find_lib_path(name=None, search_path=None, optional=False):
# current version
# We use the version of the incoming release for code
# that is under development.
# The following line is set by tvm/python/update_version.py
# The following line is set by dgl/python/update_version.py
__version__ = "0.0.1"
......@@ -6,8 +6,8 @@ import sys
import ctypes
import numpy as np
from .base import _LIB, check_call, c_array, string_types, _FFI_MODE, c_str
from .runtime_ctypes import TVMType, TVMContext, TVMArray, TVMArrayHandle
from .runtime_ctypes import TypeCode, tvm_shape_index_t
from .runtime_ctypes import DGLType, DGLContext, DGLArray, DGLArrayHandle
from .runtime_ctypes import TypeCode, dgl_shape_index_t
IMPORT_EXCEPT = RuntimeError if _FFI_MODE == "cython" else ImportError
......@@ -28,7 +28,7 @@ except IMPORT_EXCEPT:
from ._ctypes.ndarray import NDArrayBase as _NDArrayBase
def context(dev_type, dev_id=0):
"""Construct a TVM context with given device type and id.
"""Construct a DGL context with given device type and id.
Parameters
----------
......@@ -40,7 +40,7 @@ def context(dev_type, dev_id=0):
Returns
-------
ctx: TVMContext
ctx: DGLContext
The corresponding context.
Examples
......@@ -50,29 +50,29 @@ def context(dev_type, dev_id=0):
.. code-block:: python
assert tvm.context("cpu", 1) == tvm.cpu(1)
assert tvm.context("gpu", 0) == tvm.gpu(0)
assert tvm.context("cuda", 0) == tvm.gpu(0)
assert dgl.context("cpu", 1) == dgl.cpu(1)
assert dgl.context("gpu", 0) == dgl.gpu(0)
assert dgl.context("cuda", 0) == dgl.gpu(0)
"""
if isinstance(dev_type, string_types):
dev_type = dev_type.split()[0]
if dev_type not in TVMContext.STR2MASK:
if dev_type not in DGLContext.STR2MASK:
raise ValueError("Unknown device type %s" % dev_type)
dev_type = TVMContext.STR2MASK[dev_type]
return TVMContext(dev_type, dev_id)
dev_type = DGLContext.STR2MASK[dev_type]
return DGLContext(dev_type, dev_id)
def numpyasarray(np_data):
"""Return a TVMArray representation of a numpy array.
"""Return a DGLArray representation of a numpy array.
"""
data = np_data
assert data.flags['C_CONTIGUOUS']
arr = TVMArray()
shape = c_array(tvm_shape_index_t, data.shape)
arr = DGLArray()
shape = c_array(dgl_shape_index_t, data.shape)
arr.data = data.ctypes.data_as(ctypes.c_void_p)
arr.shape = shape
arr.strides = None
arr.dtype = TVMType(np.dtype(data.dtype).name)
arr.dtype = DGLType(np.dtype(data.dtype).name)
arr.ndim = data.ndim
# CPU device
arr.ctx = context(1, 0)
......@@ -90,19 +90,19 @@ def empty(shape, dtype="float32", ctx=context(1, 0)):
dtype : type or str
The data type of the array.
ctx : TVMContext
ctx : DGLContext
The context of the array
Returns
-------
arr : tvm.nd.NDArray
The array tvm supported.
arr : dgl.nd.NDArray
The array dgl supported.
"""
shape = c_array(tvm_shape_index_t, shape)
shape = c_array(dgl_shape_index_t, shape)
ndim = ctypes.c_int(len(shape))
handle = TVMArrayHandle()
dtype = TVMType(dtype)
check_call(_LIB.TVMArrayAlloc(
handle = DGLArrayHandle()
dtype = DGLType(dtype)
check_call(_LIB.DGLArrayAlloc(
shape, ndim,
ctypes.c_int(dtype.type_code),
ctypes.c_int(dtype.bits),
......@@ -126,7 +126,7 @@ def from_dlpack(dltensor):
Returns
-------
arr: tvm.nd.NDArray
arr: dgl.nd.NDArray
The array view of the tensor data.
"""
return _from_dlpack(dltensor)
......@@ -217,7 +217,7 @@ class NDArrayBase(_NDArrayBase):
except:
raise TypeError('array must be an array_like data,' +
'type %s is not supported' % str(type(source_array)))
t = TVMType(self.dtype)
t = DGLType(self.dtype)
shape, dtype = self.shape, self.dtype
if t.lanes > 1:
shape = shape + (t.lanes,)
......@@ -231,11 +231,11 @@ class NDArrayBase(_NDArrayBase):
assert source_array.flags['C_CONTIGUOUS']
data = source_array.ctypes.data_as(ctypes.c_void_p)
nbytes = ctypes.c_size_t(source_array.size * source_array.dtype.itemsize)
check_call(_LIB.TVMArrayCopyFromBytes(self.handle, data, nbytes))
check_call(_LIB.DGLArrayCopyFromBytes(self.handle, data, nbytes))
return self
def __repr__(self):
res = "<tvm.NDArray shape={0}, {1}>\n".format(self.shape, self.context)
res = "<dgl.NDArray shape={0}, {1}>\n".format(self.shape, self.context)
res += self.asnumpy().__repr__()
return res
......@@ -250,7 +250,7 @@ class NDArrayBase(_NDArrayBase):
np_arr : numpy.ndarray
The corresponding numpy array.
"""
t = TVMType(self.dtype)
t = DGLType(self.dtype)
shape, dtype = self.shape, self.dtype
if t.lanes > 1:
shape = shape + (t.lanes,)
......@@ -260,7 +260,7 @@ class NDArrayBase(_NDArrayBase):
assert np_arr.flags['C_CONTIGUOUS']
data = np_arr.ctypes.data_as(ctypes.c_void_p)
nbytes = ctypes.c_size_t(np_arr.size * np_arr.dtype.itemsize)
check_call(_LIB.TVMArrayCopyToBytes(self.handle, data, nbytes))
check_call(_LIB.DGLArrayCopyToBytes(self.handle, data, nbytes))
return np_arr
def copyto(self, target):
......@@ -271,10 +271,10 @@ class NDArrayBase(_NDArrayBase):
target : NDArray
The target array to be copied, must have same shape as this array.
"""
if isinstance(target, TVMContext):
if isinstance(target, DGLContext):
target = empty(self.shape, self.dtype, target)
if isinstance(target, NDArrayBase):
check_call(_LIB.TVMArrayCopyFromTo(
check_call(_LIB.DGLArrayCopyFromTo(
self.handle, target.handle, None))
else:
raise ValueError("Unsupported target type %s" % str(type(target)))
......@@ -292,13 +292,13 @@ def free_extension_handle(handle, type_code):
type_code : int
The tyoe code
"""
check_call(_LIB.TVMExtTypeFree(handle, ctypes.c_int(type_code)))
check_call(_LIB.DGLExtTypeFree(handle, ctypes.c_int(type_code)))
def register_extension(cls, fcreate=None):
"""Register a extension class to TVM.
"""Register a extension class to DGL.
After the class is registered, the class will be able
to directly pass as Function argument generated by TVM.
to directly pass as Function argument generated by DGL.
Parameters
----------
......@@ -307,10 +307,10 @@ def register_extension(cls, fcreate=None):
Note
----
The registered class is requires one property: _tvm_handle and a class attribute _tvm_tcode.
The registered class is requires one property: _dgl_handle and a class attribute _dgl_tcode.
- ```_tvm_handle``` returns integer represents the address of the handle.
- ```_tvm_tcode``` gives integer represents type code of the class.
- ```_dgl_handle``` returns integer represents the address of the handle.
- ```_dgl_tcode``` gives integer represents type code of the class.
Returns
-------
......@@ -327,18 +327,18 @@ def register_extension(cls, fcreate=None):
.. code-block:: python
@tvm.register_extension
@dgl.register_extension
class MyTensor(object):
_tvm_tcode = tvm.TypeCode.ARRAY_HANDLE
_dgl_tcode = dgl.TypeCode.ARRAY_HANDLE
def __init__(self):
self.handle = _LIB.NewDLTensor()
@property
def _tvm_handle(self):
def _dgl_handle(self):
return self.handle.value
"""
if fcreate and cls._tvm_tcode < TypeCode.EXT_BEGIN:
if fcreate and cls._dgl_tcode < TypeCode.EXT_BEGIN:
raise ValueError("Cannot register create when extension tcode is same as buildin")
_reg_extension(cls, fcreate)
return cls
......@@ -8,7 +8,7 @@ import numpy as np
from .base import _LIB, check_call
from .. import _api_internal
tvm_shape_index_t = ctypes.c_int64
dgl_shape_index_t = ctypes.c_int64
class TypeCode(object):
"""Type code used in API calls"""
......@@ -17,8 +17,8 @@ class TypeCode(object):
FLOAT = 2
HANDLE = 3
NULL = 4
TVM_TYPE = 5
TVM_CONTEXT = 6
DGL_TYPE = 5
DGL_CONTEXT = 6
ARRAY_HANDLE = 7
NODE_HANDLE = 8
MODULE_HANDLE = 9
......@@ -28,13 +28,13 @@ class TypeCode(object):
NDARRAY_CONTAINER = 13
EXT_BEGIN = 15
class TVMByteArray(ctypes.Structure):
class DGLByteArray(ctypes.Structure):
"""Temp data structure for byte array."""
_fields_ = [("data", ctypes.POINTER(ctypes.c_byte)),
("size", ctypes.c_size_t)]
class TVMType(ctypes.Structure):
"""TVM datatype structure"""
class DGLType(ctypes.Structure):
"""DGL datatype structure"""
_fields_ = [("type_code", ctypes.c_uint8),
("bits", ctypes.c_uint8),
("lanes", ctypes.c_uint16)]
......@@ -50,7 +50,7 @@ class TVMType(ctypes.Structure):
if type_str in cls._cache:
return cls._cache[type_str]
inst = super(TVMType, cls).__new__(TVMType)
inst = super(DGLType, cls).__new__(DGLType)
if isinstance(type_str, np.dtype):
type_str = str(type_str)
......@@ -84,7 +84,7 @@ class TVMType(ctypes.Structure):
pass
def __repr__(self):
x = "%s%d" % (TVMType.CODE2STR[self.type_code], self.bits)
x = "%s%d" % (DGLType.CODE2STR[self.type_code], self.bits)
if self.lanes != 1:
x += "x%d" % self.lanes
return x
......@@ -99,8 +99,8 @@ class TVMType(ctypes.Structure):
RPC_SESS_MASK = 128
class TVMContext(ctypes.Structure):
"""TVM context strucure."""
class DGLContext(ctypes.Structure):
"""DGL context strucure."""
_fields_ = [("device_type", ctypes.c_int),
("device_id", ctypes.c_int)]
MASK2STR = {
......@@ -141,7 +141,7 @@ class TVMContext(ctypes.Structure):
if (device_type, device_id) in cls._cache:
return cls._cache[(device_type, device_id)]
inst = super(TVMContext, cls).__new__(TVMContext)
inst = super(DGLContext, cls).__new__(DGLContext)
inst.device_type = device_type
inst.device_id = device_id
......@@ -222,10 +222,10 @@ class TVMContext(ctypes.Structure):
def sync(self):
"""Synchronize until jobs finished at the context."""
check_call(_LIB.TVMSynchronize(self.device_type, self.device_id, None))
check_call(_LIB.DGLSynchronize(self.device_type, self.device_id, None))
def __eq__(self, other):
return (isinstance(other, TVMContext) and
return (isinstance(other, DGLContext) and
self.device_id == other.device_id and
self.device_type == other.device_type)
......@@ -237,22 +237,22 @@ class TVMContext(ctypes.Structure):
tbl_id = self.device_type / RPC_SESS_MASK - 1
dev_type = self.device_type % RPC_SESS_MASK
return "remote[%d]:%s(%d)" % (
tbl_id, TVMContext.MASK2STR[dev_type], self.device_id)
tbl_id, DGLContext.MASK2STR[dev_type], self.device_id)
return "%s(%d)" % (
TVMContext.MASK2STR[self.device_type], self.device_id)
DGLContext.MASK2STR[self.device_type], self.device_id)
def __hash__(self):
return hash((self.device_type, self.device_id))
class TVMArray(ctypes.Structure):
"""TVMValue in C API"""
class DGLArray(ctypes.Structure):
"""DGLValue in C API"""
_fields_ = [("data", ctypes.c_void_p),
("ctx", TVMContext),
("ctx", DGLContext),
("ndim", ctypes.c_int),
("dtype", TVMType),
("shape", ctypes.POINTER(tvm_shape_index_t)),
("strides", ctypes.POINTER(tvm_shape_index_t)),
("dtype", DGLType),
("shape", ctypes.POINTER(dgl_shape_index_t)),
("strides", ctypes.POINTER(dgl_shape_index_t)),
("byte_offset", ctypes.c_uint64)]
TVMArrayHandle = ctypes.POINTER(TVMArray)
DGLArrayHandle = ctypes.POINTER(DGLArray)
......@@ -306,7 +306,7 @@ class Frame(MutableMapping):
The column name.
scheme : Scheme
The column scheme.
ctx : TVMContext
ctx : DGLContext
The column context.
"""
if name in self:
......
......@@ -11,7 +11,7 @@ import functools
import operator
import numpy as _np
from ._ffi.ndarray import TVMContext, TVMType, NDArrayBase
from ._ffi.ndarray import DGLContext, DGLType, NDArrayBase
from ._ffi.ndarray import context, empty, from_dlpack, numpyasarray
from ._ffi.ndarray import _set_class_ndarray
from . import backend as F
......@@ -31,10 +31,10 @@ def cpu(dev_id=0):
Returns
-------
ctx : TVMContext
ctx : DGLContext
The created context
"""
return TVMContext(1, dev_id)
return DGLContext(1, dev_id)
def gpu(dev_id=0):
"""Construct a CPU device
......@@ -46,10 +46,10 @@ def gpu(dev_id=0):
Returns
-------
ctx : TVMContext
ctx : DGLContext
The created context
"""
return TVMContext(2, dev_id)
return DGLContext(2, dev_id)
def array(arr, ctx=cpu(0)):
"""Create an array from source arr.
......@@ -59,7 +59,7 @@ def array(arr, ctx=cpu(0)):
arr : numpy.ndarray
The array to be copied from
ctx : TVMContext, optional
ctx : DGLContext, optional
The device context to create the array
Returns
......
......@@ -5,15 +5,15 @@
*/
#include "c_api_common.h"
using tvm::runtime::TVMArgs;
using tvm::runtime::TVMArgValue;
using tvm::runtime::TVMRetValue;
using tvm::runtime::PackedFunc;
using tvm::runtime::NDArray;
using dgl::runtime::DGLArgs;
using dgl::runtime::DGLArgValue;
using dgl::runtime::DGLRetValue;
using dgl::runtime::PackedFunc;
using dgl::runtime::NDArray;
namespace dgl {
DLManagedTensor* CreateTmpDLManagedTensor(const TVMArgValue& arg) {
DLManagedTensor* CreateTmpDLManagedTensor(const DGLArgValue& arg) {
const DLTensor* dl_tensor = arg;
DLManagedTensor* ret = new DLManagedTensor();
ret->deleter = [] (DLManagedTensor* self) { delete self; };
......@@ -23,7 +23,7 @@ DLManagedTensor* CreateTmpDLManagedTensor(const TVMArgValue& arg) {
}
PackedFunc ConvertNDArrayVectorToPackedFunc(const std::vector<NDArray>& vec) {
auto body = [vec](TVMArgs args, TVMRetValue* rv) {
auto body = [vec](DGLArgs args, DGLRetValue* rv) {
const int which = args[0];
if (which >= vec.size()) {
LOG(FATAL) << "invalid choice";
......
......@@ -23,16 +23,16 @@ typedef void* GraphHandle;
* Return a temporary DLManagedTensor that does not own memory.
*/
DLManagedTensor* CreateTmpDLManagedTensor(
const tvm::runtime::TVMArgValue& arg);
const dgl::runtime::DGLArgValue& arg);
/*!
* \brief Convert a vector of NDArray to PackedFunc.
*/
tvm::runtime::PackedFunc ConvertNDArrayVectorToPackedFunc(
const std::vector<tvm::runtime::NDArray>& vec);
dgl::runtime::PackedFunc ConvertNDArrayVectorToPackedFunc(
const std::vector<dgl::runtime::NDArray>& vec);
/*!\brief Return whether the array is a valid 1D int array*/
inline bool IsValidIdArray(const tvm::runtime::NDArray& arr) {
inline bool IsValidIdArray(const dgl::runtime::NDArray& arr) {
return arr->ctx.device_type == kDLCPU && arr->ndim == 1
&& arr->dtype.code == kDLInt && arr->dtype.bits == 64;
}
......@@ -43,9 +43,9 @@ inline bool IsValidIdArray(const tvm::runtime::NDArray& arr) {
* The element type of the vector must be convertible to int64_t.
*/
template<typename DType>
tvm::runtime::NDArray CopyVectorToNDArray(
dgl::runtime::NDArray CopyVectorToNDArray(
const std::vector<DType>& vec) {
using tvm::runtime::NDArray;
using dgl::runtime::NDArray;
const int64_t len = vec.size();
NDArray a = NDArray::Empty({len}, DLDataType{kDLInt, 64, 1}, DLContext{kDLCPU, 0});
std::copy(vec.begin(), vec.end(), static_cast<int64_t*>(a->data));
......
......@@ -7,18 +7,18 @@
#include <dgl/graph_op.h>
#include "../c_api_common.h"
using tvm::runtime::TVMArgs;
using tvm::runtime::TVMArgValue;
using tvm::runtime::TVMRetValue;
using tvm::runtime::PackedFunc;
using tvm::runtime::NDArray;
using dgl::runtime::DGLArgs;
using dgl::runtime::DGLArgValue;
using dgl::runtime::DGLRetValue;
using dgl::runtime::PackedFunc;
using dgl::runtime::NDArray;
namespace dgl {
namespace {
// Convert EdgeArray structure to PackedFunc.
PackedFunc ConvertEdgeArrayToPackedFunc(const Graph::EdgeArray& ea) {
auto body = [ea] (TVMArgs args, TVMRetValue* rv) {
auto body = [ea] (DGLArgs args, DGLRetValue* rv) {
const int which = args[0];
if (which == 0) {
*rv = std::move(ea.src);
......@@ -35,7 +35,7 @@ PackedFunc ConvertEdgeArrayToPackedFunc(const Graph::EdgeArray& ea) {
// Convert Subgraph structure to PackedFunc.
PackedFunc ConvertSubgraphToPackedFunc(const Subgraph& sg) {
auto body = [sg] (TVMArgs args, TVMRetValue* rv) {
auto body = [sg] (DGLArgs args, DGLRetValue* rv) {
const int which = args[0];
if (which == 0) {
Graph* gptr = new Graph();
......@@ -55,30 +55,30 @@ PackedFunc ConvertSubgraphToPackedFunc(const Subgraph& sg) {
} // namespace
TVM_REGISTER_GLOBAL("graph_index._CAPI_DGLGraphCreate")
.set_body([] (TVMArgs args, TVMRetValue* rv) {
DGL_REGISTER_GLOBAL("graph_index._CAPI_DGLGraphCreate")
.set_body([] (DGLArgs args, DGLRetValue* rv) {
bool multigraph = static_cast<bool>(args[0]);
GraphHandle ghandle = new Graph(multigraph);
*rv = ghandle;
});
TVM_REGISTER_GLOBAL("graph_index._CAPI_DGLGraphFree")
.set_body([] (TVMArgs args, TVMRetValue* rv) {
DGL_REGISTER_GLOBAL("graph_index._CAPI_DGLGraphFree")
.set_body([] (DGLArgs args, DGLRetValue* rv) {
GraphHandle ghandle = args[0];
Graph* gptr = static_cast<Graph*>(ghandle);
delete gptr;
});
TVM_REGISTER_GLOBAL("graph_index._CAPI_DGLGraphAddVertices")
.set_body([] (TVMArgs args, TVMRetValue* rv) {
DGL_REGISTER_GLOBAL("graph_index._CAPI_DGLGraphAddVertices")
.set_body([] (DGLArgs args, DGLRetValue* rv) {
GraphHandle ghandle = args[0];
Graph* gptr = static_cast<Graph*>(ghandle);
uint64_t num_vertices = args[1];
gptr->AddVertices(num_vertices);
});
TVM_REGISTER_GLOBAL("graph_index._CAPI_DGLGraphAddEdge")
.set_body([] (TVMArgs args, TVMRetValue* rv) {
DGL_REGISTER_GLOBAL("graph_index._CAPI_DGLGraphAddEdge")
.set_body([] (DGLArgs args, DGLRetValue* rv) {
GraphHandle ghandle = args[0];
Graph* gptr = static_cast<Graph*>(ghandle);
const dgl_id_t src = args[1];
......@@ -86,8 +86,8 @@ TVM_REGISTER_GLOBAL("graph_index._CAPI_DGLGraphAddEdge")
gptr->AddEdge(src, dst);
});
TVM_REGISTER_GLOBAL("graph_index._CAPI_DGLGraphAddEdges")
.set_body([] (TVMArgs args, TVMRetValue* rv) {
DGL_REGISTER_GLOBAL("graph_index._CAPI_DGLGraphAddEdges")
.set_body([] (DGLArgs args, DGLRetValue* rv) {
GraphHandle ghandle = args[0];
Graph* gptr = static_cast<Graph*>(ghandle);
const IdArray src = IdArray::FromDLPack(CreateTmpDLManagedTensor(args[1]));
......@@ -95,67 +95,67 @@ TVM_REGISTER_GLOBAL("graph_index._CAPI_DGLGraphAddEdges")
gptr->AddEdges(src, dst);
});
TVM_REGISTER_GLOBAL("graph_index._CAPI_DGLGraphClear")
.set_body([] (TVMArgs args, TVMRetValue* rv) {
DGL_REGISTER_GLOBAL("graph_index._CAPI_DGLGraphClear")
.set_body([] (DGLArgs args, DGLRetValue* rv) {
GraphHandle ghandle = args[0];
Graph* gptr = static_cast<Graph*>(ghandle);
gptr->Clear();
});
TVM_REGISTER_GLOBAL("graph_index._CAPI_DGLGraphIsMultigraph")
.set_body([] (TVMArgs args, TVMRetValue *rv) {
DGL_REGISTER_GLOBAL("graph_index._CAPI_DGLGraphIsMultigraph")
.set_body([] (DGLArgs args, DGLRetValue *rv) {
GraphHandle ghandle = args[0];
// NOTE: not const since we have caches
const Graph* gptr = static_cast<Graph*>(ghandle);
*rv = gptr->IsMultigraph();
});
TVM_REGISTER_GLOBAL("graph_index._CAPI_DGLGraphNumVertices")
.set_body([] (TVMArgs args, TVMRetValue* rv) {
DGL_REGISTER_GLOBAL("graph_index._CAPI_DGLGraphNumVertices")
.set_body([] (DGLArgs args, DGLRetValue* rv) {
GraphHandle ghandle = args[0];
const Graph* gptr = static_cast<Graph*>(ghandle);
*rv = static_cast<int64_t>(gptr->NumVertices());
});
TVM_REGISTER_GLOBAL("graph_index._CAPI_DGLGraphNumEdges")
.set_body([] (TVMArgs args, TVMRetValue* rv) {
DGL_REGISTER_GLOBAL("graph_index._CAPI_DGLGraphNumEdges")
.set_body([] (DGLArgs args, DGLRetValue* rv) {
GraphHandle ghandle = args[0];
const Graph* gptr = static_cast<Graph*>(ghandle);
*rv = static_cast<int64_t>(gptr->NumEdges());
});
TVM_REGISTER_GLOBAL("graph_index._CAPI_DGLGraphHasVertex")
.set_body([] (TVMArgs args, TVMRetValue* rv) {
DGL_REGISTER_GLOBAL("graph_index._CAPI_DGLGraphHasVertex")
.set_body([] (DGLArgs args, DGLRetValue* rv) {
GraphHandle ghandle = args[0];
const Graph* gptr = static_cast<Graph*>(ghandle);
const dgl_id_t vid = args[1];
*rv = gptr->HasVertex(vid);
});
TVM_REGISTER_GLOBAL("graph_index._CAPI_DGLGraphHasVertices")
.set_body([] (TVMArgs args, TVMRetValue* rv) {
DGL_REGISTER_GLOBAL("graph_index._CAPI_DGLGraphHasVertices")
.set_body([] (DGLArgs args, DGLRetValue* rv) {
GraphHandle ghandle = args[0];
const Graph* gptr = static_cast<Graph*>(ghandle);
const IdArray vids = IdArray::FromDLPack(CreateTmpDLManagedTensor(args[1]));
*rv = gptr->HasVertices(vids);
});
TVM_REGISTER_GLOBAL("graph_index._CAPI_DGLMapSubgraphNID")
.set_body([] (TVMArgs args, TVMRetValue* rv) {
DGL_REGISTER_GLOBAL("graph_index._CAPI_DGLMapSubgraphNID")
.set_body([] (DGLArgs args, DGLRetValue* rv) {
const IdArray parent_vids = IdArray::FromDLPack(CreateTmpDLManagedTensor(args[0]));
const IdArray query = IdArray::FromDLPack(CreateTmpDLManagedTensor(args[1]));
*rv = GraphOp::MapParentIdToSubgraphId(parent_vids, query);
});
TVM_REGISTER_GLOBAL("immutable_graph_index._CAPI_DGLExpandIds")
.set_body([] (TVMArgs args, TVMRetValue* rv) {
DGL_REGISTER_GLOBAL("immutable_graph_index._CAPI_DGLExpandIds")
.set_body([] (DGLArgs args, DGLRetValue* rv) {
const IdArray ids = IdArray::FromDLPack(CreateTmpDLManagedTensor(args[0]));
const IdArray offsets = IdArray::FromDLPack(CreateTmpDLManagedTensor(args[1]));
*rv = GraphOp::ExpandIds(ids, offsets);
});
TVM_REGISTER_GLOBAL("graph_index._CAPI_DGLGraphHasEdgeBetween")
.set_body([] (TVMArgs args, TVMRetValue* rv) {
DGL_REGISTER_GLOBAL("graph_index._CAPI_DGLGraphHasEdgeBetween")
.set_body([] (DGLArgs args, DGLRetValue* rv) {
GraphHandle ghandle = args[0];
const Graph* gptr = static_cast<Graph*>(ghandle);
const dgl_id_t src = args[1];
......@@ -163,8 +163,8 @@ TVM_REGISTER_GLOBAL("graph_index._CAPI_DGLGraphHasEdgeBetween")
*rv = gptr->HasEdgeBetween(src, dst);
});
TVM_REGISTER_GLOBAL("graph_index._CAPI_DGLGraphHasEdgesBetween")
.set_body([] (TVMArgs args, TVMRetValue* rv) {
DGL_REGISTER_GLOBAL("graph_index._CAPI_DGLGraphHasEdgesBetween")
.set_body([] (DGLArgs args, DGLRetValue* rv) {
GraphHandle ghandle = args[0];
const Graph* gptr = static_cast<Graph*>(ghandle);
const IdArray src = IdArray::FromDLPack(CreateTmpDLManagedTensor(args[1]));
......@@ -172,8 +172,8 @@ TVM_REGISTER_GLOBAL("graph_index._CAPI_DGLGraphHasEdgesBetween")
*rv = gptr->HasEdgesBetween(src, dst);
});
TVM_REGISTER_GLOBAL("graph_index._CAPI_DGLGraphPredecessors")
.set_body([] (TVMArgs args, TVMRetValue* rv) {
DGL_REGISTER_GLOBAL("graph_index._CAPI_DGLGraphPredecessors")
.set_body([] (DGLArgs args, DGLRetValue* rv) {
GraphHandle ghandle = args[0];
const Graph* gptr = static_cast<Graph*>(ghandle);
const dgl_id_t vid = args[1];
......@@ -181,8 +181,8 @@ TVM_REGISTER_GLOBAL("graph_index._CAPI_DGLGraphPredecessors")
*rv = gptr->Predecessors(vid, radius);
});
TVM_REGISTER_GLOBAL("graph_index._CAPI_DGLGraphSuccessors")
.set_body([] (TVMArgs args, TVMRetValue* rv) {
DGL_REGISTER_GLOBAL("graph_index._CAPI_DGLGraphSuccessors")
.set_body([] (DGLArgs args, DGLRetValue* rv) {
GraphHandle ghandle = args[0];
const Graph* gptr = static_cast<Graph*>(ghandle);
const dgl_id_t vid = args[1];
......@@ -190,8 +190,8 @@ TVM_REGISTER_GLOBAL("graph_index._CAPI_DGLGraphSuccessors")
*rv = gptr->Successors(vid, radius);
});
TVM_REGISTER_GLOBAL("graph_index._CAPI_DGLGraphEdgeId")
.set_body([] (TVMArgs args, TVMRetValue* rv) {
DGL_REGISTER_GLOBAL("graph_index._CAPI_DGLGraphEdgeId")
.set_body([] (DGLArgs args, DGLRetValue* rv) {
GraphHandle ghandle = args[0];
const Graph* gptr = static_cast<Graph*>(ghandle);
const dgl_id_t src = args[1];
......@@ -199,8 +199,8 @@ TVM_REGISTER_GLOBAL("graph_index._CAPI_DGLGraphEdgeId")
*rv = gptr->EdgeId(src, dst);
});
TVM_REGISTER_GLOBAL("graph_index._CAPI_DGLGraphEdgeIds")
.set_body([] (TVMArgs args, TVMRetValue* rv) {
DGL_REGISTER_GLOBAL("graph_index._CAPI_DGLGraphEdgeIds")
.set_body([] (DGLArgs args, DGLRetValue* rv) {
GraphHandle ghandle = args[0];
const Graph* gptr = static_cast<Graph*>(ghandle);
const IdArray src = IdArray::FromDLPack(CreateTmpDLManagedTensor(args[1]));
......@@ -208,104 +208,104 @@ TVM_REGISTER_GLOBAL("graph_index._CAPI_DGLGraphEdgeIds")
*rv = ConvertEdgeArrayToPackedFunc(gptr->EdgeIds(src, dst));
});
TVM_REGISTER_GLOBAL("graph_index._CAPI_DGLGraphFindEdges")
.set_body([] (TVMArgs args, TVMRetValue* rv) {
DGL_REGISTER_GLOBAL("graph_index._CAPI_DGLGraphFindEdges")
.set_body([] (DGLArgs args, DGLRetValue* rv) {
GraphHandle ghandle = args[0];
const Graph* gptr = static_cast<Graph*>(ghandle);
const IdArray eids = IdArray::FromDLPack(CreateTmpDLManagedTensor(args[1]));
*rv = ConvertEdgeArrayToPackedFunc(gptr->FindEdges(eids));
});
TVM_REGISTER_GLOBAL("graph_index._CAPI_DGLGraphInEdges_1")
.set_body([] (TVMArgs args, TVMRetValue* rv) {
DGL_REGISTER_GLOBAL("graph_index._CAPI_DGLGraphInEdges_1")
.set_body([] (DGLArgs args, DGLRetValue* rv) {
GraphHandle ghandle = args[0];
const Graph* gptr = static_cast<Graph*>(ghandle);
const dgl_id_t vid = args[1];
*rv = ConvertEdgeArrayToPackedFunc(gptr->InEdges(vid));
});
TVM_REGISTER_GLOBAL("graph_index._CAPI_DGLGraphInEdges_2")
.set_body([] (TVMArgs args, TVMRetValue* rv) {
DGL_REGISTER_GLOBAL("graph_index._CAPI_DGLGraphInEdges_2")
.set_body([] (DGLArgs args, DGLRetValue* rv) {
GraphHandle ghandle = args[0];
const Graph* gptr = static_cast<Graph*>(ghandle);
const IdArray vids = IdArray::FromDLPack(CreateTmpDLManagedTensor(args[1]));
*rv = ConvertEdgeArrayToPackedFunc(gptr->InEdges(vids));
});
TVM_REGISTER_GLOBAL("graph_index._CAPI_DGLGraphOutEdges_1")
.set_body([] (TVMArgs args, TVMRetValue* rv) {
DGL_REGISTER_GLOBAL("graph_index._CAPI_DGLGraphOutEdges_1")
.set_body([] (DGLArgs args, DGLRetValue* rv) {
GraphHandle ghandle = args[0];
const Graph* gptr = static_cast<Graph*>(ghandle);
const dgl_id_t vid = args[1];
*rv = ConvertEdgeArrayToPackedFunc(gptr->OutEdges(vid));
});
TVM_REGISTER_GLOBAL("graph_index._CAPI_DGLGraphOutEdges_2")
.set_body([] (TVMArgs args, TVMRetValue* rv) {
DGL_REGISTER_GLOBAL("graph_index._CAPI_DGLGraphOutEdges_2")
.set_body([] (DGLArgs args, DGLRetValue* rv) {
GraphHandle ghandle = args[0];
const Graph* gptr = static_cast<Graph*>(ghandle);
const IdArray vids = IdArray::FromDLPack(CreateTmpDLManagedTensor(args[1]));
*rv = ConvertEdgeArrayToPackedFunc(gptr->OutEdges(vids));
});
TVM_REGISTER_GLOBAL("graph_index._CAPI_DGLGraphEdges")
.set_body([] (TVMArgs args, TVMRetValue* rv) {
DGL_REGISTER_GLOBAL("graph_index._CAPI_DGLGraphEdges")
.set_body([] (DGLArgs args, DGLRetValue* rv) {
GraphHandle ghandle = args[0];
const Graph* gptr = static_cast<Graph*>(ghandle);
const bool sorted = args[1];
*rv = ConvertEdgeArrayToPackedFunc(gptr->Edges(sorted));
});
TVM_REGISTER_GLOBAL("graph_index._CAPI_DGLGraphInDegree")
.set_body([] (TVMArgs args, TVMRetValue* rv) {
DGL_REGISTER_GLOBAL("graph_index._CAPI_DGLGraphInDegree")
.set_body([] (DGLArgs args, DGLRetValue* rv) {
GraphHandle ghandle = args[0];
const Graph* gptr = static_cast<Graph*>(ghandle);
const dgl_id_t vid = args[1];
*rv = static_cast<int64_t>(gptr->InDegree(vid));
});
TVM_REGISTER_GLOBAL("graph_index._CAPI_DGLGraphInDegrees")
.set_body([] (TVMArgs args, TVMRetValue* rv) {
DGL_REGISTER_GLOBAL("graph_index._CAPI_DGLGraphInDegrees")
.set_body([] (DGLArgs args, DGLRetValue* rv) {
GraphHandle ghandle = args[0];
const Graph* gptr = static_cast<Graph*>(ghandle);
const IdArray vids = IdArray::FromDLPack(CreateTmpDLManagedTensor(args[1]));
*rv = gptr->InDegrees(vids);
});
TVM_REGISTER_GLOBAL("graph_index._CAPI_DGLGraphOutDegree")
.set_body([] (TVMArgs args, TVMRetValue* rv) {
DGL_REGISTER_GLOBAL("graph_index._CAPI_DGLGraphOutDegree")
.set_body([] (DGLArgs args, DGLRetValue* rv) {
GraphHandle ghandle = args[0];
const Graph* gptr = static_cast<Graph*>(ghandle);
const dgl_id_t vid = args[1];
*rv = static_cast<int64_t>(gptr->OutDegree(vid));
});
TVM_REGISTER_GLOBAL("graph_index._CAPI_DGLGraphOutDegrees")
.set_body([] (TVMArgs args, TVMRetValue* rv) {
DGL_REGISTER_GLOBAL("graph_index._CAPI_DGLGraphOutDegrees")
.set_body([] (DGLArgs args, DGLRetValue* rv) {
GraphHandle ghandle = args[0];
const Graph* gptr = static_cast<Graph*>(ghandle);
const IdArray vids = IdArray::FromDLPack(CreateTmpDLManagedTensor(args[1]));
*rv = gptr->OutDegrees(vids);
});
TVM_REGISTER_GLOBAL("graph_index._CAPI_DGLGraphVertexSubgraph")
.set_body([] (TVMArgs args, TVMRetValue* rv) {
DGL_REGISTER_GLOBAL("graph_index._CAPI_DGLGraphVertexSubgraph")
.set_body([] (DGLArgs args, DGLRetValue* rv) {
GraphHandle ghandle = args[0];
const Graph* gptr = static_cast<Graph*>(ghandle);
const IdArray vids = IdArray::FromDLPack(CreateTmpDLManagedTensor(args[1]));
*rv = ConvertSubgraphToPackedFunc(gptr->VertexSubgraph(vids));
});
TVM_REGISTER_GLOBAL("graph_index._CAPI_DGLGraphEdgeSubgraph")
.set_body([] (TVMArgs args, TVMRetValue* rv) {
DGL_REGISTER_GLOBAL("graph_index._CAPI_DGLGraphEdgeSubgraph")
.set_body([] (DGLArgs args, DGLRetValue* rv) {
GraphHandle ghandle = args[0];
const Graph *gptr = static_cast<Graph*>(ghandle);
const IdArray eids = IdArray::FromDLPack(CreateTmpDLManagedTensor(args[1]));
*rv = ConvertSubgraphToPackedFunc(gptr->EdgeSubgraph(eids));
});
TVM_REGISTER_GLOBAL("graph_index._CAPI_DGLDisjointUnion")
.set_body([] (TVMArgs args, TVMRetValue* rv) {
DGL_REGISTER_GLOBAL("graph_index._CAPI_DGLDisjointUnion")
.set_body([] (DGLArgs args, DGLRetValue* rv) {
void* list = args[0];
GraphHandle* inhandles = static_cast<GraphHandle*>(list);
int list_size = args[1];
......@@ -320,8 +320,8 @@ TVM_REGISTER_GLOBAL("graph_index._CAPI_DGLDisjointUnion")
*rv = ghandle;
});
TVM_REGISTER_GLOBAL("graph_index._CAPI_DGLDisjointPartitionByNum")
.set_body([] (TVMArgs args, TVMRetValue* rv) {
DGL_REGISTER_GLOBAL("graph_index._CAPI_DGLDisjointPartitionByNum")
.set_body([] (DGLArgs args, DGLRetValue* rv) {
GraphHandle ghandle = args[0];
const Graph* gptr = static_cast<Graph*>(ghandle);
int64_t num = args[1];
......@@ -338,8 +338,8 @@ TVM_REGISTER_GLOBAL("graph_index._CAPI_DGLDisjointPartitionByNum")
*rv = ptr_array;
});
TVM_REGISTER_GLOBAL("graph_index._CAPI_DGLDisjointPartitionBySizes")
.set_body([] (TVMArgs args, TVMRetValue* rv) {
DGL_REGISTER_GLOBAL("graph_index._CAPI_DGLDisjointPartitionBySizes")
.set_body([] (DGLArgs args, DGLRetValue* rv) {
GraphHandle ghandle = args[0];
const Graph* gptr = static_cast<Graph*>(ghandle);
const IdArray sizes = IdArray::FromDLPack(CreateTmpDLManagedTensor(args[1]));
......@@ -356,8 +356,8 @@ TVM_REGISTER_GLOBAL("graph_index._CAPI_DGLDisjointPartitionBySizes")
*rv = ptr_array;
});
TVM_REGISTER_GLOBAL("graph_index._CAPI_DGLGraphLineGraph")
.set_body([] (TVMArgs args, TVMRetValue* rv) {
DGL_REGISTER_GLOBAL("graph_index._CAPI_DGLGraphLineGraph")
.set_body([] (DGLArgs args, DGLRetValue* rv) {
GraphHandle ghandle = args[0];
bool backtracking = args[1];
const Graph* gptr = static_cast<Graph*>(ghandle);
......
......@@ -8,11 +8,11 @@
#include "./traversal.h"
#include "../c_api_common.h"
using tvm::runtime::TVMArgs;
using tvm::runtime::TVMArgValue;
using tvm::runtime::TVMRetValue;
using tvm::runtime::PackedFunc;
using tvm::runtime::NDArray;
using dgl::runtime::DGLArgs;
using dgl::runtime::DGLArgValue;
using dgl::runtime::DGLRetValue;
using dgl::runtime::PackedFunc;
using dgl::runtime::NDArray;
namespace dgl {
namespace traverse {
......@@ -129,8 +129,8 @@ Frontiers BFSNodesFrontiers(const Graph& graph, IdArray source, bool reversed) {
return front;
}
TVM_REGISTER_GLOBAL("traversal._CAPI_DGLBFSNodes")
.set_body([] (TVMArgs args, TVMRetValue* rv) {
DGL_REGISTER_GLOBAL("traversal._CAPI_DGLBFSNodes")
.set_body([] (DGLArgs args, DGLRetValue* rv) {
GraphHandle ghandle = args[0];
const Graph* gptr = static_cast<Graph*>(ghandle);
const IdArray src = IdArray::FromDLPack(CreateTmpDLManagedTensor(args[1]));
......@@ -160,8 +160,8 @@ Frontiers BFSEdgesFrontiers(const Graph& graph, IdArray source, bool reversed) {
return front;
}
TVM_REGISTER_GLOBAL("traversal._CAPI_DGLBFSEdges")
.set_body([] (TVMArgs args, TVMRetValue* rv) {
DGL_REGISTER_GLOBAL("traversal._CAPI_DGLBFSEdges")
.set_body([] (DGLArgs args, DGLRetValue* rv) {
GraphHandle ghandle = args[0];
const Graph* gptr = static_cast<Graph*>(ghandle);
const IdArray src = IdArray::FromDLPack(CreateTmpDLManagedTensor(args[1]));
......@@ -186,8 +186,8 @@ Frontiers TopologicalNodesFrontiers(const Graph& graph, bool reversed) {
return front;
}
TVM_REGISTER_GLOBAL("traversal._CAPI_DGLTopologicalNodes")
.set_body([] (TVMArgs args, TVMRetValue* rv) {
DGL_REGISTER_GLOBAL("traversal._CAPI_DGLTopologicalNodes")
.set_body([] (DGLArgs args, DGLRetValue* rv) {
GraphHandle ghandle = args[0];
const Graph* gptr = static_cast<Graph*>(ghandle);
bool reversed = args[1];
......@@ -198,8 +198,8 @@ TVM_REGISTER_GLOBAL("traversal._CAPI_DGLTopologicalNodes")
});
TVM_REGISTER_GLOBAL("traversal._CAPI_DGLDFSEdges")
.set_body([] (TVMArgs args, TVMRetValue* rv) {
DGL_REGISTER_GLOBAL("traversal._CAPI_DGLDFSEdges")
.set_body([] (DGLArgs args, DGLRetValue* rv) {
GraphHandle ghandle = args[0];
const Graph* gptr = static_cast<Graph*>(ghandle);
const IdArray source = args[1];
......@@ -217,8 +217,8 @@ TVM_REGISTER_GLOBAL("traversal._CAPI_DGLDFSEdges")
*rv = ConvertNDArrayVectorToPackedFunc({ids, sections});
});
TVM_REGISTER_GLOBAL("traversal._CAPI_DGLDFSLabeledEdges")
.set_body([] (TVMArgs args, TVMRetValue* rv) {
DGL_REGISTER_GLOBAL("traversal._CAPI_DGLDFSLabeledEdges")
.set_body([] (DGLArgs args, DGLRetValue* rv) {
GraphHandle ghandle = args[0];
const Graph* gptr = static_cast<Graph*>(ghandle);
const IdArray source = args[1];
......
......@@ -16,7 +16,7 @@
#include <cstdlib>
#include "runtime_base.h"
namespace tvm {
namespace dgl {
namespace runtime {
/*!
......@@ -44,7 +44,7 @@ class DeviceAPIManager {
public:
static const int kMaxDeviceAPI = 32;
// Get API
static DeviceAPI* Get(const TVMContext& ctx) {
static DeviceAPI* Get(const DGLContext& ctx) {
return Get(ctx.device_type);
}
static DeviceAPI* Get(int dev_type, bool allow_missing = false) {
......@@ -93,81 +93,81 @@ class DeviceAPIManager {
}
};
DeviceAPI* DeviceAPI::Get(TVMContext ctx, bool allow_missing) {
DeviceAPI* DeviceAPI::Get(DGLContext ctx, bool allow_missing) {
return DeviceAPIManager::Get(
static_cast<int>(ctx.device_type), allow_missing);
}
void* DeviceAPI::AllocWorkspace(TVMContext ctx,
void* DeviceAPI::AllocWorkspace(DGLContext ctx,
size_t size,
TVMType type_hint) {
DGLType type_hint) {
return AllocDataSpace(ctx, size, kTempAllocaAlignment, type_hint);
}
void DeviceAPI::FreeWorkspace(TVMContext ctx, void* ptr) {
void DeviceAPI::FreeWorkspace(DGLContext ctx, void* ptr) {
FreeDataSpace(ctx, ptr);
}
TVMStreamHandle DeviceAPI::CreateStream(TVMContext ctx) {
DGLStreamHandle DeviceAPI::CreateStream(DGLContext ctx) {
LOG(FATAL) << "Device does not support stream api.";
return 0;
}
void DeviceAPI::FreeStream(TVMContext ctx, TVMStreamHandle stream) {
void DeviceAPI::FreeStream(DGLContext ctx, DGLStreamHandle stream) {
LOG(FATAL) << "Device does not support stream api.";
}
void DeviceAPI::SyncStreamFromTo(TVMContext ctx,
TVMStreamHandle event_src,
TVMStreamHandle event_dst) {
void DeviceAPI::SyncStreamFromTo(DGLContext ctx,
DGLStreamHandle event_src,
DGLStreamHandle event_dst) {
LOG(FATAL) << "Device does not support stream api.";
}
} // namespace runtime
} // namespace tvm
} // namespace dgl
using namespace tvm::runtime;
using namespace dgl::runtime;
struct TVMRuntimeEntry {
struct DGLRuntimeEntry {
std::string ret_str;
std::string last_error;
TVMByteArray ret_bytes;
DGLByteArray ret_bytes;
};
typedef dmlc::ThreadLocalStore<TVMRuntimeEntry> TVMAPIRuntimeStore;
typedef dmlc::ThreadLocalStore<DGLRuntimeEntry> DGLAPIRuntimeStore;
const char *TVMGetLastError() {
return TVMAPIRuntimeStore::Get()->last_error.c_str();
const char *DGLGetLastError() {
return DGLAPIRuntimeStore::Get()->last_error.c_str();
}
void TVMAPISetLastError(const char* msg) {
void DGLAPISetLastError(const char* msg) {
#ifndef _LIBCPP_SGX_CONFIG
TVMAPIRuntimeStore::Get()->last_error = msg;
DGLAPIRuntimeStore::Get()->last_error = msg;
#else
sgx::OCallPackedFunc("__sgx_set_last_error__", msg);
#endif
}
int TVMModLoadFromFile(const char* file_name,
int DGLModLoadFromFile(const char* file_name,
const char* format,
TVMModuleHandle* out) {
DGLModuleHandle* out) {
API_BEGIN();
Module m = Module::LoadFromFile(file_name, format);
*out = new Module(m);
API_END();
}
int TVMModImport(TVMModuleHandle mod,
TVMModuleHandle dep) {
int DGLModImport(DGLModuleHandle mod,
DGLModuleHandle dep) {
API_BEGIN();
static_cast<Module*>(mod)->Import(
*static_cast<Module*>(dep));
API_END();
}
int TVMModGetFunction(TVMModuleHandle mod,
int DGLModGetFunction(DGLModuleHandle mod,
const char* func_name,
int query_imports,
TVMFunctionHandle *func) {
DGLFunctionHandle *func) {
API_BEGIN();
PackedFunc pf = static_cast<Module*>(mod)->GetFunction(
func_name, query_imports != 0);
......@@ -179,31 +179,31 @@ int TVMModGetFunction(TVMModuleHandle mod,
API_END();
}
int TVMModFree(TVMModuleHandle mod) {
int DGLModFree(DGLModuleHandle mod) {
API_BEGIN();
delete static_cast<Module*>(mod);
API_END();
}
int TVMBackendGetFuncFromEnv(void* mod_node,
int DGLBackendGetFuncFromEnv(void* mod_node,
const char* func_name,
TVMFunctionHandle *func) {
DGLFunctionHandle *func) {
API_BEGIN();
*func = (TVMFunctionHandle)(
*func = (DGLFunctionHandle)(
static_cast<ModuleNode*>(mod_node)->GetFuncFromEnv(func_name));
API_END();
}
void* TVMBackendAllocWorkspace(int device_type,
void* DGLBackendAllocWorkspace(int device_type,
int device_id,
uint64_t size,
int dtype_code_hint,
int dtype_bits_hint) {
TVMContext ctx;
DGLContext ctx;
ctx.device_type = static_cast<DLDeviceType>(device_type);
ctx.device_id = device_id;
TVMType type_hint;
DGLType type_hint;
type_hint.code = static_cast<decltype(type_hint.code)>(dtype_code_hint);
type_hint.bits = static_cast<decltype(type_hint.bits)>(dtype_bits_hint);
type_hint.lanes = 1;
......@@ -213,17 +213,17 @@ void* TVMBackendAllocWorkspace(int device_type,
type_hint);
}
int TVMBackendFreeWorkspace(int device_type,
int DGLBackendFreeWorkspace(int device_type,
int device_id,
void* ptr) {
TVMContext ctx;
DGLContext ctx;
ctx.device_type = static_cast<DLDeviceType>(device_type);
ctx.device_id = device_id;
DeviceAPIManager::Get(ctx)->FreeWorkspace(ctx, ptr);
return 0;
}
int TVMBackendRunOnce(void** handle,
int DGLBackendRunOnce(void** handle,
int (*f)(void*),
void* cdata,
int nbytes) {
......@@ -234,28 +234,28 @@ int TVMBackendRunOnce(void** handle,
return 0;
}
int TVMFuncFree(TVMFunctionHandle func) {
int DGLFuncFree(DGLFunctionHandle func) {
API_BEGIN();
delete static_cast<PackedFunc*>(func);
API_END();
}
int TVMFuncCall(TVMFunctionHandle func,
TVMValue* args,
int DGLFuncCall(DGLFunctionHandle func,
DGLValue* args,
int* arg_type_codes,
int num_args,
TVMValue* ret_val,
DGLValue* ret_val,
int* ret_type_code) {
API_BEGIN();
TVMRetValue rv;
DGLRetValue rv;
(*static_cast<const PackedFunc*>(func)).CallPacked(
TVMArgs(args, arg_type_codes, num_args), &rv);
DGLArgs(args, arg_type_codes, num_args), &rv);
// handle return string.
if (rv.type_code() == kStr ||
rv.type_code() == kTVMType ||
rv.type_code() == kDGLType ||
rv.type_code() == kBytes) {
TVMRuntimeEntry* e = TVMAPIRuntimeStore::Get();
if (rv.type_code() != kTVMType) {
DGLRuntimeEntry* e = DGLAPIRuntimeStore::Get();
if (rv.type_code() != kDGLType) {
e->ret_str = *rv.ptr<std::string>();
} else {
e->ret_str = rv.operator std::string();
......@@ -275,30 +275,30 @@ int TVMFuncCall(TVMFunctionHandle func,
API_END();
}
int TVMCFuncSetReturn(TVMRetValueHandle ret,
TVMValue* value,
int DGLCFuncSetReturn(DGLRetValueHandle ret,
DGLValue* value,
int* type_code,
int num_ret) {
API_BEGIN();
CHECK_EQ(num_ret, 1);
TVMRetValue* rv = static_cast<TVMRetValue*>(ret);
*rv = TVMArgValue(value[0], type_code[0]);
DGLRetValue* rv = static_cast<DGLRetValue*>(ret);
*rv = DGLArgValue(value[0], type_code[0]);
API_END();
}
int TVMFuncCreateFromCFunc(TVMPackedCFunc func,
int DGLFuncCreateFromCFunc(DGLPackedCFunc func,
void* resource_handle,
TVMPackedCFuncFinalizer fin,
TVMFunctionHandle *out) {
DGLPackedCFuncFinalizer fin,
DGLFunctionHandle *out) {
API_BEGIN();
if (fin == nullptr) {
*out = new PackedFunc(
[func, resource_handle](TVMArgs args, TVMRetValue* rv) {
int ret = func((TVMValue*)args.values, (int*)args.type_codes, // NOLINT(*)
[func, resource_handle](DGLArgs args, DGLRetValue* rv) {
int ret = func((DGLValue*)args.values, (int*)args.type_codes, // NOLINT(*)
args.num_args, rv, resource_handle);
if (ret != 0) {
std::string err = "TVMCall CFunc Error:\n";
err += TVMGetLastError();
std::string err = "DGLCall CFunc Error:\n";
err += DGLGetLastError();
throw dmlc::Error(err);
}
});
......@@ -307,12 +307,12 @@ int TVMFuncCreateFromCFunc(TVMPackedCFunc func,
// so fin will be called when the lambda went out of scope.
std::shared_ptr<void> rpack(resource_handle, fin);
*out = new PackedFunc(
[func, rpack](TVMArgs args, TVMRetValue* rv) {
int ret = func((TVMValue*)args.values, (int*)args.type_codes, // NOLINT(*)
[func, rpack](DGLArgs args, DGLRetValue* rv) {
int ret = func((DGLValue*)args.values, (int*)args.type_codes, // NOLINT(*)
args.num_args, rv, rpack.get());
if (ret != 0) {
std::string err = "TVMCall CFunc Error:\n";
err += TVMGetLastError();
std::string err = "DGLCall CFunc Error:\n";
err += DGLGetLastError();
throw dmlc::Error(err);
}
});
......@@ -320,58 +320,58 @@ int TVMFuncCreateFromCFunc(TVMPackedCFunc func,
API_END();
}
int TVMStreamCreate(int device_type, int device_id, TVMStreamHandle* out) {
int DGLStreamCreate(int device_type, int device_id, DGLStreamHandle* out) {
API_BEGIN();
TVMContext ctx;
DGLContext ctx;
ctx.device_type = static_cast<DLDeviceType>(device_type);
ctx.device_id = device_id;
*out = DeviceAPIManager::Get(ctx)->CreateStream(ctx);
API_END();
}
int TVMStreamFree(int device_type, int device_id, TVMStreamHandle stream) {
int DGLStreamFree(int device_type, int device_id, DGLStreamHandle stream) {
API_BEGIN();
TVMContext ctx;
DGLContext ctx;
ctx.device_type = static_cast<DLDeviceType>(device_type);
ctx.device_id = device_id;
DeviceAPIManager::Get(ctx)->FreeStream(ctx, stream);
API_END();
}
int TVMSetStream(int device_type, int device_id, TVMStreamHandle stream) {
int DGLSetStream(int device_type, int device_id, DGLStreamHandle stream) {
API_BEGIN();
TVMContext ctx;
DGLContext ctx;
ctx.device_type = static_cast<DLDeviceType>(device_type);
ctx.device_id = device_id;
DeviceAPIManager::Get(ctx)->SetStream(ctx, stream);
API_END();
}
int TVMSynchronize(int device_type, int device_id, TVMStreamHandle stream) {
int DGLSynchronize(int device_type, int device_id, DGLStreamHandle stream) {
API_BEGIN();
TVMContext ctx;
DGLContext ctx;
ctx.device_type = static_cast<DLDeviceType>(device_type);
ctx.device_id = device_id;
DeviceAPIManager::Get(ctx)->StreamSync(ctx, stream);
API_END();
}
int TVMStreamStreamSynchronize(int device_type,
int DGLStreamStreamSynchronize(int device_type,
int device_id,
TVMStreamHandle src,
TVMStreamHandle dst) {
DGLStreamHandle src,
DGLStreamHandle dst) {
API_BEGIN();
TVMContext ctx;
DGLContext ctx;
ctx.device_type = static_cast<DLDeviceType>(device_type);
ctx.device_id = device_id;
DeviceAPIManager::Get(ctx)->SyncStreamFromTo(ctx, src, dst);
API_END();
}
int TVMCbArgToReturn(TVMValue* value, int code) {
int DGLCbArgToReturn(DGLValue* value, int code) {
API_BEGIN();
tvm::runtime::TVMRetValue rv;
rv = tvm::runtime::TVMArgValue(*value, code);
dgl::runtime::DGLRetValue rv;
rv = dgl::runtime::DGLArgValue(*value, code);
int tcode;
rv.MoveToCHost(value, &tcode);
CHECK_EQ(tcode, code);
......@@ -379,18 +379,18 @@ int TVMCbArgToReturn(TVMValue* value, int code) {
}
// set device api
TVM_REGISTER_GLOBAL(tvm::runtime::symbol::tvm_set_device)
.set_body([](TVMArgs args, TVMRetValue *ret) {
TVMContext ctx;
DGL_REGISTER_GLOBAL(dgl::runtime::symbol::dgl_set_device)
.set_body([](DGLArgs args, DGLRetValue *ret) {
DGLContext ctx;
ctx.device_type = static_cast<DLDeviceType>(args[0].operator int());
ctx.device_id = args[1];
DeviceAPIManager::Get(ctx)->SetDevice(ctx);
});
// set device api
TVM_REGISTER_GLOBAL("_GetDeviceAttr")
.set_body([](TVMArgs args, TVMRetValue *ret) {
TVMContext ctx;
DGL_REGISTER_GLOBAL("_GetDeviceAttr")
.set_body([](DGLArgs args, DGLRetValue *ret) {
DGLContext ctx;
ctx.device_type = static_cast<DLDeviceType>(args[0].operator int());
ctx.device_id = args[1];
......
......@@ -10,20 +10,20 @@
#include <cstring>
#include "workspace_pool.h"
namespace tvm {
namespace dgl {
namespace runtime {
class CPUDeviceAPI final : public DeviceAPI {
public:
void SetDevice(TVMContext ctx) final {}
void GetAttr(TVMContext ctx, DeviceAttrKind kind, TVMRetValue* rv) final {
void SetDevice(DGLContext ctx) final {}
void GetAttr(DGLContext ctx, DeviceAttrKind kind, DGLRetValue* rv) final {
if (kind == kExist) {
*rv = 1;
}
}
void* AllocDataSpace(TVMContext ctx,
void* AllocDataSpace(DGLContext ctx,
size_t nbytes,
size_t alignment,
TVMType type_hint) final {
DGLType type_hint) final {
void* ptr;
#if _MSC_VER || defined(__MINGW32__)
ptr = _aligned_malloc(nbytes, alignment);
......@@ -38,7 +38,7 @@ class CPUDeviceAPI final : public DeviceAPI {
return ptr;
}
void FreeDataSpace(TVMContext ctx, void* ptr) final {
void FreeDataSpace(DGLContext ctx, void* ptr) final {
#if _MSC_VER || defined(__MINGW32__)
_aligned_free(ptr);
#else
......@@ -51,20 +51,20 @@ class CPUDeviceAPI final : public DeviceAPI {
void* to,
size_t to_offset,
size_t size,
TVMContext ctx_from,
TVMContext ctx_to,
TVMType type_hint,
TVMStreamHandle stream) final {
DGLContext ctx_from,
DGLContext ctx_to,
DGLType type_hint,
DGLStreamHandle stream) final {
memcpy(static_cast<char*>(to) + to_offset,
static_cast<const char*>(from) + from_offset,
size);
}
void StreamSync(TVMContext ctx, TVMStreamHandle stream) final {
void StreamSync(DGLContext ctx, DGLStreamHandle stream) final {
}
void* AllocWorkspace(TVMContext ctx, size_t size, TVMType type_hint) final;
void FreeWorkspace(TVMContext ctx, void* data) final;
void* AllocWorkspace(DGLContext ctx, size_t size, DGLType type_hint) final;
void FreeWorkspace(DGLContext ctx, void* data) final;
static const std::shared_ptr<CPUDeviceAPI>& Global() {
static std::shared_ptr<CPUDeviceAPI> inst =
......@@ -78,21 +78,21 @@ struct CPUWorkspacePool : public WorkspacePool {
WorkspacePool(kDLCPU, CPUDeviceAPI::Global()) {}
};
void* CPUDeviceAPI::AllocWorkspace(TVMContext ctx,
void* CPUDeviceAPI::AllocWorkspace(DGLContext ctx,
size_t size,
TVMType type_hint) {
DGLType type_hint) {
return dmlc::ThreadLocalStore<CPUWorkspacePool>::Get()
->AllocWorkspace(ctx, size);
}
void CPUDeviceAPI::FreeWorkspace(TVMContext ctx, void* data) {
void CPUDeviceAPI::FreeWorkspace(DGLContext ctx, void* data) {
dmlc::ThreadLocalStore<CPUWorkspacePool>::Get()->FreeWorkspace(ctx, data);
}
TVM_REGISTER_GLOBAL("device_api.cpu")
.set_body([](TVMArgs args, TVMRetValue* rv) {
DGL_REGISTER_GLOBAL("device_api.cpu")
.set_body([](DGLArgs args, DGLRetValue* rv) {
DeviceAPI* ptr = CPUDeviceAPI::Global().get();
*rv = static_cast<void*>(ptr);
});
} // namespace runtime
} // namespace tvm
} // namespace dgl
......@@ -14,11 +14,11 @@
#include <dlfcn.h>
#endif
namespace tvm {
namespace dgl {
namespace runtime {
// Module to load from dynamic shared libary.
// This is the default module TVM used for host-side AOT
// This is the default module DGL used for host-side AOT
class DSOModuleNode final : public ModuleNode {
public:
~DSOModuleNode() {
......@@ -33,11 +33,11 @@ class DSOModuleNode final : public ModuleNode {
const std::string& name,
const std::shared_ptr<ModuleNode>& sptr_to_self) final {
BackendPackedCFunc faddr;
if (name == runtime::symbol::tvm_module_main) {
if (name == runtime::symbol::dgl_module_main) {
const char* entry_name = reinterpret_cast<const char*>(
GetSymbol(runtime::symbol::tvm_module_main));
GetSymbol(runtime::symbol::dgl_module_main));
CHECK(entry_name!= nullptr)
<< "Symbol " << runtime::symbol::tvm_module_main << " is not presented";
<< "Symbol " << runtime::symbol::dgl_module_main << " is not presented";
faddr = reinterpret_cast<BackendPackedCFunc>(GetSymbol(entry_name));
} else {
faddr = reinterpret_cast<BackendPackedCFunc>(GetSymbol(name.c_str()));
......@@ -49,7 +49,7 @@ class DSOModuleNode final : public ModuleNode {
void Init(const std::string& name) {
Load(name);
if (auto *ctx_addr =
reinterpret_cast<void**>(GetSymbol(runtime::symbol::tvm_module_ctx))) {
reinterpret_cast<void**>(GetSymbol(runtime::symbol::dgl_module_ctx))) {
*ctx_addr = this;
}
InitContextFunctions([this](const char* fname) {
......@@ -58,7 +58,7 @@ class DSOModuleNode final : public ModuleNode {
// Load the imported modules
const char* dev_mblob =
reinterpret_cast<const char*>(
GetSymbol(runtime::symbol::tvm_dev_mblob));
GetSymbol(runtime::symbol::dgl_dev_mblob));
if (dev_mblob != nullptr) {
ImportModuleBlob(dev_mblob, &imports_);
}
......@@ -103,11 +103,11 @@ class DSOModuleNode final : public ModuleNode {
#endif
};
TVM_REGISTER_GLOBAL("module.loadfile_so")
.set_body([](TVMArgs args, TVMRetValue* rv) {
DGL_REGISTER_GLOBAL("module.loadfile_so")
.set_body([](DGLArgs args, DGLRetValue* rv) {
std::shared_ptr<DSOModuleNode> n = std::make_shared<DSOModuleNode>();
n->Init(args[0]);
*rv = runtime::Module(n);
});
} // namespace runtime
} // namespace tvm
} // namespace dgl
......@@ -10,13 +10,13 @@
#include "file_util.h"
namespace tvm {
namespace dgl {
namespace runtime {
void FunctionInfo::Save(dmlc::JSONWriter* writer) const {
std::vector<std::string> sarg_types(arg_types.size());
for (size_t i = 0; i < arg_types.size(); ++i) {
sarg_types[i] = TVMType2String(arg_types[i]);
sarg_types[i] = DGLType2String(arg_types[i]);
}
writer->BeginObject();
writer->WriteObjectKeyValue("name", name);
......@@ -34,7 +34,7 @@ void FunctionInfo::Load(dmlc::JSONReader* reader) {
helper.ReadAllFields(reader);
arg_types.resize(sarg_types.size());
for (size_t i = 0; i < arg_types.size(); ++i) {
arg_types[i] = String2TVMType(sarg_types[i]);
arg_types[i] = String2DGLType(sarg_types[i]);
}
}
......@@ -69,12 +69,12 @@ std::string GetFileFormat(const std::string& file_name,
std::string GetCacheDir() {
char* env_cache_dir;
if ((env_cache_dir = getenv("TVM_CACHE_DIR"))) return env_cache_dir;
if ((env_cache_dir = getenv("DGL_CACHE_DIR"))) return env_cache_dir;
if ((env_cache_dir = getenv("XDG_CACHE_HOME"))) {
return std::string(env_cache_dir) + "/tvm";
return std::string(env_cache_dir) + "/dgl";
}
if ((env_cache_dir = getenv("HOME"))) {
return std::string(env_cache_dir) + "/.cache/tvm";
return std::string(env_cache_dir) + "/.cache/dgl";
}
return ".";
}
......@@ -88,9 +88,9 @@ std::string GetFileBasename(const std::string& file_name) {
std::string GetMetaFilePath(const std::string& file_name) {
size_t pos = file_name.find_last_of(".");
if (pos != std::string::npos) {
return file_name.substr(0, pos) + ".tvm_meta.json";
return file_name.substr(0, pos) + ".dgl_meta.json";
} else {
return file_name + ".tvm_meta.json";
return file_name + ".dgl_meta.json";
}
}
......@@ -122,7 +122,7 @@ void SaveMetaDataToFile(
CHECK(!fs.fail()) << "Cannot open file " << file_name;
dmlc::JSONWriter writer(&fs);
writer.BeginObject();
writer.WriteObjectKeyValue("tvm_version", version);
writer.WriteObjectKeyValue("dgl_version", version);
writer.WriteObjectKeyValue("func_info", fmap);
writer.EndObject();
fs.close();
......@@ -136,11 +136,11 @@ void LoadMetaDataFromFile(
std::string version;
dmlc::JSONReader reader(&fs);
dmlc::JSONObjectReadHelper helper;
helper.DeclareField("tvm_version", &version);
helper.DeclareField("dgl_version", &version);
helper.DeclareField("func_info", fmap);
helper.ReadAllFields(&reader);
fs.close();
}
} // namespace runtime
} // namespace tvm
} // namespace dgl
......@@ -9,7 +9,7 @@
#include <string>
#include "meta_data.h"
namespace tvm {
namespace dgl {
namespace runtime {
/*!
* \brief Get file format from given file name or format argument.
......@@ -20,8 +20,8 @@ std::string GetFileFormat(const std::string& file_name,
const std::string& format);
/*!
* \return the directory in which TVM stores cached files.
* May be set using TVM_CACHE_DIR; defaults to system locations.
* \return the directory in which DGL stores cached files.
* May be set using DGL_CACHE_DIR; defaults to system locations.
*/
std::string GetCacheDir();
......@@ -72,5 +72,5 @@ void LoadMetaDataFromFile(
const std::string& file_name,
std::unordered_map<std::string, FunctionInfo>* fmap);
} // namespace runtime
} // namespace tvm
} // namespace dgl
#endif // DGL_RUNTIME_FILE_UTIL_H_
......@@ -13,13 +13,13 @@
#include <vector>
#include "runtime_base.h"
namespace tvm {
namespace dgl {
namespace runtime {
/*! \brief function information needed by device */
struct FunctionInfo {
std::string name;
std::vector<TVMType> arg_types;
std::vector<DGLType> arg_types;
std::vector<std::string> thread_axis_tags;
void Save(dmlc::JSONWriter *writer) const;
......@@ -28,9 +28,9 @@ struct FunctionInfo {
bool Load(dmlc::Stream *reader);
};
} // namespace runtime
} // namespace tvm
} // namespace dgl
namespace dmlc {
DMLC_DECLARE_TRAITS(has_saveload, ::tvm::runtime::FunctionInfo, true);
DMLC_DECLARE_TRAITS(has_saveload, ::dgl::runtime::FunctionInfo, true);
} // namespace dmlc
#endif // DGL_RUNTIME_META_DATA_H_
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment