registry.py 8.41 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
# pylint: disable=invalid-name, unused-import
19
"""FFI registry to register function and objects."""
20
import sys
21 22
import ctypes

23
from .base import _LIB, check_call, py_str, c_str, string_types, _FFI_MODE, _RUNTIME_ONLY
24 25

try:
26
    # pylint: disable=wrong-import-position,unused-import
27 28
    if _FFI_MODE == "ctypes":
        raise ImportError()
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
    from ._cy3.core import _register_object
    from ._cy3.core import _reg_extension
    from ._cy3.core import convert_to_tvm_func, _get_global_func, PackedFuncBase
except (RuntimeError, ImportError):
    # pylint: disable=wrong-import-position,unused-import
    from ._ctypes.object import _register_object
    from ._ctypes.ndarray import _reg_extension
    from ._ctypes.packed_func import convert_to_tvm_func, _get_global_func, PackedFuncBase


def register_object(type_key=None):
    """register object type.

    Parameters
    ----------
    type_key : str or cls
        The type key of the node

    Examples
48
    --------
49 50 51 52 53 54 55 56
    The following code registers MyObject
    using type key "test.MyObject"

    .. code-block:: python

      @tvm.register_object("test.MyObject")
      class MyObject(Object):
          pass
57
    """
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
    object_name = type_key if isinstance(type_key, str) else type_key.__name__

    def register(cls):
        """internal register function"""
        if hasattr(cls, "_type_index"):
            tindex = cls._type_index
        else:
            tidx = ctypes.c_uint()
            if not _RUNTIME_ONLY:
                check_call(_LIB.TVMObjectTypeKey2Index(
                    c_str(object_name), ctypes.byref(tidx)))
            else:
                # directly skip unknown objects during runtime.
                ret = _LIB.TVMObjectTypeKey2Index(
                    c_str(object_name), ctypes.byref(tidx))
                if ret != 0:
                    return cls
            tindex = tidx.value
        _register_object(tindex, cls)
        return cls

    if isinstance(type_key, str):
        return register

    return register(type_key)


def register_extension(cls, fcreate=None):
    """Register a extension class to TVM.

    After the class is registered, the class will be able
    to directly pass as Function argument generated by TVM.
90

91 92 93 94 95 96 97
    Parameters
    ----------
    cls : class
        The class object to be registered as extension.

    fcreate : function, optional
        The creation function to create a class object given handle value.
98

99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
    Note
    ----
    The registered class is requires one property: _tvm_handle.

    If the registered class is a subclass of NDArray,
    it is required to have a class attribute _array_type_code.
    Otherwise, it is required to have a class attribute _tvm_tcode.

    - ```_tvm_handle``` returns integer represents the address of the handle.
    - ```_tvm_tcode``` or ```_array_type_code``` gives integer represents type
      code of the class.

    Returns
    -------
    cls : class
        The class being registered.

    Example
    -------
    The following code registers user defined class
    MyTensor to be DLTensor compatible.

    .. code-block:: python

       @tvm.register_extension
       class MyTensor(object):
           _tvm_tcode = tvm.TypeCode.ARRAY_HANDLE

           def __init__(self):
               self.handle = _LIB.NewDLTensor()

           @property
           def _tvm_handle(self):
               return self.handle.value
    """
    assert hasattr(cls, "_tvm_tcode")
    if fcreate and cls._tvm_tcode < TypeCode.EXT_BEGIN:
        raise ValueError("Cannot register create when extension tcode is same as buildin")
    _reg_extension(cls, fcreate)
    return cls
139

140

141
def register_func(func_name, f=None, override=False):
142 143 144 145 146 147 148
    """Register global function

    Parameters
    ----------
    func_name : str or function
        The function name

149
    f : function, optional
150 151
        The function to be registered.

152 153 154
    override: boolean optional
        Whether override existing entry.

155 156 157 158
    Returns
    -------
    fregister : function
        Register function if f is not specified.
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175

    Examples
    --------
    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.

    .. code-block:: python

      targs = (10, 10.0, "hello")
      @tvm.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")
176
      assert isinstance(f, tvm.PackedFunc)
177 178
      y = f(*targs)
      assert y == 10
179 180 181 182 183 184 185
    """
    if callable(func_name):
        f = func_name
        func_name = f.__name__

    if not isinstance(func_name, str):
        raise ValueError("expect string function name")
186 187

    ioverride = ctypes.c_int(override)
188 189
    def register(myf):
        """internal register function"""
190
        if not isinstance(myf, PackedFuncBase):
191 192
            myf = convert_to_tvm_func(myf)
        check_call(_LIB.TVMFuncRegisterGlobal(
193
            c_str(func_name), myf.handle, ioverride))
194
        return myf
195
    if f:
196 197
        return register(f)
    return register
198 199


200
def get_global_func(name, allow_missing=False):
201 202 203 204 205 206 207
    """Get a global function by name

    Parameters
    ----------
    name : str
        The name of the global function

208 209 210
    allow_missing : bool
        Whether allow missing function or raise an error.

211 212
    Returns
    -------
213
    func : PackedFunc
214
        The function to be returned, None if function is missing.
215
    """
216
    return _get_global_func(name, allow_missing)
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237


def list_global_func_names():
    """Get list of global functions registered.

    Returns
    -------
    names : list
       List of global functions names.
    """
    plist = ctypes.POINTER(ctypes.c_char_p)()
    size = ctypes.c_uint()

    check_call(_LIB.TVMFuncListGlobalNames(ctypes.byref(size),
                                           ctypes.byref(plist)))
    fnames = []
    for i in range(size.value):
        fnames.append(py_str(plist[i]))
    return fnames


238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
def extract_ext_funcs(finit):
    """
    Extract the extension PackedFuncs from a C module.

    Parameters
    ----------
    finit : ctypes function
        a ctypes that takes signature of TVMExtensionDeclarer

    Returns
    -------
    fdict : dict of str to Function
        The extracted functions
    """
    fdict = {}
    def _list(name, func):
        fdict[name] = func
    myf = convert_to_tvm_func(_list)
    ret = finit(myf.handle)
    _ = myf
    if ret != 0:
        raise RuntimeError("cannot initialize with %s" % finit)
    return fdict


263 264
def _get_api(f):
    flocal = f
265
    flocal.is_global = True
266
    return flocal
267

268

269
def _init_api(namespace, target_module_name=None):
270 271
    """Initialize api for a given module name

272 273 274 275 276
    namespace : str
       The namespace of the source registry

    target_module_name : str
       The target module name if different from namespace
277
    """
278 279 280 281 282 283 284
    target_module_name = (
        target_module_name if target_module_name else namespace)
    if namespace.startswith("tvm."):
        _init_api_prefix(target_module_name, namespace[4:])
    else:
        _init_api_prefix(target_module_name, namespace)

285 286 287

def _init_api_prefix(module_name, prefix):
    module = sys.modules[module_name]
288

289
    for name in list_global_func_names():
290 291 292 293 294
        if not name.startswith(prefix):
            continue

        fname = name[len(prefix)+1:]
        target_module = module
295

296 297
        if fname.find(".") != -1:
            continue
298
        f = get_global_func(name)
299 300 301 302
        ff = _get_api(f)
        ff.__name__ = fname
        ff.__doc__ = ("TVM PackedFunc %s. " % fname)
        setattr(target_module, ff.__name__, ff)