ndarray.py 11.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
# 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.
17
# pylint: disable=invalid-name, unused-import
18
"""Runtime NDArray api"""
19
from __future__ import absolute_import
20 21

import sys
22 23
import ctypes
import numpy as np
eqy committed
24
from .base import _LIB, check_call, c_array, string_types, _FFI_MODE, c_str
25 26
from .runtime_ctypes import TVMType, TVMContext, TVMArray, TVMArrayHandle
from .runtime_ctypes import TypeCode, tvm_shape_index_t
27

28

29
IMPORT_EXCEPT = RuntimeError if _FFI_MODE == "cython" else ImportError
30

31 32 33 34 35
try:
    # pylint: disable=wrong-import-position
    if _FFI_MODE == "ctypes":
        raise ImportError()
    if sys.version_info >= (3, 0):
36
        from ._cy3.core import _set_class_ndarray, _make_array, _from_dlpack
37
        from ._cy3.core import NDArrayBase as _NDArrayBase
38
        from ._cy3.core import _reg_extension, _reg_ndarray
39
    else:
40
        from ._cy2.core import _set_class_ndarray, _make_array, _from_dlpack
41
        from ._cy2.core import NDArrayBase as _NDArrayBase
42
        from ._cy2.core import _reg_extension, _reg_ndarray
43 44
except IMPORT_EXCEPT:
    # pylint: disable=wrong-import-position
45
    from ._ctypes.ndarray import _set_class_ndarray, _make_array, _from_dlpack
46
    from ._ctypes.ndarray import NDArrayBase as _NDArrayBase
47
    from ._ctypes.ndarray import _reg_extension, _reg_ndarray
48

49

50 51
def context(dev_type, dev_id=0):
    """Construct a TVM context with given device type and id.
52 53 54

    Parameters
    ----------
55 56
    dev_type: int or str
        The device type mask or name of the device.
57 58 59 60

    dev_id : int, optional
        The integer device id

61 62 63 64
    Returns
    -------
    ctx: TVMContext
        The corresponding context.
65

66 67 68 69
    Examples
    --------
    Context can be used to create reflection of context by
    string representation of the device type.
70

71
    .. code-block:: python
72

73 74 75
      assert tvm.context("cpu", 1) == tvm.cpu(1)
      assert tvm.context("gpu", 0) == tvm.gpu(0)
      assert tvm.context("cuda", 0) == tvm.gpu(0)
76
    """
77
    if isinstance(dev_type, string_types):
78
        dev_type = dev_type.split()[0]
79
        if dev_type not in TVMContext.STR2MASK:
80 81 82
            raise ValueError("Unknown device type %s" % dev_type)
        dev_type = TVMContext.STR2MASK[dev_type]
    return TVMContext(dev_type, dev_id)
83

eqy committed
84

85 86 87 88 89 90
def numpyasarray(np_data):
    """Return a TVMArray representation of a numpy array.
    """
    data = np_data
    assert data.flags['C_CONTIGUOUS']
    arr = TVMArray()
91
    shape = c_array(tvm_shape_index_t, data.shape)
92 93 94
    arr.data = data.ctypes.data_as(ctypes.c_void_p)
    arr.shape = shape
    arr.strides = None
95
    arr.dtype = TVMType(np.dtype(data.dtype).name)
96 97
    arr.ndim = data.ndim
    # CPU device
98
    arr.ctx = context(1, 0)
99 100
    return arr, shape

101 102

def empty(shape, dtype="float32", ctx=context(1, 0)):
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
    """Create an empty array given shape and device

    Parameters
    ----------
    shape : tuple of int
        The shape of the array

    dtype : type or str
        The data type of the array.

    ctx : TVMContext
        The context of the array

    Returns
    -------
    arr : tvm.nd.NDArray
        The array tvm supported.
    """
121 122
    shape = c_array(tvm_shape_index_t, shape)
    ndim = ctypes.c_int(len(shape))
123
    handle = TVMArrayHandle()
124
    dtype = TVMType(dtype)
125
    check_call(_LIB.TVMArrayAlloc(
126 127 128 129 130 131 132
        shape, ndim,
        ctypes.c_int(dtype.type_code),
        ctypes.c_int(dtype.bits),
        ctypes.c_int(dtype.lanes),
        ctx.device_type,
        ctx.device_id,
        ctypes.byref(handle)))
133
    return _make_array(handle, False, False)
134

eqy committed
135 136 137 138 139 140 141 142 143 144

def from_dlpack(dltensor):
    """Produce an array from a DLPack tensor without memory copy.
    Retreives the underlying DLPack tensor's pointer to create an array from the
    data. Removes the original DLPack tensor's destructor as now the array is
    responsible for destruction.

    Parameters
    ----------
    dltensor : DLPack tensor
145
        Input DLManagedTensor, can only be consumed once.
eqy committed
146 147 148 149 150 151

    Returns
    -------
    arr: tvm.nd.NDArray
        The array view of the tensor data.
    """
152
    return _from_dlpack(dltensor)
eqy committed
153 154


155
class NDArrayBase(_NDArrayBase):
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
    """A simple Device/CPU Array object in runtime."""
    @property
    def shape(self):
        """Shape of this array"""
        return tuple(self.handle.contents.shape[i] for i in range(self.handle.contents.ndim))

    @property
    def dtype(self):
        """Type of this array"""
        return str(self.handle.contents.dtype)

    @property
    def ctx(self):
        """context of this array"""
        return self.handle.contents.ctx

    @property
    def context(self):
        """context of this array"""
        return self.ctx

