|
| 1 | +# coding: utf-8 |
| 2 | +# pylint: disable=invalid-name |
| 3 | +""" ctypes library of nnvm and helper functions """ |
| 4 | +from __future__ import absolute_import |
| 5 | + |
| 6 | +import sys |
| 7 | +import ctypes |
| 8 | +import numpy as np |
| 9 | +from . import libinfo |
| 10 | + |
| 11 | +__all__ = ['NNNetError'] |
| 12 | +#---------------------------- |
| 13 | +# library loading |
| 14 | +#---------------------------- |
| 15 | +if sys.version_info[0] == 3: |
| 16 | + string_types = str, |
| 17 | + numeric_types = (float, int, np.float32, np.int32) |
| 18 | + # this function is needed for python3 |
| 19 | + # to convert ctypes.char_p .value back to python str |
| 20 | + py_str = lambda x: x.decode('utf-8') |
| 21 | +else: |
| 22 | + string_types = basestring, |
| 23 | + numeric_types = (float, int, long, np.float32, np.int32) |
| 24 | + py_str = lambda x: x |
| 25 | + |
| 26 | + |
| 27 | +class NNVMError(Exception): |
| 28 | + """Error that will be throwed by all nnvm functions""" |
| 29 | + pass |
| 30 | + |
| 31 | +def _load_lib(): |
| 32 | + """Load libary by searching possible path.""" |
| 33 | + lib_path = libinfo.find_lib_path() |
| 34 | + lib = ctypes.cdll.LoadLibrary(lib_path[0]) |
| 35 | + # DMatrix functions |
| 36 | + lib.NNGetLastError.restype = ctypes.c_char_p |
| 37 | + return lib |
| 38 | + |
| 39 | +# version number |
| 40 | +__version__ = libinfo.__version__ |
| 41 | +# library instance of nnvm |
| 42 | +_LIB = _load_lib() |
| 43 | + |
| 44 | +# type definitions |
| 45 | +nn_uint = ctypes.c_uint |
| 46 | +SymbolCreatorHandle = ctypes.c_void_p |
| 47 | +SymbolHandle = ctypes.c_void_p |
| 48 | +GraphHandle = ctypes.c_void_p |
| 49 | + |
| 50 | +#---------------------------- |
| 51 | +# helper function definition |
| 52 | +#---------------------------- |
| 53 | +def check_call(ret): |
| 54 | + """Check the return value of C API call |
| 55 | +
|
| 56 | + This function will raise exception when error occurs. |
| 57 | + Wrap every API call with this function |
| 58 | +
|
| 59 | + Parameters |
| 60 | + ---------- |
| 61 | + ret : int |
| 62 | + return value from API calls |
| 63 | + """ |
| 64 | + if ret != 0: |
| 65 | + raise NNVMError(py_str(_LIB.NNGetLastError())) |
| 66 | + |
| 67 | +def c_str(string): |
| 68 | + """Create ctypes char * from a python string |
| 69 | + Parameters |
| 70 | + ---------- |
| 71 | + string : string type |
| 72 | + python string |
| 73 | +
|
| 74 | + Returns |
| 75 | + ------- |
| 76 | + str : c_char_p |
| 77 | + A char pointer that can be passed to C API |
| 78 | + """ |
| 79 | + return ctypes.c_char_p(string.encode('utf-8')) |
| 80 | + |
| 81 | + |
| 82 | +def c_array(ctype, values): |
| 83 | + """Create ctypes array from a python array |
| 84 | +
|
| 85 | + Parameters |
| 86 | + ---------- |
| 87 | + ctype : ctypes data type |
| 88 | + data type of the array we want to convert to |
| 89 | +
|
| 90 | + values : tuple or list |
| 91 | + data content |
| 92 | +
|
| 93 | + Returns |
| 94 | + ------- |
| 95 | + out : ctypes array |
| 96 | + Created ctypes array |
| 97 | + """ |
| 98 | + return (ctype * len(values))(*values) |
| 99 | + |
| 100 | +def ctypes2buffer(cptr, length): |
| 101 | + """Convert ctypes pointer to buffer type. |
| 102 | +
|
| 103 | + Parameters |
| 104 | + ---------- |
| 105 | + cptr : ctypes.POINTER(ctypes.c_char) |
| 106 | + pointer to the raw memory region |
| 107 | + length : int |
| 108 | + the length of the buffer |
| 109 | +
|
| 110 | + Returns |
| 111 | + ------- |
| 112 | + buffer : bytearray |
| 113 | + The raw byte memory buffer |
| 114 | + """ |
| 115 | + if not isinstance(cptr, ctypes.POINTER(ctypes.c_char)): |
| 116 | + raise TypeError('expected char pointer') |
| 117 | + res = bytearray(length) |
| 118 | + rptr = (ctypes.c_char * length).from_buffer(res) |
| 119 | + if not ctypes.memmove(rptr, cptr, length): |
| 120 | + raise RuntimeError('memmove failed') |
| 121 | + return res |
| 122 | + |
| 123 | +def ctypes2numpy_shared(cptr, shape): |
| 124 | + """Convert a ctypes pointer to a numpy array |
| 125 | +
|
| 126 | + The result numpy array shares the memory with the pointer |
| 127 | +
|
| 128 | + Parameters |
| 129 | + ---------- |
| 130 | + cptr : ctypes.POINTER(mx_float) |
| 131 | + pointer to the memory region |
| 132 | +
|
| 133 | + shape : tuple |
| 134 | + shape of target ndarray |
| 135 | +
|
| 136 | + Returns |
| 137 | + ------- |
| 138 | + out : numpy_array |
| 139 | + A numpy array : numpy array |
| 140 | + """ |
| 141 | + if not isinstance(cptr, ctypes.POINTER(mx_float)): |
| 142 | + raise RuntimeError('expected float pointer') |
| 143 | + size = 1 |
| 144 | + for s in shape: |
| 145 | + size *= s |
| 146 | + dbuffer = (mx_float * size).from_address(ctypes.addressof(cptr.contents)) |
| 147 | + return np.frombuffer(dbuffer, dtype=np.float32).reshape(shape) |
| 148 | + |
| 149 | + |
| 150 | +def ctypes2docstring(num_args, arg_names, arg_types, arg_descs, remove_dup=True): |
| 151 | + """Convert ctypes returned doc string information into parameters docstring. |
| 152 | +
|
| 153 | + num_args : nn_uint |
| 154 | + Number of arguments. |
| 155 | +
|
| 156 | + arg_names : ctypes.POINTER(ctypes.c_char_p) |
| 157 | + Argument names. |
| 158 | +
|
| 159 | + arg_types : ctypes.POINTER(ctypes.c_char_p) |
| 160 | + Argument type information. |
| 161 | +
|
| 162 | + arg_descs : ctypes.POINTER(ctypes.c_char_p) |
| 163 | + Argument description information. |
| 164 | +
|
| 165 | + remove_dup : boolean, optional |
| 166 | + Whether remove duplication or not. |
| 167 | +
|
| 168 | + Returns |
| 169 | + ------- |
| 170 | + docstr : str |
| 171 | + Python docstring of parameter sections. |
| 172 | + """ |
| 173 | + param_keys = set() |
| 174 | + param_str = [] |
| 175 | + for i in range(num_args.value): |
| 176 | + key = py_str(arg_names[i]) |
| 177 | + if key in param_keys and remove_dup: |
| 178 | + continue |
| 179 | + param_keys.add(key) |
| 180 | + type_info = py_str(arg_types[i]) |
| 181 | + ret = '%s : %s' % (key, type_info) |
| 182 | + if len(arg_descs[i]) != 0: |
| 183 | + ret += '\n ' + py_str(arg_descs[i]) |
| 184 | + param_str.append(ret) |
| 185 | + doc_str = ('Parameters\n' + |
| 186 | + '----------\n' + |
| 187 | + '%s\n') |
| 188 | + doc_str = doc_str % ('\n'.join(param_str)) |
| 189 | + return doc_str |
0 commit comments