• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Copyright 2022-2023 Huawei Technologies Co., Ltd
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14# ============================================================================
15"""
16Tensor API.
17"""
18from __future__ import absolute_import
19from enum import Enum
20
21import numpy
22
23from mindspore_lite.lib import _c_lite_wrapper
24from mindspore_lite._checkparam import check_tensor_input_param, check_isinstance
25
26__all__ = ['TensorMeta', 'DataType', 'Format', 'Tensor']
27
28
29class TensorMeta:
30    """
31    The `TensorMeta` class defines a TensorInfo in MindSpore Lite.
32
33    Args:
34        tensor(): The info to be stored in a new TensorMeta.
35    """
36
37    def __init__(self):
38        self.name = ""
39        self.dtype = DataType.UNKNOWN
40        self.shape = []
41        self.format = Format.DEFAULT
42        self.element_num = 0
43        self.data_size = 0
44
45    def __str__(self):
46        res = f"name: {self.name},\n" \
47              f"dtype: {self.dtype},\n" \
48              f"shape: {self.shape},\n" \
49              f"format: {self.format},\n" \
50              f"element_num: {self.element_num},\n" \
51              f"data_size: {self.data_size}."
52        return res
53
54
55class DataType(Enum):
56    """
57    The `DataType` class defines the data type of the Tensor in MindSpore Lite.
58
59    Currently, the following 'DataType' are supported:
60
61    ===========================  ==================================================================
62    Definition                    Description
63    ===========================  ==================================================================
64    `DataType.UNKNOWN`           No matching any of the following known types.
65    `DataType.BOOL`              Boolean `True` or `False` .
66    `DataType.INT8`              8-bit integer.
67    `DataType.INT16`             16-bit integer.
68    `DataType.INT32`             32-bit integer.
69    `DataType.INT64`             64-bit integer.
70    `DataType.UINT8`             unsigned 8-bit integer.
71    `DataType.UINT16`            unsigned 16-bit integer.
72    `DataType.UINT32`            unsigned 32-bit integer.
73    `DataType.UINT64`            unsigned 64-bit integer.
74    `DataType.FLOAT16`           16-bit floating-point number.
75    `DataType.FLOAT32`           32-bit floating-point number.
76    `DataType.FLOAT64`           64-bit floating-point number.
77    `DataType.INVALID`           The maximum threshold value of DataType to prevent invalid types.
78    ===========================  ==================================================================
79
80    Examples:
81        >>> # Method 1: Import mindspore_lite package
82        >>> import mindspore_lite as mslite
83        >>> print(mslite.DataType.FLOAT32)
84        DataType.FLOAT32
85        >>> # Method 2: from mindspore_lite package import DataType
86        >>> from mindspore_lite import DataType
87        >>> print(DataType.FLOAT32)
88        DataType.FLOAT32
89    """
90
91    UNKNOWN = 0
92    BOOL = 30
93    INT8 = 32
94    INT16 = 33
95    INT32 = 34
96    INT64 = 35
97    UINT8 = 37
98    UINT16 = 38
99    UINT32 = 39
100    UINT64 = 40
101    FLOAT16 = 42
102    FLOAT32 = 43
103    FLOAT64 = 44
104    INVALID = 2147483647  # INT32_MAX
105
106
107class Format(Enum):
108    """
109    The `Format` class defines the format of the Tensor in MindSpore Lite.
110
111    Currently, the following 'Format' are supported:
112
113    ===========================  ===================================================================================
114    Definition                    Description
115    ===========================  ===================================================================================
116    `Format.DEFAULT`             default format.
117    `Format.NCHW`                Store Tensor data in the order of batch N, channel C, height H and width W.
118    `Format.NHWC`                Store Tensor data in the order of batch N, height H, width W and channel C.
119    `Format.NHWC4`               C-axis 4-byte aligned `Format.NHWC` .
120    `Format.HWKC`                Store Tensor data in the order of height H, width W, kernel num K and channel C.
121    `Format.HWCK`                Store Tensor data in the order of height H, width W, channel C and kernel num K.
122    `Format.KCHW`                Store Tensor data in the order of kernel num K, channel C, height H and width W.
123    `Format.CKHW`                Store Tensor data in the order of channel C, kernel num K, height H and width W.
124    `Format.KHWC`                Store Tensor data in the order of kernel num K, height H, width W and channel C.
125    `Format.CHWK`                Store Tensor data in the order of channel C, height H, width W and kernel num K.
126    `Format.HW`                  Store Tensor data in the order of height H and width W.
127    `Format.HW4`                 w-axis 4-byte aligned `Format.HW` .
128    `Format.NC`                  Store Tensor data in the order of batch N and channel C.
129    `Format.NC4`                 C-axis 4-byte aligned `Format.NC` .
130    `Format.NC4HW4`              C-axis 4-byte aligned and W-axis 4-byte aligned `Format.NCHW` .
131    `Format.NCDHW`               Store Tensor data in the order of batch N, channel C, depth D, height H and width W.
132    `Format.NWC`                 Store Tensor data in the order of batch N, width W and channel C.
133    `Format.NCW`                 Store Tensor data in the order of batch N, channel C and width W.
134    `Format.NDHWC`               Store Tensor data in the order of batch N, depth D, height H, width W and channel C.
135    `Format.NC8HW8`              C-axis 8-byte aligned and W-axis 8-byte aligned `Format.NCHW` .
136    ===========================  ===================================================================================
137
138    Examples:
139        >>> # Method 1: Import mindspore_lite package
140        >>> import mindspore_lite as mslite
141        >>> print(mslite.Format.NHWC)
142        Format.NHWC
143        >>> # Method 2: from mindspore_lite package import Format
144        >>> from mindspore_lite import Format
145        >>> print(Format.NHWC)
146        Format.NHWC
147    """
148
149    DEFAULT = -1
150    NCHW = 0
151    NHWC = 1
152    NHWC4 = 2
153    HWKC = 3
154    HWCK = 4
155    KCHW = 5
156    CKHW = 6
157    KHWC = 7
158    CHWK = 8
159    HW = 9
160    HW4 = 10
161    NC = 11
162    NC4 = 12
163    NC4HW4 = 13
164    NCDHW = 15
165    NWC = 16
166    NCW = 17
167    NDHWC = 18
168    NC8HW8 = 19
169
170
171data_type_py_cxx_map = {
172    DataType.UNKNOWN: _c_lite_wrapper.DataType.kTypeUnknown,
173    DataType.BOOL: _c_lite_wrapper.DataType.kNumberTypeBool,
174    DataType.INT8: _c_lite_wrapper.DataType.kNumberTypeInt8,
175    DataType.INT16: _c_lite_wrapper.DataType.kNumberTypeInt16,
176    DataType.INT32: _c_lite_wrapper.DataType.kNumberTypeInt32,
177    DataType.INT64: _c_lite_wrapper.DataType.kNumberTypeInt64,
178    DataType.UINT8: _c_lite_wrapper.DataType.kNumberTypeUInt8,
179    DataType.UINT16: _c_lite_wrapper.DataType.kNumberTypeUInt16,
180    DataType.UINT32: _c_lite_wrapper.DataType.kNumberTypeUInt32,
181    DataType.UINT64: _c_lite_wrapper.DataType.kNumberTypeUInt64,
182    DataType.FLOAT16: _c_lite_wrapper.DataType.kNumberTypeFloat16,
183    DataType.FLOAT32: _c_lite_wrapper.DataType.kNumberTypeFloat32,
184    DataType.FLOAT64: _c_lite_wrapper.DataType.kNumberTypeFloat64,
185    DataType.INVALID: _c_lite_wrapper.DataType.kInvalidType,
186}
187
188data_type_cxx_py_map = {
189    _c_lite_wrapper.DataType.kTypeUnknown: DataType.UNKNOWN,
190    _c_lite_wrapper.DataType.kNumberTypeBool: DataType.BOOL,
191    _c_lite_wrapper.DataType.kNumberTypeInt8: DataType.INT8,
192    _c_lite_wrapper.DataType.kNumberTypeInt16: DataType.INT16,
193    _c_lite_wrapper.DataType.kNumberTypeInt32: DataType.INT32,
194    _c_lite_wrapper.DataType.kNumberTypeInt64: DataType.INT64,
195    _c_lite_wrapper.DataType.kNumberTypeUInt8: DataType.UINT8,
196    _c_lite_wrapper.DataType.kNumberTypeUInt16: DataType.UINT16,
197    _c_lite_wrapper.DataType.kNumberTypeUInt32: DataType.UINT32,
198    _c_lite_wrapper.DataType.kNumberTypeUInt64: DataType.UINT64,
199    _c_lite_wrapper.DataType.kNumberTypeFloat16: DataType.FLOAT16,
200    _c_lite_wrapper.DataType.kNumberTypeFloat32: DataType.FLOAT32,
201    _c_lite_wrapper.DataType.kNumberTypeFloat64: DataType.FLOAT64,
202    _c_lite_wrapper.DataType.kInvalidType: DataType.INVALID,
203}
204
205numpy_data_type_map = {
206    numpy.bool_: DataType.BOOL,
207    numpy.int8: DataType.INT8,
208    numpy.int16: DataType.INT16,
209    numpy.int32: DataType.INT32,
210    numpy.int64: DataType.INT64,
211    numpy.uint8: DataType.UINT8,
212    numpy.uint16: DataType.UINT16,
213    numpy.uint32: DataType.UINT32,
214    numpy.uint64: DataType.UINT64,
215    numpy.float16: DataType.FLOAT16,
216    numpy.float32: DataType.FLOAT32,
217    numpy.float64: DataType.FLOAT64,
218}
219
220ms_to_numpy_data_type_map = {
221    DataType.BOOL: numpy.bool_,
222    DataType.INT8: numpy.int8,
223    DataType.INT16: numpy.int16,
224    DataType.INT32: numpy.int32,
225    DataType.INT64: numpy.int64,
226    DataType.UINT8: numpy.uint8,
227    DataType.UINT16: numpy.uint16,
228    DataType.UINT32: numpy.uint32,
229    DataType.UINT64: numpy.uint64,
230    DataType.FLOAT16: numpy.float16,
231    DataType.FLOAT32: numpy.float32,
232    DataType.FLOAT64: numpy.float64,
233}
234
235format_py_cxx_map = {
236    Format.DEFAULT: _c_lite_wrapper.Format.DEFAULT_FORMAT,
237    Format.NCHW: _c_lite_wrapper.Format.NCHW,
238    Format.NHWC: _c_lite_wrapper.Format.NHWC,
239    Format.NHWC4: _c_lite_wrapper.Format.NHWC4,
240    Format.HWKC: _c_lite_wrapper.Format.HWKC,
241    Format.HWCK: _c_lite_wrapper.Format.HWCK,
242    Format.KCHW: _c_lite_wrapper.Format.KCHW,
243    Format.CKHW: _c_lite_wrapper.Format.CKHW,
244    Format.KHWC: _c_lite_wrapper.Format.KHWC,
245    Format.CHWK: _c_lite_wrapper.Format.CHWK,
246    Format.HW: _c_lite_wrapper.Format.HW,
247    Format.HW4: _c_lite_wrapper.Format.HW4,
248    Format.NC: _c_lite_wrapper.Format.NC,
249    Format.NC4: _c_lite_wrapper.Format.NC4,
250    Format.NC4HW4: _c_lite_wrapper.Format.NC4HW4,
251    Format.NCDHW: _c_lite_wrapper.Format.NCDHW,
252    Format.NWC: _c_lite_wrapper.Format.NWC,
253    Format.NCW: _c_lite_wrapper.Format.NCW,
254    Format.NDHWC: _c_lite_wrapper.Format.NDHWC,
255    Format.NC8HW8: _c_lite_wrapper.Format.NC8HW8,
256}
257
258format_cxx_py_map = {
259    _c_lite_wrapper.Format.DEFAULT_FORMAT: Format.DEFAULT,
260    _c_lite_wrapper.Format.NCHW: Format.NCHW,
261    _c_lite_wrapper.Format.NHWC: Format.NHWC,
262    _c_lite_wrapper.Format.NHWC4: Format.NHWC4,
263    _c_lite_wrapper.Format.HWKC: Format.HWKC,
264    _c_lite_wrapper.Format.HWCK: Format.HWCK,
265    _c_lite_wrapper.Format.KCHW: Format.KCHW,
266    _c_lite_wrapper.Format.CKHW: Format.CKHW,
267    _c_lite_wrapper.Format.KHWC: Format.KHWC,
268    _c_lite_wrapper.Format.CHWK: Format.CHWK,
269    _c_lite_wrapper.Format.HW: Format.HW,
270    _c_lite_wrapper.Format.HW4: Format.HW4,
271    _c_lite_wrapper.Format.NC: Format.NC,
272    _c_lite_wrapper.Format.NC4: Format.NC4,
273    _c_lite_wrapper.Format.NC4HW4: Format.NC4HW4,
274    _c_lite_wrapper.Format.NCDHW: Format.NCDHW,
275    _c_lite_wrapper.Format.NWC: Format.NWC,
276    _c_lite_wrapper.Format.NCW: Format.NCW,
277    _c_lite_wrapper.Format.NDHWC: Format.NDHWC,
278    _c_lite_wrapper.Format.NC8HW8: Format.NC8HW8,
279}
280
281
282class Tensor:
283    """
284    The `Tensor` class defines a Tensor in MindSpore Lite.
285
286    Args:
287        tensor(Tensor, optional): The data to be stored in a new Tensor. It can be from another Tensor.
288            Default: ``None``.
289        shape(list, optional): The shape of the Tensor.
290            Default: ``None``.
291        dtype(DataType, optional): The dtype of the Tensor.
292            Default: ``None``.
293        device(str, optional): The device type of the Tensor. It can be ``"ascend"`` or
294            ``"ascend:device_id"`` or ``None``. ``device_id`` indicates the device number, which can be ``0`` ,
295            ``1`` , ``2`` , ``3`` , ``4`` , ``5`` , ``6`` , or ``7``. If ``device`` is ``None``, the tensor will be
296            initialized at CPU. Default: ``None``.
297
298    Raises:
299        TypeError: `tensor` is neither a Tensor nor ``None``.
300
301    Examples:
302        >>> import mindspore_lite as mslite
303        >>> tensor = mslite.Tensor()
304        >>> tensor.name = "tensor1"
305        >>> print(tensor.name)
306        tensor1
307        >>> tensor.dtype = mslite.DataType.FLOAT32
308        >>> print(tensor.dtype)
309        DataType.FLOAT32
310        >>> tensor.shape = [1, 3, 2, 2]
311        >>> print(tensor.shape)
312        [1, 3, 2, 2]
313        >>> tensor.format = mslite.Format.NCHW
314        >>> print(tensor.format)
315        Format.NCHW
316        >>> print(tensor.element_num)
317        12
318        >>> print(tensor.data_size)
319        48
320        >>> print(tensor)
321        name: tensor1,
322        dtype: DataType.FLOAT32,
323        shape: [1, 3, 2, 2],
324        format: Format.NCHW,
325        element_num: 12,
326        data_size: 48.
327        device: None:-1.
328    """
329
330    def __init__(self, tensor=None, shape=None, dtype=None, device=None):
331        # check shape, dtype and device
332        check_tensor_input_param(shape, device)
333        device_type = ""
334        device_id = -1
335        if device is not None:
336            device_type = device.split(":")[0]
337            if len(device.split(":")) == 2:
338                device_id = int(device.split(":")[1])
339        check_isinstance("dtype", dtype, DataType, True)
340        if tensor is not None:
341            # use tensor to init tensor
342            if isinstance(tensor, _c_lite_wrapper.TensorBind):
343                self._tensor = tensor
344            elif isinstance(tensor, Tensor):
345                tensor_shape = tensor.shape
346                if shape is not None and list(shape) != list(tensor_shape):
347                    raise TypeError(
348                        f"user set shape is not equal numpy shape, user's shape: {shape}, "
349                        f"tensor shape is: {tensor_shape}.")
350                tensor_dtype = tensor.dtype
351                if dtype is not None and tensor_dtype != dtype:
352                    raise TypeError(
353                        f"user set dtype is not equal tensor dtype, user's dtype: {dtype}, "
354                        f"tensor dtype is: {tensor_dtype}.")
355                numpy_data = tensor.get_data_to_numpy()
356                self._tensor = _c_lite_wrapper.create_tensor_by_numpy(numpy_data, device_type, device_id)
357            # use numpy to init tensor
358            elif isinstance(tensor, numpy.ndarray):
359                if not tensor.flags['FORC']:
360                    tensor = numpy.ascontiguousarray(tensor)
361                numpy_shape = tensor.shape
362                numpy_dtype = tensor.dtype
363                if numpy_dtype.type not in numpy_data_type_map:
364                    raise TypeError(f"Unsupported numpy dtype value {numpy_dtype}")
365                ms_dtype = numpy_data_type_map.get(numpy_dtype.type)
366                if shape is not None and list(shape) != list(numpy_shape):
367                    raise TypeError(
368                        f"user set shape is not equal numpy shape, user shape: {shape}, "
369                        f"numpy shape is: {numpy_shape}.")
370                if dtype is not None and ms_dtype != dtype:
371                    raise TypeError(
372                        f"user set dtype is not equal numpy dtype, user dtype: {dtype}, "
373                        f"numpy dtype is: {numpy_dtype}.")
374                self._tensor = _c_lite_wrapper.create_tensor_by_numpy(tensor, device_type, device_id)
375            else:
376                raise TypeError(
377                    f"tensor must be MindSpore Lite's Tensor._tensor or numpy ndarray, but got {type(tensor)}.")
378        else:
379            if dtype is not None and shape is not None:
380                self._tensor = _c_lite_wrapper.create_tensor(data_type_py_cxx_map.get(dtype), shape, device_type,
381                                                             device_id)
382            else:
383                self._tensor = _c_lite_wrapper.create_tensor(data_type_py_cxx_map.get(DataType.FLOAT32), (), "", -1)
384
385    def __str__(self):
386        res = f"name: {self.name},\n" \
387              f"dtype: {self.dtype},\n" \
388              f"shape: {self.shape},\n" \
389              f"format: {self.format},\n" \
390              f"element_num: {self.element_num},\n" \
391              f"data_size: {self.data_size}.\n" \
392              f"device: {self.device}."
393        return res
394
395    @property
396    def data_size(self):
397        """
398        Get the data size of the Tensor.
399
400        Data size of the Tensor = the element num of the Tensor * size of unit data type of the Tensor.
401
402        Returns:
403            int, the data size of the Tensor data.
404        """
405        return self._tensor.get_data_size()
406
407    @property
408    def dtype(self):
409        """
410        Get the data type of the Tensor.
411
412        Returns:
413            DataType, the data type of the Tensor.
414        """
415        return data_type_cxx_py_map.get(self._tensor.get_data_type())
416
417    @dtype.setter
418    def dtype(self, dtype):
419        """
420        Set data type for the Tensor.
421
422        Args:
423            dtype (DataType): The data type of the Tensor. For details, see
424                `DataType <https://mindspore.cn/lite/api/en/master/mindspore_lite/mindspore_lite.DataType.html>`_ .
425
426        Raises:
427            TypeError: `dtype` is not a DataType.
428        """
429        if not isinstance(dtype, DataType):
430            raise TypeError(f"dtype must be DataType, but got {type(dtype)}.")
431        self._tensor.set_data_type(data_type_py_cxx_map.get(dtype))
432
433    @property
434    def element_num(self):
435        """
436        Get the element num of the Tensor.
437
438        Returns:
439            int, the element num of the Tensor data.
440        """
441        return self._tensor.get_element_num()
442
443    @property
444    def format(self):
445        """
446        Get the format of the Tensor.
447
448        Returns:
449            Format, the format of the Tensor.
450        """
451        return format_cxx_py_map.get(self._tensor.get_format())
452
453    @format.setter
454    def format(self, tensor_format):
455        """
456        Set format of the Tensor.
457
458        Args:
459            tensor_format (Format): The format of the Tensor. For details, see
460                `Format <https://mindspore.cn/lite/api/en/master/mindspore_lite/mindspore_lite.Format.html>`_ .
461
462        Raises:
463            TypeError: `tensor_format` is not a Format.
464        """
465        if not isinstance(tensor_format, Format):
466            raise TypeError(f"format must be Format, but got {type(tensor_format)}.")
467        self._tensor.set_format(format_py_cxx_map.get(tensor_format))
468
469    @property
470    def name(self):
471        """
472        Get the name of the Tensor.
473
474        Returns:
475            str, the name of the Tensor.
476        """
477        return self._tensor.get_tensor_name()
478
479    @name.setter
480    def name(self, name):
481        """
482        Set the name of the Tensor.
483
484        Args:
485            name (str): The name of the Tensor.
486
487        Raises:
488            TypeError: `name` is not a str.
489        """
490        if not isinstance(name, str):
491            raise TypeError(f"name must be str, but got {type(name)}.")
492        self._tensor.set_tensor_name(name)
493
494    @property
495    def shape(self):
496        """
497        Get the shape of the Tensor.
498
499        Returns:
500            list[int], the shape of the Tensor.
501        """
502        return self._tensor.get_shape()
503
504    @shape.setter
505    def shape(self, shape):
506        """
507        Set shape for the Tensor.
508
509        Args:
510            shape (list[int]): The shape of the Tensor.
511
512        Raises:
513            TypeError: `shape` is not a list.
514            TypeError: `shape` is a list, but the elements is not int.
515        """
516        if not isinstance(shape, (list, tuple)):
517            raise TypeError(f"shape must be list or tuple, but got {type(shape)}.")
518        for i, element in enumerate(shape):
519            if not isinstance(element, int):
520                raise TypeError(f"shape element must be int, but got {type(element)} at index {i}.")
521        self._tensor.set_shape(shape)
522
523    def get_data_to_numpy(self):
524        """
525        Get the data from the Tensor to the numpy object.
526
527        Returns:
528            numpy.ndarray, the numpy object from Tensor data.
529
530        Examples:
531            >>> import mindspore_lite as mslite
532            >>> import numpy as np
533            >>> tensor = mslite.Tensor()
534            >>> tensor.shape = [1, 3, 2, 2]
535            >>> tensor.dtype = mslite.DataType.FLOAT32
536            >>> in_data = np.arange(1 * 3 * 2 * 2, dtype=np.float32)
537            >>> tensor.set_data_from_numpy(in_data)
538            >>> data = tensor.get_data_to_numpy()
539            >>> print(data)
540            [[[[ 0.  1.]
541               [ 2.  3.]]
542              [[ 4.  5.]
543               [ 6.  7.]]
544              [[ 8.  9.]
545               [ 10. 11.]]]]
546        """
547        return self._tensor.get_data_to_numpy()
548
549    def set_data_from_numpy(self, numpy_obj):
550        """
551        Set the data for the Tensor from the numpy object.
552
553        Args:
554            numpy_obj(numpy.ndarray): the numpy object.
555
556        Raises:
557            TypeError: `numpy_obj` is not a numpy.ndarray.
558            RuntimeError: The data type of `numpy_obj` is not equivalent to the data type of the Tensor.
559            RuntimeError: The data size of `numpy_obj` is not equal to the data size of the Tensor.
560
561        Examples:
562            >>> # 1. set Tensor data which is from file
563            >>> import mindspore_lite as mslite
564            >>> import numpy as np
565            >>> tensor = mslite.Tensor()
566            >>> tensor.shape = [1, 3, 224, 224]
567            >>> tensor.dtype = mslite.DataType.FLOAT32
568            >>> in_data = np.fromfile("input.bin", dtype=np.float32)
569            >>> tensor.set_data_from_numpy(in_data)
570            >>> print(tensor)
571            name: ,
572            dtype: DataType.FLOAT32,
573            shape: [1, 3, 224, 224],
574            format: Format.NCHW,
575            element_num: 150528,
576            data_size: 602112.
577            >>> # 2. set Tensor data which is numpy arange
578            >>> import mindspore_lite as mslite
579            >>> import numpy as np
580            >>> tensor = mslite.Tensor()
581            >>> tensor.shape = [1, 3, 2, 2]
582            >>> tensor.dtype = mslite.DataType.FLOAT32
583            >>> in_data = np.arange(1 * 3 * 2 * 2, dtype=np.float32)
584            >>> tensor.set_data_from_numpy(in_data)
585            >>> print(tensor)
586            name: ,
587            dtype: DataType.FLOAT32,
588            shape: [1, 3, 2, 2],
589            format: Format.NCHW,
590            element_num: 12,
591            data_size: 48.
592        """
593        if not isinstance(numpy_obj, numpy.ndarray):
594            raise TypeError(f"numpy_obj must be numpy.ndarray, but got {type(numpy_obj)}.")
595        if not numpy_obj.flags['FORC']:
596            numpy_obj = numpy.ascontiguousarray(numpy_obj)
597        if numpy_obj.dtype.type not in numpy_data_type_map:
598            raise TypeError(f"Unsupported numpy dtype value {numpy_obj.dtype}")
599        if numpy_data_type_map.get(numpy_obj.dtype.type) != self.dtype:
600            raise RuntimeError(
601                f"data type not equal! Numpy type: {numpy_obj.dtype.type}, Tensor type: {self.dtype}")
602        if numpy_obj.nbytes != self.data_size:
603            raise RuntimeError(
604                f"data size not equal! Numpy size: {numpy_obj.nbytes}, Tensor size: {self.data_size}")
605        self._tensor.set_data_from_numpy(numpy_obj)
606
607    @property
608    def device(self):
609        """
610        Get the device type of the Tensor.
611
612        Returns:
613            str, the device type of the Tensor.
614        """
615        return self._tensor.get_tensor_device_type()
616