177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
    def __hash__(self):
        return ctypes.cast(self.handle, ctypes.c_void_p).value

    def __eq__(self, other):
        return self.same_as(other)

    def __ne__(self, other):
        return not self.__eq__(other)

    def same_as(self, other):
        """Check object identity equality

        Parameters
        ----------
        other : object
            The other object to compare to

        Returns
        -------
        same : bool
            Whether other is same as self.
        """
        if not isinstance(other, NDArrayBase):
            return False
        return self.__hash__() == other.__hash__()

203 204 205 206 207 208 209 210 211 212
    def __setitem__(self, in_slice, value):
        """Set ndarray value"""
        if (not isinstance(in_slice, slice) or
                in_slice.start is not None
                or in_slice.stop is not None):
            raise ValueError('Array only support set from numpy array')
        if isinstance(value, NDArrayBase):
            if value.handle is not self.handle:
                value.copyto(self)
        elif isinstance(value, (np.ndarray, np.generic)):
213
            self.copyfrom(value)
214 215 216
        else:
            raise TypeError('type %s not supported' % str(type(value)))

217
    def copyfrom(self, source_array):
218 219 220 221 222 223
        """Peform an synchronize copy from the array.

        Parameters
        ----------
        source_array : array_like
            The data source we should like to copy from.
224 225 226 227 228

        Returns
        -------
        arr : NDArray
            Reference to self.
229
        """
230 231 232 233
        if isinstance(source_array, NDArrayBase):
            source_array.copyto(self)
            return self

234 235 236 237 238 239
        if not isinstance(source_array, np.ndarray):
            try:
                source_array = np.array(source_array, dtype=self.dtype)
            except:
                raise TypeError('array must be an array_like data,' +
                                'type %s is not supported' % str(type(source_array)))
240 241 242 243 244 245
        t = TVMType(self.dtype)
        shape, dtype = self.shape, self.dtype
        if t.lanes > 1:
            shape = shape + (t.lanes,)
            t.lanes = 1
            dtype = str(t)
246

247 248 249
        if source_array.shape != shape:
            raise ValueError("array shape do not match the shape of NDArray {0} vs {1}".format(
                source_array.shape, shape))
250
        source_array = np.ascontiguousarray(source_array, dtype=dtype)
251 252
        assert source_array.flags['C_CONTIGUOUS']
        data = source_array.ctypes.data_as(ctypes.c_void_p)
253
        nbytes = ctypes.c_size_t(source_array.size * source_array.dtype.itemsize)
254
        check_call(_LIB.TVMArrayCopyFromBytes(self.handle, data, nbytes))
255
        return self
256

257 258 259 260 261 262 263 264
    def __repr__(self):
        res = "<tvm.NDArray shape={0}, {1}>\n".format(self.shape, self.context)
        res += self.asnumpy().__repr__()
        return res

    def __str__(self):
        return str(self.asnumpy())

265 266 267 268 269 270 271 272
    def asnumpy(self):
        """Convert this array to numpy array

        Returns
        -------
        np_arr : numpy.ndarray
            The corresponding numpy array.
        """
273 274 275 276 277 278 279
        t = TVMType(self.dtype)
        shape, dtype = self.shape, self.dtype
        if t.lanes > 1:
            shape = shape + (t.lanes,)
            t.lanes = 1
            dtype = str(t)
        np_arr = np.empty(shape, dtype=dtype)
280 281
        assert np_arr.flags['C_CONTIGUOUS']
        data = np_arr.ctypes.data_as(ctypes.c_void_p)
282
        nbytes = ctypes.c_size_t(np_arr.size * np_arr.dtype.itemsize)
283
        check_call(_LIB.TVMArrayCopyToBytes(self.handle, data, nbytes))
284 285 286 287 288 289 290
        return np_arr

    def copyto(self, target):
        """Copy array to target

        Parameters
        ----------
291
        target : NDArray
292 293 294 295 296 297 298 299 300 301
            The target array to be copied, must have same shape as this array.
        """
        if isinstance(target, TVMContext):
            target = empty(self.shape, self.dtype, target)
        if isinstance(target, NDArrayBase):
            check_call(_LIB.TVMArrayCopyFromTo(
                self.handle, target.handle, None))
        else:
            raise ValueError("Unsupported target type %s" % str(type(target)))
        return target
302

eqy committed
303

304 305
def free_extension_handle(handle, type_code):
    """Free c++ extension type handle
306

307 308 309 310 311 312 313 314 315 316
    Parameters
    ----------
    handle : ctypes.c_void_p
        The handle to the extension type.

    type_code : int
         The tyoe code
    """
    check_call(_LIB.TVMExtTypeFree(handle, ctypes.c_int(type_code)))

317

318 319
def register_extension(cls, fcreate=None):
    """Register a extension class to TVM.
320 321 322 323 324 325 326

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

    Parameters
    ----------
    cls : class
327
        The class object to be registered as extension.
328

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

332 333
    Note
    ----
334 335 336 337 338
    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.
339 340

    - ```_tvm_handle``` returns integer represents the address of the handle.
341 342
    - ```_tvm_tcode``` or ```_array_type_code``` gives integer represents type
      code of the class.
343 344 345 346 347 348 349 350 351 352 353 354 355

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

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

    .. code-block:: python

356
       @tvm.register_extension
357
       class MyTensor(object):
358 359
           _tvm_tcode = tvm.TypeCode.ARRAY_HANDLE

360 361 362 363
           def __init__(self):
               self.handle = _LIB.NewDLTensor()

           @property
364
           def _tvm_handle(self):
365 366
               return self.handle.value
    """
367 368 369 370 371 372 373 374 375
    if issubclass(cls, _NDArrayBase):
        assert fcreate is not None
        assert hasattr(cls, "_array_type_code")
        _reg_ndarray(cls, fcreate)
    else:
        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)
376
    return cls