function.pxi 11.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
# 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.

18 19 20 21
import ctypes
import traceback
from cpython cimport Py_INCREF, Py_DECREF
from numbers import Number, Integral
22
from ..base import string_types, py2cerror
23
from ..node_generic import convert_to_node, NodeGeneric
24
from ..runtime_ctypes import TVMType, TVMContext, TVMByteArray
25 26 27 28 29 30 31 32 33 34


cdef void tvm_callback_finalize(void* fhandle):
    local_pyfunc = <object>(fhandle)
    Py_DECREF(local_pyfunc)

cdef int tvm_callback(TVMValue* args,
                      int* type_codes,
                      int num_args,
                      TVMRetValueHandle ret,
35
                      void* fhandle) with gil:
36 37 38 39 40 41 42 43 44 45
    cdef list pyargs
    cdef TVMValue value
    cdef int tcode
    local_pyfunc = <object>(fhandle)
    pyargs = []
    for i in range(num_args):
        value = args[i]
        tcode = type_codes[i]
        if (tcode == kNodeHandle or
            tcode == kFuncHandle or
46
            tcode == kModuleHandle or
47
            tcode == kObject or
48
            tcode > kExtBegin):
49
            CALL(TVMCbArgToReturn(&value, tcode))
50

51 52 53
        if tcode != kArrayHandle:
            pyargs.append(make_ret(value, tcode))
        else:
54
            pyargs.append(c_make_array(value.v_handle, True, False))
55 56 57 58
    try:
        rv = local_pyfunc(*pyargs)
    except Exception:
        msg = traceback.format_exc()
59
        msg = py2cerror(msg)
60 61 62 63 64 65 66
        TVMAPISetLastError(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)
67
        CALL(TVMCFuncSetReturn(ret, &value, &tcode, 1))
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
    return 0


def convert_to_tvm_func(object pyfunc):
    """Convert a python function to TVM function

    Parameters
    ----------
    pyfunc : python function
        The python function to be converted.

    Returns
    -------
    tvmfunc: tvm.Function
        The converted tvm function.
    """
    cdef TVMFunctionHandle chandle
    Py_INCREF(pyfunc)
    CALL(TVMFuncCreateFromCFunc(tvm_callback,
                                <void*>(pyfunc),
                                tvm_callback_finalize,
                                &chandle))
90 91 92
    ret = _CLASS_FUNCTION(None, False)
    (<FunctionBase>ret).chandle = chandle
    return ret
93 94


95 96 97 98
cdef inline int make_arg(object arg,
                         TVMValue* value,
                         int* tcode,
                         list temp_args) except -1:
99
    """Pack arguments into c args tvm call accept"""
100
    cdef unsigned long long ptr
101 102 103 104
    if isinstance(arg, NodeBase):
        value[0].v_handle = (<NodeBase>arg).chandle
        tcode[0] = kNodeHandle
    elif isinstance(arg, NDArrayBase):
105
        value[0].v_handle = (<NDArrayBase>arg).chandle
106 107
        tcode[0] = (kNDArrayContainer if
                    not (<NDArrayBase>arg).c_is_view else kArrayHandle)
108 109
    elif isinstance(arg, _TVM_COMPATS):
        ptr = arg._tvm_handle
110
        value[0].v_handle = (<void*>ptr)
111
        tcode[0] = arg.__class__._tvm_tcode
112
    elif isinstance(arg, (int, long)):
113 114
        value[0].v_int64 = arg
        tcode[0] = kInt
115
    elif isinstance(arg, float):
116 117
        value[0].v_float64 = arg
        tcode[0] = kFloat
118 119 120 121 122
    elif isinstance(arg, str):
        tstr = c_str(arg)
        value[0].v_str = tstr
        tcode[0] = kStr
        temp_args.append(tstr)
123 124 125
    elif arg is None:
        value[0].v_handle = NULL
        tcode[0] = kNull
126 127 128
    elif isinstance(arg, Number):
        value[0].v_float64 = arg
        tcode[0] = kFloat
129 130 131 132 133
    elif isinstance(arg, TVMType):
        tstr = c_str(str(arg))
        value[0].v_str = tstr
        tcode[0] = kStr
        temp_args.append(tstr)
134 135 136 137
    elif isinstance(arg, TVMContext):
        value[0].v_ctx = (<DLContext*>(
            <unsigned long long>ctypes.addressof(arg)))[0]
        tcode[0] = kTVMContext
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
    elif isinstance(arg, bytearray):
        arr = TVMByteArray()
        arr.data = ctypes.cast(
            (ctypes.c_byte * len(arg)).from_buffer(arg),
            ctypes.POINTER(ctypes.c_byte))
        arr.size = len(arg)
        value[0].v_handle = <void*>(
            <unsigned long long>ctypes.addressof(arr))
        tcode[0] = kBytes
        temp_args.append(arr)
    elif isinstance(arg, string_types):
        tstr = c_str(arg)
        value[0].v_str = tstr
        tcode[0] = kStr
        temp_args.append(tstr)
    elif isinstance(arg, (list, tuple, dict, NodeGeneric)):
        arg = convert_to_node(arg)
        value[0].v_handle = (<NodeBase>arg).chandle
        tcode[0] = kNodeHandle
        temp_args.append(arg)
    elif isinstance(arg, _CLASS_MODULE):
        value[0].v_handle = c_handle(arg.handle)
        tcode[0] = kModuleHandle
161 162 163
    elif isinstance(arg, _CLASS_OBJECT):
        value[0].v_handle = c_handle(arg.handle)
        tcode[0] = kObject
164 165 166
    elif isinstance(arg, FunctionBase):
        value[0].v_handle = (<FunctionBase>arg).chandle
        tcode[0] = kFuncHandle
167 168 169
    elif isinstance(arg, ctypes.c_void_p):
        value[0].v_handle = c_handle(arg)
        tcode[0] = kHandle
170 171 172 173 174 175 176
    elif callable(arg):
        arg = convert_to_tvm_func(arg)
        value[0].v_handle = (<FunctionBase>arg).chandle
        tcode[0] = kFuncHandle
        temp_args.append(arg)
    else:
        raise TypeError("Don't know how to handle type %s" % type(arg))
177
    return 0
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198

cdef inline bytearray make_ret_bytes(void* chandle):
    handle = ctypes_handle(chandle)
    arr = ctypes.cast(handle, ctypes.POINTER(TVMByteArray))[0]
    size = arr.size
    res = bytearray(size)
    rptr = (ctypes.c_byte * size).from_buffer(res)
    if not ctypes.memmove(rptr, arr.data, size):
        raise RuntimeError('memmove failed')
    return res

cdef inline object make_ret(TVMValue value, int tcode):
    """convert result to return value."""
    if tcode == kNodeHandle:
        return make_ret_node(value.v_handle)
    elif tcode == kNull:
        return None
    elif tcode == kInt:
        return value.v_int64
    elif tcode == kFloat:
        return value.v_float64
199
    elif tcode == kNDArrayContainer:
200
        return c_make_array(value.v_handle, False, True)
201 202 203 204 205 206
    elif tcode == kStr:
        return py_str(value.v_str)
    elif tcode == kBytes:
        return make_ret_bytes(value.v_handle)
    elif tcode == kHandle:
        return ctypes_handle(value.v_handle)
207 208
    elif tcode == kTVMContext:
        return TVMContext(value.v_ctx.device_type, value.v_ctx.device_id)
209 210 211 212 213 214
    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
215 216
    elif tcode == kObject:
        return _CLASS_OBJECT(ctypes_handle(value.v_handle))
217 218 219 220
    elif tcode in _TVM_EXT_RET:
        return _TVM_EXT_RET[tcode](ctypes_handle(value.v_handle))

    raise ValueError("Unhandled type code %d" % tcode)
221 222


223 224 225 226 227
cdef inline int FuncCall3(void* chandle,
                          tuple args,
                          int nargs,
                          TVMValue* ret_val,
                          int* ret_tcode) except -1:
228 229
    cdef TVMValue[3] values
    cdef int[3] tcodes
230 231 232 233 234
    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],
235 236
                     nargs, ret_val, ret_tcode))
    return 0
237

238 239 240 241
cdef inline int FuncCall(void* chandle,
                         tuple args,
                         TVMValue* ret_val,
                         int* ret_tcode) except -1:
242 243
    cdef int nargs
    nargs = len(args)
244
    if nargs <= 3:
245 246
        FuncCall3(chandle, args, nargs, ret_val, ret_tcode)
        return 0
247 248 249 250 251 252 253 254 255

    cdef vector[TVMValue] 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],
256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
                     nargs, ret_val, ret_tcode))
    return 0


cdef inline int ConstructorCall(void* constructor_handle,
                                int type_code,
                                tuple args,
                                void** handle) except -1:
    """Call contructor of a handle function"""
    cdef TVMValue ret_val
    cdef int ret_tcode
    FuncCall(constructor_handle, args, &ret_val, &ret_tcode)
    assert ret_tcode == type_code
    handle[0] = ret_val.v_handle
    return 0
271 272 273 274 275 276


cdef class FunctionBase:
    cdef TVMFunctionHandle chandle
    cdef int is_global

277
    cdef inline _set_handle(self, handle):
278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307
        if handle is None:
            self.chandle = NULL
        else:
            self.chandle = c_handle(handle)

    property is_global:
        def __get__(self):
            return self.c_is_global != 0

        def __set__(self, value):
            self.c_is_global = value

    property handle:
        def __get__(self):
            if self.chandle == NULL:
                return None
            else:
                return ctypes.cast(<unsigned long long>self.chandle, ctypes.c_void_p)
        def __set__(self, value):
            self._set_handle(value)

    def __init__(self, handle, is_global):
        self._set_handle(handle)
        self.c_is_global = is_global

    def __dealloc__(self):
        if self.is_global == 0:
            CALL(TVMFuncFree(self.chandle))

    def __call__(self, *args):
308 309 310 311
        cdef TVMValue ret_val
        cdef int ret_tcode
        FuncCall(self.chandle, args, &ret_val, &ret_tcode)
        return make_ret(ret_val, ret_tcode)
312

313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
cdef class ObjectBase:
    cdef ObjectHandle chandle

    cdef inline _set_handle(self, handle):
        if handle is None:
            self.chandle = NULL
        else:
            self.chandle = c_handle(handle)

    property handle:
        def __get__(self):
            if self.chandle == NULL:
                return None
            else:
                return ctypes.cast(<unsigned long long>self.chandle, ctypes.c_void_p)
        def __set__(self, value):
            self._set_handle(value)

    def __init__(self, handle):
        self._set_handle(handle)


335 336
_CLASS_FUNCTION = None
_CLASS_MODULE = None
337
_CLASS_OBJECT = None
338 339 340 341 342 343 344 345 346

def _set_class_module(module_class):
    """Initialize the module."""
    global _CLASS_MODULE
    _CLASS_MODULE = module_class

def _set_class_function(func_class):
    global _CLASS_FUNCTION
    _CLASS_FUNCTION = func_class
347 348 349 350

def _set_class_object(obj_class):
    global _CLASS_OBJECT
    _CLASS_OBJECT = obj_class