text
stringlengths
81
112k
Returns ctype arrays for keys and values(converted to strings) in a dictionary def _ctype_dict(param_dict): """ Returns ctype arrays for keys and values(converted to strings) in a dictionary """ assert(isinstance(param_dict, dict)), \ "unexpected type for param_dict: " + str(type(param_dict)) c_keys = c_array(ctypes.c_char_p, [c_str(k) for k in param_dict.keys()]) c_vals = c_array(ctypes.c_char_p, [c_str(str(v)) for v in param_dict.values()]) return (c_keys, c_vals)
A wrapper for the user-defined handle. def _updater_wrapper(updater): """A wrapper for the user-defined handle.""" def updater_handle(key, lhs_handle, rhs_handle, _): """ ctypes function """ lhs = _ndarray_cls(NDArrayHandle(lhs_handle)) rhs = _ndarray_cls(NDArrayHandle(rhs_handle)) updater(key, lhs, rhs) return updater_handle
Creates a new KVStore. For single machine training, there are two commonly used types: ``local``: Copies all gradients to CPU memory and updates weights there. ``device``: Aggregates gradients and updates weights on GPUs. With this setting, the KVStore also attempts to use GPU peer-to-peer communication, potentially accelerating the communication. For distributed training, KVStore also supports a number of types: ``dist_sync``: Behaves similarly to ``local`` but with one major difference. With ``dist_sync``, batch-size now means the batch size used on each machine. So if there are ``n`` machines and we use batch size ``b``, then ``dist_sync`` behaves like ``local`` with batch size ``n * b``. ``dist_device_sync``: Identical to ``dist_sync`` with the difference similar to ``device`` vs ``local``. ``dist_async``: Performs asynchronous updates. The weights are updated whenever gradients are received from any machine. No two updates happen on the same weight at the same time. However, the order is not guaranteed. Parameters ---------- name : {'local', 'device', 'nccl', 'dist_sync', 'dist_device_sync', 'dist_async'} The type of KVStore. Returns ------- kv : KVStore The created KVStore. def create(name='local'): """Creates a new KVStore. For single machine training, there are two commonly used types: ``local``: Copies all gradients to CPU memory and updates weights there. ``device``: Aggregates gradients and updates weights on GPUs. With this setting, the KVStore also attempts to use GPU peer-to-peer communication, potentially accelerating the communication. For distributed training, KVStore also supports a number of types: ``dist_sync``: Behaves similarly to ``local`` but with one major difference. With ``dist_sync``, batch-size now means the batch size used on each machine. So if there are ``n`` machines and we use batch size ``b``, then ``dist_sync`` behaves like ``local`` with batch size ``n * b``. ``dist_device_sync``: Identical to ``dist_sync`` with the difference similar to ``device`` vs ``local``. ``dist_async``: Performs asynchronous updates. The weights are updated whenever gradients are received from any machine. No two updates happen on the same weight at the same time. However, the order is not guaranteed. Parameters ---------- name : {'local', 'device', 'nccl', 'dist_sync', 'dist_device_sync', 'dist_async'} The type of KVStore. Returns ------- kv : KVStore The created KVStore. """ if not isinstance(name, string_types): raise TypeError('name must be a string') handle = KVStoreHandle() check_call(_LIB.MXKVStoreCreate(c_str(name), ctypes.byref(handle))) kv = KVStore(handle) set_kvstore_handle(kv.handle) return kv
Initializes a single or a sequence of key-value pairs into the store. For each key, one must `init` it before calling `push` or `pull`. When multiple workers invoke `init` for the same key, only the value supplied by worker with rank `0` is used. This function returns after data has been initialized successfully. Parameters ---------- key : str, int, or sequence of str or int The keys. value : NDArray, RowSparseNDArray or sequence of NDArray or RowSparseNDArray Values corresponding to the keys. Examples -------- >>> # init a single key-value pair >>> shape = (2,3) >>> kv = mx.kv.create('local') >>> kv.init('3', mx.nd.ones(shape)*2) >>> a = mx.nd.zeros(shape) >>> kv.pull('3', out=a) >>> print a.asnumpy() [[ 2. 2. 2.] [ 2. 2. 2.]] >>> # init a list of key-value pairs >>> keys = ['5', '7', '9'] >>> kv.init(keys, [mx.nd.ones(shape)]*len(keys)) >>> # init a row_sparse value >>> kv.init('4', mx.nd.ones(shape).tostype('row_sparse')) >>> b = mx.nd.sparse.zeros('row_sparse', shape) >>> kv.row_sparse_pull('4', row_ids=mx.nd.array([0, 1]), out=b) >>> print b <RowSparseNDArray 2x3 @cpu(0)> def init(self, key, value): """ Initializes a single or a sequence of key-value pairs into the store. For each key, one must `init` it before calling `push` or `pull`. When multiple workers invoke `init` for the same key, only the value supplied by worker with rank `0` is used. This function returns after data has been initialized successfully. Parameters ---------- key : str, int, or sequence of str or int The keys. value : NDArray, RowSparseNDArray or sequence of NDArray or RowSparseNDArray Values corresponding to the keys. Examples -------- >>> # init a single key-value pair >>> shape = (2,3) >>> kv = mx.kv.create('local') >>> kv.init('3', mx.nd.ones(shape)*2) >>> a = mx.nd.zeros(shape) >>> kv.pull('3', out=a) >>> print a.asnumpy() [[ 2. 2. 2.] [ 2. 2. 2.]] >>> # init a list of key-value pairs >>> keys = ['5', '7', '9'] >>> kv.init(keys, [mx.nd.ones(shape)]*len(keys)) >>> # init a row_sparse value >>> kv.init('4', mx.nd.ones(shape).tostype('row_sparse')) >>> b = mx.nd.sparse.zeros('row_sparse', shape) >>> kv.row_sparse_pull('4', row_ids=mx.nd.array([0, 1]), out=b) >>> print b <RowSparseNDArray 2x3 @cpu(0)> """ ckeys, cvals, use_str_keys = _ctype_key_value(key, value) if use_str_keys: check_call(_LIB.MXKVStoreInitEx(self.handle, mx_uint(len(ckeys)), ckeys, cvals)) else: check_call(_LIB.MXKVStoreInit(self.handle, mx_uint(len(ckeys)), ckeys, cvals))
Pushes a single or a sequence of key-value pairs into the store. This function returns immediately after adding an operator to the engine. The actual operation is executed asynchronously. If there are consecutive pushes to the same key, there is no guarantee on the serialization of pushes. The execution of a push does not guarantee that all previous pushes are finished. There is no synchronization between workers. One can use ``_barrier()`` to sync all workers. Parameters ---------- key : str, int, or sequence of str or int Keys. value : NDArray, RowSparseNDArray, list of NDArray or RowSparseNDArray, or list of list of NDArray or RowSparseNDArray Values corresponding to the keys. priority : int, optional The priority of the push operation. Higher priority push operations are likely to be executed before other push actions. Examples -------- >>> # push a single key-value pair >>> kv.push('3', mx.nd.ones(shape)*8) >>> kv.pull('3', out=a) # pull out the value >>> print a.asnumpy() [[ 8. 8. 8.] [ 8. 8. 8.]] >>> # aggregate the value and the push >>> gpus = [mx.gpu(i) for i in range(4)] >>> b = [mx.nd.ones(shape, gpu) for gpu in gpus] >>> kv.push('3', b) >>> kv.pull('3', out=a) >>> print a.asnumpy() [[ 4. 4. 4.] [ 4. 4. 4.]] >>> # push a list of keys. >>> # single device >>> keys = ['4', '5', '6'] >>> kv.push(keys, [mx.nd.ones(shape)]*len(keys)) >>> b = [mx.nd.zeros(shape)]*len(keys) >>> kv.pull(keys, out=b) >>> print b[1].asnumpy() [[ 1. 1. 1.] [ 1. 1. 1.]] >>> # multiple devices: >>> keys = ['7', '8', '9'] >>> b = [[mx.nd.ones(shape, gpu) for gpu in gpus]] * len(keys) >>> kv.push(keys, b) >>> kv.pull(keys, out=b) >>> print b[1][1].asnumpy() [[ 4. 4. 4.] [ 4. 4. 4.]] >>> # push a row_sparse value >>> b = mx.nd.sparse.zeros('row_sparse', shape) >>> kv.init('10', mx.nd.sparse.zeros('row_sparse', shape)) >>> kv.push('10', mx.nd.ones(shape).tostype('row_sparse')) >>> # pull out the value >>> kv.row_sparse_pull('10', row_ids=mx.nd.array([0, 1]), out=b) >>> print b <RowSparseNDArray 2x3 @cpu(0)> def push(self, key, value, priority=0): """ Pushes a single or a sequence of key-value pairs into the store. This function returns immediately after adding an operator to the engine. The actual operation is executed asynchronously. If there are consecutive pushes to the same key, there is no guarantee on the serialization of pushes. The execution of a push does not guarantee that all previous pushes are finished. There is no synchronization between workers. One can use ``_barrier()`` to sync all workers. Parameters ---------- key : str, int, or sequence of str or int Keys. value : NDArray, RowSparseNDArray, list of NDArray or RowSparseNDArray, or list of list of NDArray or RowSparseNDArray Values corresponding to the keys. priority : int, optional The priority of the push operation. Higher priority push operations are likely to be executed before other push actions. Examples -------- >>> # push a single key-value pair >>> kv.push('3', mx.nd.ones(shape)*8) >>> kv.pull('3', out=a) # pull out the value >>> print a.asnumpy() [[ 8. 8. 8.] [ 8. 8. 8.]] >>> # aggregate the value and the push >>> gpus = [mx.gpu(i) for i in range(4)] >>> b = [mx.nd.ones(shape, gpu) for gpu in gpus] >>> kv.push('3', b) >>> kv.pull('3', out=a) >>> print a.asnumpy() [[ 4. 4. 4.] [ 4. 4. 4.]] >>> # push a list of keys. >>> # single device >>> keys = ['4', '5', '6'] >>> kv.push(keys, [mx.nd.ones(shape)]*len(keys)) >>> b = [mx.nd.zeros(shape)]*len(keys) >>> kv.pull(keys, out=b) >>> print b[1].asnumpy() [[ 1. 1. 1.] [ 1. 1. 1.]] >>> # multiple devices: >>> keys = ['7', '8', '9'] >>> b = [[mx.nd.ones(shape, gpu) for gpu in gpus]] * len(keys) >>> kv.push(keys, b) >>> kv.pull(keys, out=b) >>> print b[1][1].asnumpy() [[ 4. 4. 4.] [ 4. 4. 4.]] >>> # push a row_sparse value >>> b = mx.nd.sparse.zeros('row_sparse', shape) >>> kv.init('10', mx.nd.sparse.zeros('row_sparse', shape)) >>> kv.push('10', mx.nd.ones(shape).tostype('row_sparse')) >>> # pull out the value >>> kv.row_sparse_pull('10', row_ids=mx.nd.array([0, 1]), out=b) >>> print b <RowSparseNDArray 2x3 @cpu(0)> """ ckeys, cvals, use_str_keys = _ctype_key_value(key, value) if use_str_keys: check_call(_LIB.MXKVStorePushEx( self.handle, mx_uint(len(ckeys)), ckeys, cvals, ctypes.c_int(priority))) else: check_call(_LIB.MXKVStorePush( self.handle, mx_uint(len(ckeys)), ckeys, cvals, ctypes.c_int(priority)))
Pulls a single value or a sequence of values from the store. This function returns immediately after adding an operator to the engine. Subsequent attempts to read from the `out` variable will be blocked until the pull operation completes. `pull` is executed asynchronously after all previous `pull` calls and only the last `push` call for the same input key(s) are finished. The returned values are guaranteed to be the latest values in the store. pull with `RowSparseNDArray` is not supported for dist kvstore. Please use ``row_sparse_pull`` instead. Parameters ---------- key : str, int, or sequence of str or int Keys. out: NDArray or list of NDArray or list of list of NDArray Values corresponding to the keys. priority : int, optional The priority of the pull operation. Higher priority pull operations are likely to be executed before other pull actions. ignore_sparse: bool, optional, default True Whether to ignore sparse arrays in the request. Examples -------- >>> # pull a single key-value pair >>> a = mx.nd.zeros(shape) >>> kv.pull('3', out=a) >>> print a.asnumpy() [[ 2. 2. 2.] [ 2. 2. 2.]] >>> # pull into multiple devices >>> b = [mx.nd.ones(shape, gpu) for gpu in gpus] >>> kv.pull('3', out=b) >>> print b[1].asnumpy() [[ 2. 2. 2.] [ 2. 2. 2.]] >>> # pull a list of key-value pairs. >>> # On single device >>> keys = ['5', '7', '9'] >>> b = [mx.nd.zeros(shape)]*len(keys) >>> kv.pull(keys, out=b) >>> print b[1].asnumpy() [[ 2. 2. 2.] [ 2. 2. 2.]] >>> # On multiple devices >>> keys = ['6', '8', '10'] >>> b = [[mx.nd.ones(shape, gpu) for gpu in gpus]] * len(keys) >>> kv.pull(keys, out=b) >>> print b[1][1].asnumpy() [[ 2. 2. 2.] [ 2. 2. 2.]] def pull(self, key, out=None, priority=0, ignore_sparse=True): """ Pulls a single value or a sequence of values from the store. This function returns immediately after adding an operator to the engine. Subsequent attempts to read from the `out` variable will be blocked until the pull operation completes. `pull` is executed asynchronously after all previous `pull` calls and only the last `push` call for the same input key(s) are finished. The returned values are guaranteed to be the latest values in the store. pull with `RowSparseNDArray` is not supported for dist kvstore. Please use ``row_sparse_pull`` instead. Parameters ---------- key : str, int, or sequence of str or int Keys. out: NDArray or list of NDArray or list of list of NDArray Values corresponding to the keys. priority : int, optional The priority of the pull operation. Higher priority pull operations are likely to be executed before other pull actions. ignore_sparse: bool, optional, default True Whether to ignore sparse arrays in the request. Examples -------- >>> # pull a single key-value pair >>> a = mx.nd.zeros(shape) >>> kv.pull('3', out=a) >>> print a.asnumpy() [[ 2. 2. 2.] [ 2. 2. 2.]] >>> # pull into multiple devices >>> b = [mx.nd.ones(shape, gpu) for gpu in gpus] >>> kv.pull('3', out=b) >>> print b[1].asnumpy() [[ 2. 2. 2.] [ 2. 2. 2.]] >>> # pull a list of key-value pairs. >>> # On single device >>> keys = ['5', '7', '9'] >>> b = [mx.nd.zeros(shape)]*len(keys) >>> kv.pull(keys, out=b) >>> print b[1].asnumpy() [[ 2. 2. 2.] [ 2. 2. 2.]] >>> # On multiple devices >>> keys = ['6', '8', '10'] >>> b = [[mx.nd.ones(shape, gpu) for gpu in gpus]] * len(keys) >>> kv.pull(keys, out=b) >>> print b[1][1].asnumpy() [[ 2. 2. 2.] [ 2. 2. 2.]] """ assert(out is not None) ckeys, cvals, use_str_keys = _ctype_key_value(key, out) if use_str_keys: check_call(_LIB.MXKVStorePullWithSparseEx(self.handle, mx_uint(len(ckeys)), ckeys, cvals, ctypes.c_int(priority), ctypes.c_bool(ignore_sparse))) else: check_call(_LIB.MXKVStorePullWithSparse(self.handle, mx_uint(len(ckeys)), ckeys, cvals, ctypes.c_int(priority), ctypes.c_bool(ignore_sparse)))
Pulls a single RowSparseNDArray value or a sequence of RowSparseNDArray values \ from the store with specified row_ids. When there is only one row_id, KVStoreRowSparsePull \ is invoked just once and the result is broadcast to all the rest of outputs. `row_sparse_pull` is executed asynchronously after all previous `pull`/`row_sparse_pull` calls and the last `push` call for the same input key(s) are finished. The returned values are guaranteed to be the latest values in the store. Parameters ---------- key : str, int, or sequence of str or int Keys. out: RowSparseNDArray or list of RowSparseNDArray or list of list of RowSparseNDArray Values corresponding to the keys. The stype is expected to be row_sparse priority : int, optional The priority of the pull operation. Higher priority pull operations are likely to be executed before other pull actions. row_ids : NDArray or list of NDArray The row_ids for which to pull for each value. Each row_id is an 1-D NDArray \ whose values don't have to be unique nor sorted. Examples -------- >>> shape = (3, 3) >>> kv.init('3', mx.nd.ones(shape).tostype('row_sparse')) >>> a = mx.nd.sparse.zeros('row_sparse', shape) >>> row_ids = mx.nd.array([0, 2], dtype='int64') >>> kv.row_sparse_pull('3', out=a, row_ids=row_ids) >>> print a.asnumpy() [[ 1. 1. 1.] [ 0. 0. 0.] [ 1. 1. 1.]] >>> duplicate_row_ids = mx.nd.array([2, 2], dtype='int64') >>> kv.row_sparse_pull('3', out=a, row_ids=duplicate_row_ids) >>> print a.asnumpy() [[ 0. 0. 0.] [ 0. 0. 0.] [ 1. 1. 1.]] >>> unsorted_row_ids = mx.nd.array([1, 0], dtype='int64') >>> kv.row_sparse_pull('3', out=a, row_ids=unsorted_row_ids) >>> print a.asnumpy() [[ 1. 1. 1.] [ 1. 1. 1.] [ 0. 0. 0.]] def row_sparse_pull(self, key, out=None, priority=0, row_ids=None): """ Pulls a single RowSparseNDArray value or a sequence of RowSparseNDArray values \ from the store with specified row_ids. When there is only one row_id, KVStoreRowSparsePull \ is invoked just once and the result is broadcast to all the rest of outputs. `row_sparse_pull` is executed asynchronously after all previous `pull`/`row_sparse_pull` calls and the last `push` call for the same input key(s) are finished. The returned values are guaranteed to be the latest values in the store. Parameters ---------- key : str, int, or sequence of str or int Keys. out: RowSparseNDArray or list of RowSparseNDArray or list of list of RowSparseNDArray Values corresponding to the keys. The stype is expected to be row_sparse priority : int, optional The priority of the pull operation. Higher priority pull operations are likely to be executed before other pull actions. row_ids : NDArray or list of NDArray The row_ids for which to pull for each value. Each row_id is an 1-D NDArray \ whose values don't have to be unique nor sorted. Examples -------- >>> shape = (3, 3) >>> kv.init('3', mx.nd.ones(shape).tostype('row_sparse')) >>> a = mx.nd.sparse.zeros('row_sparse', shape) >>> row_ids = mx.nd.array([0, 2], dtype='int64') >>> kv.row_sparse_pull('3', out=a, row_ids=row_ids) >>> print a.asnumpy() [[ 1. 1. 1.] [ 0. 0. 0.] [ 1. 1. 1.]] >>> duplicate_row_ids = mx.nd.array([2, 2], dtype='int64') >>> kv.row_sparse_pull('3', out=a, row_ids=duplicate_row_ids) >>> print a.asnumpy() [[ 0. 0. 0.] [ 0. 0. 0.] [ 1. 1. 1.]] >>> unsorted_row_ids = mx.nd.array([1, 0], dtype='int64') >>> kv.row_sparse_pull('3', out=a, row_ids=unsorted_row_ids) >>> print a.asnumpy() [[ 1. 1. 1.] [ 1. 1. 1.] [ 0. 0. 0.]] """ assert(out is not None) assert(row_ids is not None) if isinstance(row_ids, NDArray): row_ids = [row_ids] assert(isinstance(row_ids, list)), \ "row_ids should be NDArray or list of NDArray" first_out = out # whether row_ids are the same single_rowid = False if len(row_ids) == 1 and isinstance(out, list): single_rowid = True first_out = [out[0]] ckeys, cvals, use_str_keys = _ctype_key_value(key, first_out) _, crow_ids, _ = _ctype_key_value(key, row_ids) assert(len(crow_ids) == len(cvals)), \ "the number of row_ids doesn't match the number of values" if use_str_keys: check_call(_LIB.MXKVStorePullRowSparseEx( self.handle, mx_uint(len(ckeys)), ckeys, cvals, crow_ids, ctypes.c_int(priority))) else: check_call(_LIB.MXKVStorePullRowSparse( self.handle, mx_uint(len(ckeys)), ckeys, cvals, crow_ids, ctypes.c_int(priority))) # the result can be copied to other devices without invoking row_sparse_pull # if the indices are the same if single_rowid: for out_i in out[1:]: out[0].copyto(out_i)
Specifies type of low-bit quantization for gradient compression \ and additional arguments depending on the type of compression being used. 2bit Gradient Compression takes a positive float `threshold`. The technique works by thresholding values such that positive values in the gradient above threshold will be set to threshold. Negative values whose absolute values are higher than threshold, will be set to the negative of threshold. Values whose absolute values are less than threshold will be set to 0. By doing so, each value in the gradient is in one of three states. 2bits are used to represent these states, and every 16 float values in the original gradient can be represented using one float. This compressed representation can reduce communication costs. The difference between these thresholded values and original values is stored at the sender's end as residual and added to the gradient in the next iteration. When kvstore is 'local', gradient compression is used to reduce communication between multiple devices (gpus). Gradient is quantized on each GPU which computed the gradients, then sent to the GPU which merges the gradients. This receiving GPU dequantizes the gradients and merges them. Note that this increases memory usage on each GPU because of the residual array stored. When kvstore is 'dist', gradient compression is used to reduce communication from worker to sender. Gradient is quantized on each worker which computed the gradients, then sent to the server which dequantizes this data and merges the gradients from each worker. Note that this increases CPU memory usage on each worker because of the residual array stored. Only worker to server communication is compressed in this setting. If each machine has multiple GPUs, currently this GPU to GPU or GPU to CPU communication is not compressed. Server to worker communication (in the case of pull) is also not compressed. To use 2bit compression, we need to specify `type` as `2bit`. Only specifying `type` would use default value for the threshold. To completely specify the arguments for 2bit compression, we would need to pass a dictionary which includes `threshold` like: {'type': '2bit', 'threshold': 0.5} Parameters ---------- compression_params : dict A dictionary specifying the type and parameters for gradient compression. The key `type` in this dictionary is a required string argument and specifies the type of gradient compression. Currently `type` can be only `2bit` Other keys in this dictionary are optional and specific to the type of gradient compression. def set_gradient_compression(self, compression_params): """ Specifies type of low-bit quantization for gradient compression \ and additional arguments depending on the type of compression being used. 2bit Gradient Compression takes a positive float `threshold`. The technique works by thresholding values such that positive values in the gradient above threshold will be set to threshold. Negative values whose absolute values are higher than threshold, will be set to the negative of threshold. Values whose absolute values are less than threshold will be set to 0. By doing so, each value in the gradient is in one of three states. 2bits are used to represent these states, and every 16 float values in the original gradient can be represented using one float. This compressed representation can reduce communication costs. The difference between these thresholded values and original values is stored at the sender's end as residual and added to the gradient in the next iteration. When kvstore is 'local', gradient compression is used to reduce communication between multiple devices (gpus). Gradient is quantized on each GPU which computed the gradients, then sent to the GPU which merges the gradients. This receiving GPU dequantizes the gradients and merges them. Note that this increases memory usage on each GPU because of the residual array stored. When kvstore is 'dist', gradient compression is used to reduce communication from worker to sender. Gradient is quantized on each worker which computed the gradients, then sent to the server which dequantizes this data and merges the gradients from each worker. Note that this increases CPU memory usage on each worker because of the residual array stored. Only worker to server communication is compressed in this setting. If each machine has multiple GPUs, currently this GPU to GPU or GPU to CPU communication is not compressed. Server to worker communication (in the case of pull) is also not compressed. To use 2bit compression, we need to specify `type` as `2bit`. Only specifying `type` would use default value for the threshold. To completely specify the arguments for 2bit compression, we would need to pass a dictionary which includes `threshold` like: {'type': '2bit', 'threshold': 0.5} Parameters ---------- compression_params : dict A dictionary specifying the type and parameters for gradient compression. The key `type` in this dictionary is a required string argument and specifies the type of gradient compression. Currently `type` can be only `2bit` Other keys in this dictionary are optional and specific to the type of gradient compression. """ if ('device' in self.type) or ('dist' in self.type): # pylint: disable=unsupported-membership-test ckeys, cvals = _ctype_dict(compression_params) check_call(_LIB.MXKVStoreSetGradientCompression(self.handle, mx_uint(len(compression_params)), ckeys, cvals)) else: raise Exception('Gradient compression is not supported for this type of kvstore')
Registers an optimizer with the kvstore. When using a single machine, this function updates the local optimizer. If using multiple machines and this operation is invoked from a worker node, it will serialized the optimizer with pickle and send it to all servers. The function returns after all servers have been updated. Parameters ---------- optimizer : Optimizer The new optimizer for the store Examples -------- >>> kv = mx.kv.create() >>> shape = (2, 2) >>> weight = mx.nd.zeros(shape) >>> kv.init(3, weight) >>> # set the optimizer for kvstore as the default SGD optimizer >>> kv.set_optimizer(mx.optimizer.SGD()) >>> grad = mx.nd.ones(shape) >>> kv.push(3, grad) >>> kv.pull(3, out = weight) >>> # weight is updated via gradient descent >>> weight.asnumpy() array([[-0.01, -0.01], [-0.01, -0.01]], dtype=float32) def set_optimizer(self, optimizer): """ Registers an optimizer with the kvstore. When using a single machine, this function updates the local optimizer. If using multiple machines and this operation is invoked from a worker node, it will serialized the optimizer with pickle and send it to all servers. The function returns after all servers have been updated. Parameters ---------- optimizer : Optimizer The new optimizer for the store Examples -------- >>> kv = mx.kv.create() >>> shape = (2, 2) >>> weight = mx.nd.zeros(shape) >>> kv.init(3, weight) >>> # set the optimizer for kvstore as the default SGD optimizer >>> kv.set_optimizer(mx.optimizer.SGD()) >>> grad = mx.nd.ones(shape) >>> kv.push(3, grad) >>> kv.pull(3, out = weight) >>> # weight is updated via gradient descent >>> weight.asnumpy() array([[-0.01, -0.01], [-0.01, -0.01]], dtype=float32) """ is_worker = ctypes.c_int() check_call(_LIB.MXKVStoreIsWorkerNode(ctypes.byref(is_worker))) # pylint: disable=invalid-name if 'dist' in self.type and is_worker.value: # pylint: disable=unsupported-membership-test # send the optimizer to server try: # use ASCII protocol 0, might be slower, but not a big ideal optim_str = py_str(pickle.dumps(optimizer, 0)) except: raise cmd = _get_kvstore_server_command_type('kController') self._send_command_to_servers(cmd, optim_str) if optimizer.multi_precision: cmd = _get_kvstore_server_command_type('kSetMultiPrecision') self._send_command_to_servers(cmd, '') else: self._set_updater(opt.get_updater(optimizer))
Returns the type of this kvstore. Returns ------- type : str the string type def type(self): """ Returns the type of this kvstore. Returns ------- type : str the string type """ kv_type = ctypes.c_char_p() check_call(_LIB.MXKVStoreGetType(self.handle, ctypes.byref(kv_type))) return py_str(kv_type.value)
Returns the rank of this worker node. Returns ------- rank : int The rank of this node, which is in range [0, num_workers()) def rank(self): """ Returns the rank of this worker node. Returns ------- rank : int The rank of this node, which is in range [0, num_workers()) """ rank = ctypes.c_int() check_call(_LIB.MXKVStoreGetRank(self.handle, ctypes.byref(rank))) return rank.value
Returns the number of worker nodes. Returns ------- size :int The number of worker nodes. def num_workers(self): """Returns the number of worker nodes. Returns ------- size :int The number of worker nodes. """ size = ctypes.c_int() check_call(_LIB.MXKVStoreGetGroupSize(self.handle, ctypes.byref(size))) return size.value
Saves the optimizer (updater) state to a file. This is often used when checkpointing the model during training. Parameters ---------- fname : str Path to the output states file. dump_optimizer : bool, default False Whether to also save the optimizer itself. This would also save optimizer information such as learning rate and weight decay schedules. def save_optimizer_states(self, fname, dump_optimizer=False): """Saves the optimizer (updater) state to a file. This is often used when checkpointing the model during training. Parameters ---------- fname : str Path to the output states file. dump_optimizer : bool, default False Whether to also save the optimizer itself. This would also save optimizer information such as learning rate and weight decay schedules. """ assert self._updater is not None, "Cannot save states for distributed training" with open(fname, 'wb') as fout: fout.write(self._updater.get_states(dump_optimizer))
Loads the optimizer (updater) state from the file. Parameters ---------- fname : str Path to input states file. def load_optimizer_states(self, fname): """Loads the optimizer (updater) state from the file. Parameters ---------- fname : str Path to input states file. """ assert self._updater is not None, "Cannot load states for distributed training" self._updater.set_states(open(fname, 'rb').read())
Sets a push updater into the store. This function only changes the local store. When running on multiple machines one must use `set_optimizer`. Parameters ---------- updater : function The updater function. Examples -------- >>> def update(key, input, stored): ... print "update on key: %d" % key ... stored += input * 2 >>> kv._set_updater(update) >>> kv.pull('3', out=a) >>> print a.asnumpy() [[ 4. 4. 4.] [ 4. 4. 4.]] >>> kv.push('3', mx.nd.ones(shape)) update on key: 3 >>> kv.pull('3', out=a) >>> print a.asnumpy() [[ 6. 6. 6.] [ 6. 6. 6.]] def _set_updater(self, updater): """Sets a push updater into the store. This function only changes the local store. When running on multiple machines one must use `set_optimizer`. Parameters ---------- updater : function The updater function. Examples -------- >>> def update(key, input, stored): ... print "update on key: %d" % key ... stored += input * 2 >>> kv._set_updater(update) >>> kv.pull('3', out=a) >>> print a.asnumpy() [[ 4. 4. 4.] [ 4. 4. 4.]] >>> kv.push('3', mx.nd.ones(shape)) update on key: 3 >>> kv.pull('3', out=a) >>> print a.asnumpy() [[ 6. 6. 6.] [ 6. 6. 6.]] """ self._updater = updater # set updater with int keys _updater_proto = ctypes.CFUNCTYPE( None, ctypes.c_int, NDArrayHandle, NDArrayHandle, ctypes.c_void_p) self._updater_func = _updater_proto(_updater_wrapper(updater)) # set updater with str keys _str_updater_proto = ctypes.CFUNCTYPE( None, ctypes.c_char_p, NDArrayHandle, NDArrayHandle, ctypes.c_void_p) self._str_updater_func = _str_updater_proto(_updater_wrapper(updater)) check_call(_LIB.MXKVStoreSetUpdaterEx(self.handle, self._updater_func, self._str_updater_func, None))
Sends a command to all server nodes. Sending command to a server node will cause that server node to invoke ``KVStoreServer.controller`` to execute the command. This function returns after the command has been executed on all server nodes. Parameters ---------- head : int the head of the command. body : str the body of the command. def _send_command_to_servers(self, head, body): """Sends a command to all server nodes. Sending command to a server node will cause that server node to invoke ``KVStoreServer.controller`` to execute the command. This function returns after the command has been executed on all server nodes. Parameters ---------- head : int the head of the command. body : str the body of the command. """ check_call(_LIB.MXKVStoreSendCommmandToServers( self.handle, mx_uint(head), c_str(body)))
Add a module to the chain. Parameters ---------- module : BaseModule The new module to add. kwargs : ``**keywords`` All the keyword arguments are saved as meta information for the added module. The currently known meta includes - `take_labels`: indicating whether the module expect to take labels when doing computation. Note any module in the chain can take labels (not necessarily only the top most one), and they all take the same labels passed from the original data batch for the `SequentialModule`. Returns ------- self This function returns `self` to allow us to easily chain a series of `add` calls. Examples -------- >>> # An example of addinging two modules to a chain. >>> seq_mod = mx.mod.SequentialModule() >>> seq_mod.add(mod1) >>> seq_mod.add(mod2) def add(self, module, **kwargs): """Add a module to the chain. Parameters ---------- module : BaseModule The new module to add. kwargs : ``**keywords`` All the keyword arguments are saved as meta information for the added module. The currently known meta includes - `take_labels`: indicating whether the module expect to take labels when doing computation. Note any module in the chain can take labels (not necessarily only the top most one), and they all take the same labels passed from the original data batch for the `SequentialModule`. Returns ------- self This function returns `self` to allow us to easily chain a series of `add` calls. Examples -------- >>> # An example of addinging two modules to a chain. >>> seq_mod = mx.mod.SequentialModule() >>> seq_mod.add(mod1) >>> seq_mod.add(mod2) """ self._modules.append(module) # a sanity check to avoid typo for key in kwargs: assert key in self._meta_keys, ('Unknown meta "%s", a typo?' % key) self._metas.append(kwargs) # after adding new modules, we are reset back to raw states, needs # to bind, init_params, etc. self.binded = False self.params_initialized = False self.optimizer_initialized = False return self
Gets current parameters. Returns ------- (arg_params, aux_params) A pair of dictionaries each mapping parameter names to NDArray values. This is a merged dictionary of all the parameters in the modules. def get_params(self): """Gets current parameters. Returns ------- (arg_params, aux_params) A pair of dictionaries each mapping parameter names to NDArray values. This is a merged dictionary of all the parameters in the modules. """ assert self.binded and self.params_initialized arg_params = dict() aux_params = dict() for module in self._modules: arg, aux = module.get_params() arg_params.update(arg) aux_params.update(aux) return (arg_params, aux_params)
Initializes parameters. Parameters ---------- initializer : Initializer arg_params : dict Default ``None``. Existing parameters. This has higher priority than `initializer`. aux_params : dict Default ``None``. Existing auxiliary states. This has higher priority than `initializer`. allow_missing : bool Allow missing values in `arg_params` and `aux_params` (if not ``None``). In this case, missing values will be filled with `initializer`. force_init : bool Default ``False``. allow_extra : boolean, optional Whether allow extra parameters that are not needed by symbol. If this is True, no error will be thrown when arg_params or aux_params contain extra parameters that is not needed by the executor. def init_params(self, initializer=Uniform(0.01), arg_params=None, aux_params=None, allow_missing=False, force_init=False, allow_extra=False): """Initializes parameters. Parameters ---------- initializer : Initializer arg_params : dict Default ``None``. Existing parameters. This has higher priority than `initializer`. aux_params : dict Default ``None``. Existing auxiliary states. This has higher priority than `initializer`. allow_missing : bool Allow missing values in `arg_params` and `aux_params` (if not ``None``). In this case, missing values will be filled with `initializer`. force_init : bool Default ``False``. allow_extra : boolean, optional Whether allow extra parameters that are not needed by symbol. If this is True, no error will be thrown when arg_params or aux_params contain extra parameters that is not needed by the executor. """ if self.params_initialized and not force_init: return assert self.binded, 'call bind before initializing the parameters' for module in self._modules: module.init_params(initializer=initializer, arg_params=arg_params, aux_params=aux_params, allow_missing=allow_missing, force_init=force_init, allow_extra=allow_extra) # make sure we do not have duplicated parameter names def _check_name(known_names, new_names, modules, i): """Internal function to help checking duplicated names.""" for name in new_names: assert not name in known_names, "Duplicated parameter names: " + \ ('name "%s" in layer %d (%s) is already ' % (name, i, type(modules[i]))) + \ ('used in layer %d (%s).' % (known_names[name], type(modules[known_names[name]]))) known_names[name] = i arg_names = dict() aux_names = dict() for i_layer, module in enumerate(self._modules): arg_params, aux_params = module.get_params() _check_name(arg_names, arg_params.keys(), self._modules, i_layer) _check_name(aux_names, aux_params.keys(), self._modules, i_layer) self.params_initialized = True
Binds the symbols to construct executors. This is necessary before one can perform computation with the module. Parameters ---------- data_shapes : list of (str, tuple) Typically is `data_iter.provide_data`. label_shapes : list of (str, tuple) Typically is `data_iter.provide_label`. for_training : bool Default is ``True``. Whether the executors should be bind for training. inputs_need_grad : bool Default is ``False``. Whether the gradients to the input data need to be computed. Typically this is not needed. But this might be needed when implementing composition of modules. force_rebind : bool Default is ``False``. This function does nothing if the executors are already bound. But with this ``True``, the executors will be forced to rebind. shared_module : Module Default is ``None``. Currently shared module is not supported for `SequentialModule`. grad_req : str, list of str, dict of str to str Requirement for gradient accumulation. Can be 'write', 'add', or 'null' (default to 'write'). Can be specified globally (str) or for each argument (list, dict). def bind(self, data_shapes, label_shapes=None, for_training=True, inputs_need_grad=False, force_rebind=False, shared_module=None, grad_req='write'): """Binds the symbols to construct executors. This is necessary before one can perform computation with the module. Parameters ---------- data_shapes : list of (str, tuple) Typically is `data_iter.provide_data`. label_shapes : list of (str, tuple) Typically is `data_iter.provide_label`. for_training : bool Default is ``True``. Whether the executors should be bind for training. inputs_need_grad : bool Default is ``False``. Whether the gradients to the input data need to be computed. Typically this is not needed. But this might be needed when implementing composition of modules. force_rebind : bool Default is ``False``. This function does nothing if the executors are already bound. But with this ``True``, the executors will be forced to rebind. shared_module : Module Default is ``None``. Currently shared module is not supported for `SequentialModule`. grad_req : str, list of str, dict of str to str Requirement for gradient accumulation. Can be 'write', 'add', or 'null' (default to 'write'). Can be specified globally (str) or for each argument (list, dict). """ if self.binded and not force_rebind: self.logger.warning('Already bound, ignoring bind()') return if inputs_need_grad: assert for_training is True assert shared_module is None, 'Shared module is not supported' assert len(self._modules) > 0, 'Attempting to bind an empty SequentialModule' self.binded = True # the same label shapes are used for all chained modules self._label_shapes = label_shapes my_data_shapes = data_shapes anybody_ever_needs_label = False for i_layer, module in enumerate(self._modules): meta = self._metas[i_layer] if SequentialModule.META_TAKE_LABELS in meta and \ meta[SequentialModule.META_TAKE_LABELS]: my_label_shapes = label_shapes anybody_ever_needs_label = True else: my_label_shapes = None my_inputs_need_grad = bool(inputs_need_grad or (for_training and i_layer > 0)) if meta.get(SequentialModule.META_AUTO_WIRING, False): data_names = module.data_names assert len(data_names) == len(my_data_shapes) my_data_shapes = [(new_name, shape) for (new_name, (_, shape)) in zip(data_names, my_data_shapes)] module.bind(data_shapes=my_data_shapes, label_shapes=my_label_shapes, for_training=for_training, inputs_need_grad=my_inputs_need_grad, force_rebind=force_rebind, shared_module=None, grad_req=grad_req) # the output of the previous module is the data of the next module my_data_shapes = module.output_shapes if not anybody_ever_needs_label: # then I do not need label either self._label_shapes = None
Installs and initializes optimizers. Parameters ---------- kvstore : str or KVStore Default `'local'`. optimizer : str or Optimizer Default `'sgd'` optimizer_params : dict Default ``(('learning_rate', 0.01),)``. The default value is not a dictionary, just to avoid pylint warning of dangerous default values. force_init : bool Default ``False``, indicating whether we should force re-initializing the optimizer in the case an optimizer is already installed. def init_optimizer(self, kvstore='local', optimizer='sgd', optimizer_params=(('learning_rate', 0.01),), force_init=False): """Installs and initializes optimizers. Parameters ---------- kvstore : str or KVStore Default `'local'`. optimizer : str or Optimizer Default `'sgd'` optimizer_params : dict Default ``(('learning_rate', 0.01),)``. The default value is not a dictionary, just to avoid pylint warning of dangerous default values. force_init : bool Default ``False``, indicating whether we should force re-initializing the optimizer in the case an optimizer is already installed. """ assert self.binded and self.params_initialized if self.optimizer_initialized and not force_init: self.logger.warning('optimizer already initialized, ignoring.') return for module in self._modules: module.init_optimizer(kvstore=kvstore, optimizer=optimizer, optimizer_params=optimizer_params, force_init=force_init) self.optimizer_initialized = True
Forward computation. Parameters ---------- data_batch : DataBatch is_train : bool Default is ``None``, in which case `is_train` is take as ``self.for_training``. def forward(self, data_batch, is_train=None): """Forward computation. Parameters ---------- data_batch : DataBatch is_train : bool Default is ``None``, in which case `is_train` is take as ``self.for_training``. """ assert self.binded and self.params_initialized # make a shallow copy, just to maintain necessary properties (if any) like # bucket_key, pad, etc. data_batch = copy.copy(data_batch) for i_layer, module in enumerate(self._modules): module.forward(data_batch, is_train=is_train) if i_layer+1 == len(self._modules): # the last layer, do not need to do the followings break data_batch.data = module.get_outputs() if hasattr(data_batch, 'provide_data'): # need to update this, in case the internal module is using bucketing # or whatever data_names = [x[0] for x in module.output_shapes] assert len(data_names) == len(data_batch.data) data_batch.provide_data = [(name, x.shape) for name, x in zip(data_names, data_batch.data)]
Backward computation. def backward(self, out_grads=None): """Backward computation.""" assert self.binded and self.params_initialized for i_layer, module in reversed(list(zip(range(len(self._modules)), self._modules))): module.backward(out_grads=out_grads) if i_layer == 0: break out_grads = module.get_input_grads()
Updates parameters according to installed optimizer and the gradient computed in the previous forward-backward cycle. def update(self): """Updates parameters according to installed optimizer and the gradient computed in the previous forward-backward cycle. """ assert self.binded and self.params_initialized and self.optimizer_initialized for module in self._modules: module.update()
Gets outputs from a previous forward computation. Parameters ---------- merge_multi_context : bool Default is ``True``. In the case when data-parallelism is used, the outputs will be collected from multiple devices. A ``True`` value indicate that we should merge the collected results so that they look like from a single executor. Returns ------- list of NDArray or list of list of NDArray If `merge_multi_context` is ``True``, it is like ``[out1, out2]``. Otherwise, it is like ``[[out1_dev1, out1_dev2], [out2_dev1, out2_dev2]]``. All the output elements are numpy arrays. def get_outputs(self, merge_multi_context=True): """Gets outputs from a previous forward computation. Parameters ---------- merge_multi_context : bool Default is ``True``. In the case when data-parallelism is used, the outputs will be collected from multiple devices. A ``True`` value indicate that we should merge the collected results so that they look like from a single executor. Returns ------- list of NDArray or list of list of NDArray If `merge_multi_context` is ``True``, it is like ``[out1, out2]``. Otherwise, it is like ``[[out1_dev1, out1_dev2], [out2_dev1, out2_dev2]]``. All the output elements are numpy arrays. """ assert self.binded and self.params_initialized return self._modules[-1].get_outputs(merge_multi_context=merge_multi_context)
Gets the gradients with respect to the inputs of the module. Parameters ---------- merge_multi_context : bool Default is ``True``. In the case when data-parallelism is used, the outputs will be collected from multiple devices. A ``True`` value indicate that we should merge the collected results so that they look like from a single executor. Returns ------- list of NDArrays or list of list of NDArrays If `merge_multi_context` is ``True``, it is like ``[grad1, grad2]``. Otherwise, it is like ``[[grad1_dev1, grad1_dev2], [grad2_dev1, grad2_dev2]]``. All the output elements are `NDArray`. def get_input_grads(self, merge_multi_context=True): """Gets the gradients with respect to the inputs of the module. Parameters ---------- merge_multi_context : bool Default is ``True``. In the case when data-parallelism is used, the outputs will be collected from multiple devices. A ``True`` value indicate that we should merge the collected results so that they look like from a single executor. Returns ------- list of NDArrays or list of list of NDArrays If `merge_multi_context` is ``True``, it is like ``[grad1, grad2]``. Otherwise, it is like ``[[grad1_dev1, grad1_dev2], [grad2_dev1, grad2_dev2]]``. All the output elements are `NDArray`. """ assert self.binded and self.params_initialized and self.inputs_need_grad return self._modules[0].get_input_grads(merge_multi_context=merge_multi_context)
Evaluates and accumulates evaluation metric on outputs of the last forward computation. Parameters ---------- eval_metric : EvalMetric labels : list of NDArray Typically ``data_batch.label``. def update_metric(self, eval_metric, labels, pre_sliced=False): """Evaluates and accumulates evaluation metric on outputs of the last forward computation. Parameters ---------- eval_metric : EvalMetric labels : list of NDArray Typically ``data_batch.label``. """ assert self.binded and self.params_initialized for meta, module in zip(self._metas, self._modules): if SequentialModule.META_TAKE_LABELS in meta and \ meta[SequentialModule.META_TAKE_LABELS]: module.update_metric(eval_metric, labels, pre_sliced)
Installs monitor on all executors. def install_monitor(self, mon): """Installs monitor on all executors.""" assert self.binded for module in self._modules: module.install_monitor(mon)
Generate the iterator of mnist dataset def get_iterator(data_shape, use_caffe_data): """Generate the iterator of mnist dataset""" def get_iterator_impl_mnist(args, kv): """return train and val iterators for mnist""" # download data get_mnist_ubyte() flat = False if len(data_shape) != 1 else True train = mx.io.MNISTIter( image="data/train-images-idx3-ubyte", label="data/train-labels-idx1-ubyte", input_shape=data_shape, batch_size=args.batch_size, shuffle=True, flat=flat, num_parts=kv.num_workers, part_index=kv.rank) val = mx.io.MNISTIter( image="data/t10k-images-idx3-ubyte", label="data/t10k-labels-idx1-ubyte", input_shape=data_shape, batch_size=args.batch_size, flat=flat, num_parts=kv.num_workers, part_index=kv.rank) return (train, val) def get_iterator_impl_caffe(args, kv): flat = False if len(data_shape) != 1 else True train = mx.io.CaffeDataIter( prototxt= 'layer { \ name: "mnist" \ type: "Data" \ top: "data" \ top: "label" \ include { \ phase: TRAIN \ } \ transform_param { \ scale: 0.00390625 \ } \ data_param { \ source: "mnist_train_lmdb" \ batch_size: 64 \ backend: LMDB \ } \ }', flat=flat, num_examples=60000 # float32 is the default, so left out here in order to illustrate ) val = mx.io.CaffeDataIter( prototxt= 'layer { \ name: "mnist" \ type: "Data" \ top: "data" \ top: "label" \ include { \ phase: TEST \ } \ transform_param { \ scale: 0.00390625 \ } \ data_param { \ source: "mnist_test_lmdb" \ batch_size: 100 \ backend: LMDB \ } \ }', flat=flat, num_examples=10000, dtype="float32" # float32 is the default ) return train, val if use_caffe_data: return get_iterator_impl_caffe else: return get_iterator_impl_mnist
The function is used to run predictions on the audio files in the directory `pred_directory`. Parameters ---------- net: The model that has been trained. prediction_dir: string, default ./Test The directory that contains the audio files on which predictions are to be made def predict(prediction_dir='./Test'): """The function is used to run predictions on the audio files in the directory `pred_directory`. Parameters ---------- net: The model that has been trained. prediction_dir: string, default ./Test The directory that contains the audio files on which predictions are to be made """ if not os.path.exists(prediction_dir): warnings.warn("The directory on which predictions are to be made is not found!") return if len(os.listdir(prediction_dir)) == 0: warnings.warn("The directory on which predictions are to be made is empty! Exiting...") return # Loading synsets if not os.path.exists('./synset.txt'): warnings.warn("The synset or labels for the dataset do not exist. Please run the training script first.") return with open("./synset.txt", "r") as f: synset = [l.rstrip() for l in f] net = get_net(len(synset)) print("Trying to load the model with the saved parameters...") if not os.path.exists("./net.params"): warnings.warn("The model does not have any saved parameters... Cannot proceed! Train the model first") return net.load_parameters("./net.params") file_names = os.listdir(prediction_dir) full_file_names = [os.path.join(prediction_dir, item) for item in file_names] from transforms import MFCC mfcc = MFCC() print("\nStarting predictions for audio files in ", prediction_dir, " ....\n") for filename in full_file_names: # Argument kaiser_fast to res_type is faster than 'kaiser_best'. To reduce the load time, passing kaiser_fast. X1, _ = librosa.load(filename, res_type='kaiser_fast') transformed_test_data = mfcc(mx.nd.array(X1)) output = net(transformed_test_data.reshape((1, -1))) prediction = nd.argmax(output, axis=1) print(filename, " -> ", synset[(int)(prediction.asscalar())])
Thread loop for generating data Parameters ---------- proc_id: int Process id alive: multiprocessing.Value variable for signaling whether process should continue or not queue: multiprocessing.Queue queue for passing data back fn: function function object that returns a sample to be pushed into the queue def _proc_loop(proc_id, alive, queue, fn): """Thread loop for generating data Parameters ---------- proc_id: int Process id alive: multiprocessing.Value variable for signaling whether process should continue or not queue: multiprocessing.Queue queue for passing data back fn: function function object that returns a sample to be pushed into the queue """ print("proc {} started".format(proc_id)) try: while alive.value: data = fn() put_success = False while alive.value and not put_success: try: queue.put(data, timeout=0.5) put_success = True except QFullExcept: # print("Queue Full") pass except KeyboardInterrupt: print("W: interrupt received, stopping process {} ...".format(proc_id)) print("Closing process {}".format(proc_id)) queue.close()
Start processes if not already started def _init_proc(self): """Start processes if not already started""" if not self.proc: self.proc = [ mp.Process(target=self._proc_loop, args=(i, self.alive, self.queue, self.fn)) for i in range(self.num_proc) ] self.alive.value = True for p in self.proc: p.start()
Resets the generator by stopping all processes def reset(self): """Resets the generator by stopping all processes""" self.alive.value = False qsize = 0 try: while True: self.queue.get(timeout=0.1) qsize += 1 except QEmptyExcept: pass print("Queue size on reset: {}".format(qsize)) for i, p in enumerate(self.proc): p.join() self.proc.clear()
Create a base class with a metaclass. def with_metaclass(meta, *bases): """Create a base class with a metaclass.""" # This requires a bit of explanation: the basic idea is to make a dummy # metaclass for one level of class instantiation that replaces itself with # the actual metaclass. class metaclass(type): def __new__(cls, name, this_bases, d): return meta(name, bases, d) @classmethod def __prepare__(cls, name, this_bases): return meta.__prepare__(name, bases) return type.__new__(metaclass, 'temporary_class', (), {})
Load library by searching possible path. def _load_lib(): """Load library by searching possible path.""" lib_path = libinfo.find_lib_path() lib = ctypes.CDLL(lib_path[0], ctypes.RTLD_LOCAL) # DMatrix functions lib.MXGetLastError.restype = ctypes.c_char_p return lib
Create ctypes array from a Python array. Parameters ---------- ctype : ctypes data type Data type of the array we want to convert to, such as mx_float. values : tuple or list Data content. Returns ------- out : ctypes array Created ctypes array. Examples -------- >>> x = mx.base.c_array(mx.base.mx_float, [1, 2, 3]) >>> print len(x) 3 >>> x[1] 2.0 def c_array(ctype, values): """Create ctypes array from a Python array. Parameters ---------- ctype : ctypes data type Data type of the array we want to convert to, such as mx_float. values : tuple or list Data content. Returns ------- out : ctypes array Created ctypes array. Examples -------- >>> x = mx.base.c_array(mx.base.mx_float, [1, 2, 3]) >>> print len(x) 3 >>> x[1] 2.0 """ out = (ctype * len(values))() out[:] = values return out
Create ctypes const void ** from a list of MXNet objects with handles. Parameters ---------- objs : list of NDArray/Symbol. MXNet objects. Returns ------- (ctypes.c_void_p * len(objs)) A void ** pointer that can be passed to C API. def c_handle_array(objs): """Create ctypes const void ** from a list of MXNet objects with handles. Parameters ---------- objs : list of NDArray/Symbol. MXNet objects. Returns ------- (ctypes.c_void_p * len(objs)) A void ** pointer that can be passed to C API. """ arr = (ctypes.c_void_p * len(objs))() arr[:] = [o.handle for o in objs] return arr
Convert a ctypes pointer to a numpy array. The resulting NumPy array shares the memory with the pointer. Parameters ---------- cptr : ctypes.POINTER(mx_float) pointer to the memory region shape : tuple Shape of target `NDArray`. Returns ------- out : numpy_array A numpy array : numpy array. def ctypes2numpy_shared(cptr, shape): """Convert a ctypes pointer to a numpy array. The resulting NumPy array shares the memory with the pointer. Parameters ---------- cptr : ctypes.POINTER(mx_float) pointer to the memory region shape : tuple Shape of target `NDArray`. Returns ------- out : numpy_array A numpy array : numpy array. """ if not isinstance(cptr, ctypes.POINTER(mx_float)): raise RuntimeError('expected float pointer') size = 1 for s in shape: size *= s dbuffer = (mx_float * size).from_address(ctypes.addressof(cptr.contents)) return _np.frombuffer(dbuffer, dtype=_np.float32).reshape(shape)
Build argument docs in python style. arg_names : list of str Argument names. arg_types : list of str Argument type information. arg_descs : list of str Argument description information. remove_dup : boolean, optional Whether remove duplication or not. Returns ------- docstr : str Python docstring of parameter sections. def build_param_doc(arg_names, arg_types, arg_descs, remove_dup=True): """Build argument docs in python style. arg_names : list of str Argument names. arg_types : list of str Argument type information. arg_descs : list of str Argument description information. remove_dup : boolean, optional Whether remove duplication or not. Returns ------- docstr : str Python docstring of parameter sections. """ param_keys = set() param_str = [] for key, type_info, desc in zip(arg_names, arg_types, arg_descs): if key in param_keys and remove_dup: continue if key == 'num_args': continue param_keys.add(key) ret = '%s : %s' % (key, type_info) if len(desc) != 0: ret += '\n ' + desc param_str.append(ret) doc_str = ('Parameters\n' + '----------\n' + '%s\n') doc_str = doc_str % ('\n'.join(param_str)) return doc_str
Append the definition position to each function contained in module. Examples -------- # Put the following codes at the end of a file add_fileline_to_docstring(__name__) def add_fileline_to_docstring(module, incursive=True): """Append the definition position to each function contained in module. Examples -------- # Put the following codes at the end of a file add_fileline_to_docstring(__name__) """ def _add_fileline(obj): """Add fileinto to a object. """ if obj.__doc__ is None or 'From:' in obj.__doc__: return fname = inspect.getsourcefile(obj) if fname is None: return try: line = inspect.getsourcelines(obj)[-1] except IOError: return obj.__doc__ += '\n\nFrom:%s:%d' % (fname, line) if isinstance(module, str): module = sys.modules[module] for _, obj in inspect.getmembers(module): if inspect.isbuiltin(obj): continue if inspect.isfunction(obj): _add_fileline(obj) if inspect.ismethod(obj): _add_fileline(obj.__func__) if inspect.isclass(obj) and incursive: add_fileline_to_docstring(obj, False)
Registers op functions created by `make_op_func` under `root_namespace.module_name.[submodule_name]`, where `submodule_name` is one of `_OP_SUBMODULE_NAME_LIST`. Parameters ---------- root_namespace : str Top level module name, `mxnet` in the current cases. module_name : str Second level module name, `ndarray` and `symbol` in the current cases. make_op_func : function Function for creating op functions for `ndarray` and `symbol` modules. def _init_op_module(root_namespace, module_name, make_op_func): """ Registers op functions created by `make_op_func` under `root_namespace.module_name.[submodule_name]`, where `submodule_name` is one of `_OP_SUBMODULE_NAME_LIST`. Parameters ---------- root_namespace : str Top level module name, `mxnet` in the current cases. module_name : str Second level module name, `ndarray` and `symbol` in the current cases. make_op_func : function Function for creating op functions for `ndarray` and `symbol` modules. """ plist = ctypes.POINTER(ctypes.c_char_p)() size = ctypes.c_uint() check_call(_LIB.MXListAllOpNames(ctypes.byref(size), ctypes.byref(plist))) op_names = [] for i in range(size.value): op_names.append(py_str(plist[i])) module_op = sys.modules["%s.%s.op" % (root_namespace, module_name)] module_internal = sys.modules["%s.%s._internal" % (root_namespace, module_name)] # contrib module in the old format (deprecated) # kept here for backward compatibility # use mx.nd.contrib or mx.sym.contrib from now on contrib_module_name_old = "%s.contrib.%s" % (root_namespace, module_name) contrib_module_old = sys.modules[contrib_module_name_old] submodule_dict = {} for op_name_prefix in _OP_NAME_PREFIX_LIST: submodule_dict[op_name_prefix] =\ sys.modules["%s.%s.%s" % (root_namespace, module_name, op_name_prefix[1:-1])] for name in op_names: hdl = OpHandle() check_call(_LIB.NNGetOpHandle(c_str(name), ctypes.byref(hdl))) op_name_prefix = _get_op_name_prefix(name) module_name_local = module_name if len(op_name_prefix) > 0: if op_name_prefix != '_random_' or name.endswith('_like'): func_name = name[len(op_name_prefix):] cur_module = submodule_dict[op_name_prefix] module_name_local = "%s.%s.%s" % (root_namespace, module_name, op_name_prefix[1:-1]) else: func_name = name cur_module = module_internal elif name.startswith('_'): func_name = name cur_module = module_internal else: func_name = name cur_module = module_op function = make_op_func(hdl, name, func_name) function.__module__ = module_name_local setattr(cur_module, function.__name__, function) cur_module.__all__.append(function.__name__) if op_name_prefix == '_contrib_': hdl = OpHandle() check_call(_LIB.NNGetOpHandle(c_str(name), ctypes.byref(hdl))) func_name = name[len(op_name_prefix):] function = make_op_func(hdl, name, func_name) function.__module__ = contrib_module_name_old setattr(contrib_module_old, function.__name__, function) contrib_module_old.__all__.append(function.__name__)
Generate op functions created by `op_code_gen_func` and write to the source file of `root_namespace.module_name.[submodule_name]`, where `submodule_name` is one of `_OP_SUBMODULE_NAME_LIST`. Parameters ---------- root_namespace : str Top level module name, `mxnet` in the current cases. module_name : str Second level module name, `ndarray` and `symbol` in the current cases. op_code_gen_func : function Function for creating op functions for `ndarray` and `symbol` modules. def _generate_op_module_signature(root_namespace, module_name, op_code_gen_func): """ Generate op functions created by `op_code_gen_func` and write to the source file of `root_namespace.module_name.[submodule_name]`, where `submodule_name` is one of `_OP_SUBMODULE_NAME_LIST`. Parameters ---------- root_namespace : str Top level module name, `mxnet` in the current cases. module_name : str Second level module name, `ndarray` and `symbol` in the current cases. op_code_gen_func : function Function for creating op functions for `ndarray` and `symbol` modules. """ def get_module_file(module_name): """Return the generated module file based on module name.""" path = os.path.dirname(__file__) module_path = module_name.split('.') module_path[-1] = 'gen_' + module_path[-1] file_name = os.path.join(path, '..', *module_path) + '.py' module_file = open(file_name, 'w') dependencies = {'symbol': ['from ._internal import SymbolBase', 'from ..base import _Null'], 'ndarray': ['from ._internal import NDArrayBase', 'from ..base import _Null']} module_file.write('# File content is auto-generated. Do not modify.' + os.linesep) module_file.write('# pylint: skip-file' + os.linesep) module_file.write(os.linesep.join(dependencies[module_name.split('.')[1]])) return module_file def write_all_str(module_file, module_all_list): """Write the proper __all__ based on available operators.""" module_file.write(os.linesep) module_file.write(os.linesep) all_str = '__all__ = [' + ', '.join(["'%s'"%s for s in module_all_list]) + ']' module_file.write(all_str) plist = ctypes.POINTER(ctypes.c_char_p)() size = ctypes.c_uint() check_call(_LIB.MXListAllOpNames(ctypes.byref(size), ctypes.byref(plist))) op_names = [] for i in range(size.value): op_names.append(py_str(plist[i])) module_op_file = get_module_file("%s.%s.op" % (root_namespace, module_name)) module_op_all = [] module_internal_file = get_module_file("%s.%s._internal"%(root_namespace, module_name)) module_internal_all = [] submodule_dict = {} for op_name_prefix in _OP_NAME_PREFIX_LIST: submodule_dict[op_name_prefix] =\ (get_module_file("%s.%s.%s" % (root_namespace, module_name, op_name_prefix[1:-1])), []) for name in op_names: hdl = OpHandle() check_call(_LIB.NNGetOpHandle(c_str(name), ctypes.byref(hdl))) op_name_prefix = _get_op_name_prefix(name) if len(op_name_prefix) > 0: func_name = name[len(op_name_prefix):] cur_module_file, cur_module_all = submodule_dict[op_name_prefix] elif name.startswith('_'): func_name = name cur_module_file = module_internal_file cur_module_all = module_internal_all else: func_name = name cur_module_file = module_op_file cur_module_all = module_op_all code, _ = op_code_gen_func(hdl, name, func_name, True) cur_module_file.write(os.linesep) cur_module_file.write(code) cur_module_all.append(func_name) for (submodule_f, submodule_all) in submodule_dict.values(): write_all_str(submodule_f, submodule_all) submodule_f.close() write_all_str(module_op_file, module_op_all) module_op_file.close() write_all_str(module_internal_file, module_internal_all) module_internal_file.close()
Turns on/off NumPy compatibility. NumPy-compatibility is turned off by default in backend. Parameters ---------- active : bool Indicates whether to turn on/off NumPy compatibility. Returns ------- A bool value indicating the previous state of NumPy compatibility. def set_np_compat(active): """ Turns on/off NumPy compatibility. NumPy-compatibility is turned off by default in backend. Parameters ---------- active : bool Indicates whether to turn on/off NumPy compatibility. Returns ------- A bool value indicating the previous state of NumPy compatibility. """ prev = ctypes.c_int() check_call(_LIB.MXSetIsNumpyCompatible(ctypes.c_int(active), ctypes.byref(prev))) return bool(prev.value)
Checks whether the NumPy compatibility is currently turned on. NumPy-compatibility is turned off by default in backend. Returns ------- A bool value indicating whether the NumPy compatibility is currently on. def is_np_compat(): """ Checks whether the NumPy compatibility is currently turned on. NumPy-compatibility is turned off by default in backend. Returns ------- A bool value indicating whether the NumPy compatibility is currently on. """ curr = ctypes.c_bool() check_call(_LIB.MXIsNumpyCompatible(ctypes.byref(curr))) return curr.value
Wraps a function with an activated NumPy-compatibility scope. This ensures that the execution of the function is guaranteed with NumPy compatible semantics, such as zero-dim and zero size tensors. Example:: import mxnet as mx @mx.use_np_compat def scalar_one(): return mx.nd.ones(()) print(scalar_one()) Parameters ---------- func : a user-provided callable function to be scoped by the NumPy compatibility state. Returns ------- Function A function for wrapping the user functions in the NumPy compatibility scope. def use_np_compat(func): """Wraps a function with an activated NumPy-compatibility scope. This ensures that the execution of the function is guaranteed with NumPy compatible semantics, such as zero-dim and zero size tensors. Example:: import mxnet as mx @mx.use_np_compat def scalar_one(): return mx.nd.ones(()) print(scalar_one()) Parameters ---------- func : a user-provided callable function to be scoped by the NumPy compatibility state. Returns ------- Function A function for wrapping the user functions in the NumPy compatibility scope. """ @wraps(func) def _with_np_compat(*args, **kwargs): with np_compat(active=True): return func(*args, **kwargs) return _with_np_compat
computes the root relative squared error (condensed using standard deviation formula) def rse(label, pred): """computes the root relative squared error (condensed using standard deviation formula)""" numerator = np.sqrt(np.mean(np.square(label - pred), axis = None)) denominator = np.std(label, axis = None) return numerator / denominator
computes the relative absolute error (condensed using standard deviation formula) def rae(label, pred): """computes the relative absolute error (condensed using standard deviation formula)""" numerator = np.mean(np.abs(label - pred), axis=None) denominator = np.mean(np.abs(label - np.mean(label, axis=None)), axis=None) return numerator / denominator
computes the empirical correlation coefficient def corr(label, pred): """computes the empirical correlation coefficient""" numerator1 = label - np.mean(label, axis=0) numerator2 = pred - np.mean(pred, axis = 0) numerator = np.mean(numerator1 * numerator2, axis=0) denominator = np.std(label, axis=0) * np.std(pred, axis=0) return np.mean(numerator / denominator)
:return: mxnet metric object def get_custom_metrics(): """ :return: mxnet metric object """ _rse = mx.metric.create(rse) _rae = mx.metric.create(rae) _corr = mx.metric.create(corr) return mx.metric.create([_rae, _rse, _corr])
Get input size def _get_input(proto): """Get input size """ layer = caffe_parser.get_layers(proto) if len(proto.input_dim) > 0: input_dim = proto.input_dim elif len(proto.input_shape) > 0: input_dim = proto.input_shape[0].dim elif layer[0].type == "Input": input_dim = layer[0].input_param.shape[0].dim layer.pop(0) else: raise ValueError('Cannot find input size') assert layer[0].type != "Input", 'only support single input' # We assume the first bottom blob of first layer is the output from data layer input_name = layer[0].bottom[0] return input_name, input_dim, layer
Convert convolution layer parameter from Caffe to MXNet def _convert_conv_param(param): """ Convert convolution layer parameter from Caffe to MXNet """ param_string = "num_filter=%d" % param.num_output pad_w = 0 pad_h = 0 if isinstance(param.pad, int): pad = param.pad param_string += ", pad=(%d, %d)" % (pad, pad) else: if len(param.pad) > 0: pad = param.pad[0] param_string += ", pad=(%d, %d)" % (pad, pad) else: if isinstance(param.pad_w, int): pad_w = param.pad_w if isinstance(param.pad_h, int): pad_h = param.pad_h param_string += ", pad=(%d, %d)" % (pad_h, pad_w) if isinstance(param.kernel_size, int): kernel_size = param.kernel_size param_string += ", kernel=(%d,%d)" % (kernel_size, kernel_size) else: if len(param.kernel_size) > 0: kernel_size = param.kernel_size[0] param_string += ", kernel=(%d,%d)" % (kernel_size, kernel_size) else: assert isinstance(param.kernel_w, int) kernel_w = param.kernel_w assert isinstance(param.kernel_h, int) kernel_h = param.kernel_h param_string += ", kernel=(%d,%d)" % (kernel_h, kernel_w) stride = 1 if isinstance(param.stride, int): stride = param.stride else: stride = 1 if len(param.stride) == 0 else param.stride[0] param_string += ", stride=(%d,%d)" % (stride, stride) dilate = 1 if hasattr(param, 'dilation'): if isinstance(param.dilation, int): dilate = param.dilation else: dilate = 1 if len(param.dilation) == 0 else param.dilation[0] param_string += ", no_bias=%s" % (not param.bias_term) # deal with dilation. Won't be in deconvolution if dilate > 1: param_string += ", dilate=(%d, %d)" % (dilate, dilate) if isinstance(param.group, int): if param.group != 1: param_string += ", num_group=%d" % param.group return param_string
Convert the pooling layer parameter def _convert_pooling_param(param): """Convert the pooling layer parameter """ param_string = "pooling_convention='full', " if param.global_pooling: param_string += "global_pool=True, kernel=(1,1)" else: param_string += "pad=(%d,%d), kernel=(%d,%d), stride=(%d,%d)" % ( param.pad, param.pad, param.kernel_size, param.kernel_size, param.stride, param.stride) if param.pool == 0: param_string += ", pool_type='max'" elif param.pool == 1: param_string += ", pool_type='avg'" else: raise ValueError("Unknown Pooling Method!") return param_string
Parse Caffe prototxt into symbol string def _parse_proto(prototxt_fname): """Parse Caffe prototxt into symbol string """ proto = caffe_parser.read_prototxt(prototxt_fname) # process data layer input_name, input_dim, layers = _get_input(proto) # only support single input, so always use `data` as the input data mapping = {input_name: 'data'} need_flatten = {input_name: False} symbol_string = "import mxnet as mx\ndata = mx.symbol.Variable(name='data')\n" flatten_count = 0 output_name = "" prev_name = None # convert reset layers one by one for i, layer in enumerate(layers): type_string = '' param_string = '' skip_layer = False bottom_order = [] name = re.sub('[-/]', '_', layer.name) if layer.type == 'Convolution' or layer.type == 4: type_string = 'mx.symbol.Convolution' param_string = _convert_conv_param(layer.convolution_param) need_flatten[name] = True if layer.type == 'Deconvolution' or layer.type == 39: type_string = 'mx.symbol.Deconvolution' param_string = _convert_conv_param(layer.convolution_param) need_flatten[name] = True if layer.type == 'Pooling' or layer.type == 17: type_string = 'mx.symbol.Pooling' param_string = _convert_pooling_param(layer.pooling_param) need_flatten[name] = True if layer.type == 'ReLU' or layer.type == 18: type_string = 'mx.symbol.Activation' param_string = "act_type='relu'" need_flatten[name] = need_flatten[mapping[layer.bottom[0]]] if layer.type == 'TanH' or layer.type == 23: type_string = 'mx.symbol.Activation' param_string = "act_type='tanh'" need_flatten[name] = need_flatten[mapping[layer.bottom[0]]] if layer.type == 'Sigmoid' or layer.type == 19: type_string = 'mx.symbol.Activation' param_string = "act_type='sigmoid'" need_flatten[name] = need_flatten[mapping[layer.bottom[0]]] if layer.type == 'LRN' or layer.type == 15: type_string = 'mx.symbol.LRN' param = layer.lrn_param param_string = "alpha=%f, beta=%f, knorm=%f, nsize=%d" % ( param.alpha, param.beta, param.k, param.local_size) need_flatten[name] = True if layer.type == 'InnerProduct' or layer.type == 14: type_string = 'mx.symbol.FullyConnected' param = layer.inner_product_param param_string = "num_hidden=%d, no_bias=%s" % ( param.num_output, not param.bias_term) need_flatten[name] = False if layer.type == 'Dropout' or layer.type == 6: type_string = 'mx.symbol.Dropout' param = layer.dropout_param param_string = "p=%f" % param.dropout_ratio need_flatten[name] = need_flatten[mapping[layer.bottom[0]]] if layer.type == 'Softmax' or layer.type == 20: if layer.softmax_param.axis == 2: symbol_string += "%s = mx.symbol.transpose(%s, axes=(0,2,1))\n" %\ (mapping[layer.bottom[0]], mapping[layer.bottom[0]]) type_string = 'mx.symbol.SoftmaxActivation' param_string = "mode='channel'" need_flatten[name] = False else: type_string = 'mx.symbol.SoftmaxOutput' if layer.type == 'Flatten' or layer.type == 8: if 'softmax' in layer.bottom[0]: prev_name = re.sub('[-/]', '_', layers[i-1].name) skip_layer = True else: type_string = 'mx.symbol.Flatten' need_flatten[name] = False if layer.type == 'Split' or layer.type == 22: type_string = 'split' # will process later if layer.type == 'Concat' or layer.type == 3: type_string = 'mx.symbol.Concat' need_flatten[name] = True if layer.type == 'Crop': type_string = 'mx.symbol.Crop' need_flatten[name] = True param_string = 'center_crop=True' if layer.type == 'BatchNorm': type_string = 'mx.symbol.BatchNorm' param = layer.batch_norm_param # CuDNN requires eps to be greater than 1e-05 # We compensate for this change in convert_model epsilon = param.eps if (epsilon <= 1e-05): epsilon = 1e-04 # if next layer is scale, don't fix gamma fix_gamma = layers[i+1].type != 'Scale' param_string = 'use_global_stats=%s, fix_gamma=%s, eps=%f' % ( param.use_global_stats, fix_gamma, epsilon) need_flatten[name] = need_flatten[mapping[layer.bottom[0]]] if layer.type == 'Scale': assert layers[i-1].type == 'BatchNorm' need_flatten[name] = need_flatten[mapping[layer.bottom[0]]] skip_layer = True prev_name = re.sub('[-/]', '_', layers[i-1].name) if layer.type == 'PReLU': type_string = 'mx.symbol.LeakyReLU' param = layer.prelu_param param_string = "act_type='prelu', slope=%f" % param.filler.value need_flatten[name] = need_flatten[mapping[layer.bottom[0]]] if layer.type == 'Eltwise': type_string = 'mx.symbol.broadcast_add' param_string = "" need_flatten[name] = False if layer.type == 'Reshape': type_string = 'mx.symbol.Reshape' param = layer.reshape_param param_string = 'shape=(' + ','.join([str(x) for x in list(param.shape.dim)]) + ')' need_flatten[name] = True if layer.type == 'AbsVal': type_string = 'mx.symbol.abs' need_flatten[name] = need_flatten[mapping[layer.bottom[0]]] if layer.type == 'Normalize': bottom = re.sub('[-/]', '_', layer.bottom[0]) conv_layer = _find_layer(layers, bottom) assert conv_layer is not None param = layer.norm_param assert not param.across_spatial and not param.channel_shared assert param.scale_filler.type == 'constant' if conv_layer.type == 'Convolution': scale_name = "%s_scale" % name symbol_string += "%s=mx.sym.Variable(name='%s', shape=(1, %d, 1, 1), init=mx.init.Constant(%f))\n" % \ (scale_name, scale_name, conv_layer.convolution_param.num_output, param.scale_filler.value) symbol_string += "%s=mx.symbol.L2Normalization(name='%s', data=%s, mode='channel')\n" %\ (name, name, mapping[layer.bottom[0]]) symbol_string += "%s=mx.symbol.broadcast_mul(lhs=%s, rhs=%s)\n" %\ (name, scale_name, name) type_string = 'split' need_flatten[name] = True else: raise ValueError('Unknown/Invalid normalize layer!') if layer.type == 'Permute': type_string = 'mx.symbol.transpose' param_string = "axes=(%s)" % (','.join([str(x) for x in layer.permute_param.order])) need_flatten[name] = True from_name = '' if layer.type == 'PriorBox': param = layer.prior_box_param if layer.bottom[0] == 'data': bottom_order = [1] else: bottom_order = [0] try: import math min_size = param.min_size[0] / input_dim[2] max_size = math.sqrt(param.min_size[0] * param.max_size[0]) / input_dim[2] sizes = '(%f, %f)' %(min_size, max_size) except AttributeError: min_size = param.min_size[0] / input_dim[2] sizes = '(%f)' %(min_size) ars = list(param.aspect_ratio) ratios = [1.] for ar in ars: ratios.append(ar) if param.flip: ratios.append(1. / ar) ratios_string = '(' + ','.join(str(x) for x in ratios) + ')' clip = param.clip if (param.step_h > 0 or param.step_w > 0): step_h = param.step_h step_w = param.step_w elif param.step > 0: step_h = param.step step_w = param.step else: step_h = -1 step_w = -1 finput_dimh = float(input_dim[2]) finput_dimw = float(input_dim[3]) step = '(%f, %f)' % (step_h / finput_dimh, step_w / finput_dimw) assert param.offset == 0.5, "currently only support offset = 0.5" symbol_string += '%s = mx.contrib.symbol.MultiBoxPrior(%s, sizes=%s, ratios=%s, clip=%s, steps=%s, name="%s")\n' % \ (name, mapping[layer.bottom[0]], sizes, ratios_string, clip, step, name) symbol_string += '%s = mx.symbol.Flatten(data=%s)\n' % (name, name) type_string = 'split' need_flatten[name] = False if layer.type == 'DetectionOutput': bottom_order = [1, 0, 2] param = layer.detection_output_param assert param.share_location == True assert param.background_label_id == 0 nms_param = param.nms_param type_string = 'mx.contrib.symbol.MultiBoxDetection' param_string = "nms_threshold=%f, nms_topk=%d, clip=False" % \ (nms_param.nms_threshold, nms_param.top_k) if skip_layer: assert len(layer.bottom) == 1 symbol_string += "%s = %s\n" % (name, prev_name) elif type_string == '': raise ValueError('Unknown layer %s!' % layer.type) elif type_string != 'split': bottom = layer.bottom if param_string != "": param_string = ", " + param_string if len(bottom) == 1: # print(need_flatten) if need_flatten[mapping[bottom[0]]] and type_string == 'mx.symbol.FullyConnected': flatten_name = "flatten_%d" % flatten_count symbol_string += "%s=mx.symbol.Flatten(name='%s', data=%s)\n" % ( flatten_name, flatten_name, mapping[bottom[0]]) flatten_count += 1 need_flatten[flatten_name] = False bottom[0] = flatten_name mapping[bottom[0]] = bottom[0] symbol_string += "%s = %s(name='%s', data=%s %s)\n" % ( name, type_string, name, mapping[bottom[0]], param_string) else: if not bottom_order: bottom_order = range(len(bottom)) symbol_string += "%s = %s(name='%s', *[%s] %s)\n" % \ (name, type_string, name, ','.join([mapping[bottom[x]] for x in bottom_order]), param_string) if layer.type == 'Concat' and layer.concat_param.axis == 2: symbol_string += "%s = mx.symbol.Reshape(data=%s, shape=(0, -1, 4), name='%s')\n" %\ (name, name, name) for j in range(len(layer.top)): mapping[layer.top[j]] = name output_name = name return symbol_string, output_name, input_dim
Convert caffe model definition into Symbol Parameters ---------- prototxt_fname : str Filename of the prototxt file Returns ------- Symbol Converted Symbol tuple Input shape def convert_symbol(prototxt_fname): """Convert caffe model definition into Symbol Parameters ---------- prototxt_fname : str Filename of the prototxt file Returns ------- Symbol Converted Symbol tuple Input shape """ sym, output_name, input_dim = _parse_proto(prototxt_fname) exec(sym) # pylint: disable=exec-used _locals = locals() exec("ret = " + output_name, globals(), _locals) # pylint: disable=exec-used ret = _locals['ret'] return ret, input_dim
Complete an episode's worth of training for each environment. def train_episode(agent, envs, preprocessors, t_max, render): """Complete an episode's worth of training for each environment.""" num_envs = len(envs) # Buffers to hold trajectories, e.g. `env_xs[i]` will hold the observations # for environment `i`. env_xs, env_as = _2d_list(num_envs), _2d_list(num_envs) env_rs, env_vs = _2d_list(num_envs), _2d_list(num_envs) episode_rs = np.zeros(num_envs, dtype=np.float) for p in preprocessors: p.reset() observations = [p.preprocess(e.reset()) for p, e in zip(preprocessors, envs)] done = np.array([False for _ in range(num_envs)]) all_done = False t = 1 while not all_done: if render: envs[0].render() # NOTE(reed): Reshape to set the data shape. agent.model.reshape([('data', (num_envs, preprocessors[0].obs_size))]) step_xs = np.vstack([o.ravel() for o in observations]) # Get actions and values for all environments in a single forward pass. step_xs_nd = mx.nd.array(step_xs, ctx=agent.ctx) data_batch = mx.io.DataBatch(data=[step_xs_nd], label=None) agent.model.forward(data_batch, is_train=False) _, step_vs, _, step_ps = agent.model.get_outputs() step_ps = step_ps.asnumpy() step_vs = step_vs.asnumpy() step_as = agent.act(step_ps) # Step each environment whose episode has not completed. for i, env in enumerate(envs): if not done[i]: obs, r, done[i], _ = env.step(step_as[i]) # Record the observation, action, value, and reward in the # buffers. env_xs[i].append(step_xs[i].ravel()) env_as[i].append(step_as[i]) env_vs[i].append(step_vs[i][0]) env_rs[i].append(r) episode_rs[i] += r # Add 0 as the state value when done. if done[i]: env_vs[i].append(0.0) else: observations[i] = preprocessors[i].preprocess(obs) # Perform an update every `t_max` steps. if t == t_max: # If the episode has not finished, add current state's value. This # will be used to 'bootstrap' the final return (see Algorithm S3 # in A3C paper). step_xs = np.vstack([o.ravel() for o in observations]) step_xs_nd = mx.nd.array(step_xs, ctx=agent.ctx) data_batch = mx.io.DataBatch(data=[step_xs_nd], label=None) agent.model.forward(data_batch, is_train=False) _, extra_vs, _, _ = agent.model.get_outputs() extra_vs = extra_vs.asnumpy() for i in range(num_envs): if not done[i]: env_vs[i].append(extra_vs[i][0]) # Perform update and clear buffers. env_xs = np.vstack(list(chain.from_iterable(env_xs))) agent.train_step(env_xs, env_as, env_rs, env_vs) env_xs, env_as = _2d_list(num_envs), _2d_list(num_envs) env_rs, env_vs = _2d_list(num_envs), _2d_list(num_envs) t = 0 all_done = np.all(done) t += 1 return episode_rs
parses the trained .caffemodel file filepath: /path/to/trained-model.caffemodel returns: layers def parse_caffemodel(file_path): """ parses the trained .caffemodel file filepath: /path/to/trained-model.caffemodel returns: layers """ f = open(file_path, 'rb') contents = f.read() net_param = caffe_pb2.NetParameter() net_param.ParseFromString(contents) layers = find_layers(net_param) return layers
For a given audio clip, calculate the log of its Fourier Transform Params: audio_clip(str): Path to the audio clip def featurize(self, audio_clip, overwrite=False, save_feature_as_csvfile=False): """ For a given audio clip, calculate the log of its Fourier Transform Params: audio_clip(str): Path to the audio clip """ return spectrogram_from_file( audio_clip, step=self.step, window=self.window, max_freq=self.max_freq, overwrite=overwrite, save_feature_as_csvfile=save_feature_as_csvfile)
Read metadata from the description file (possibly takes long, depending on the filesize) Params: desc_file (str): Path to a JSON-line file that contains labels and paths to the audio files partition (str): One of 'train', 'validation' or 'test' max_duration (float): In seconds, the maximum duration of utterances to train or test on def load_metadata_from_desc_file(self, desc_file, partition='train', max_duration=16.0,): """ Read metadata from the description file (possibly takes long, depending on the filesize) Params: desc_file (str): Path to a JSON-line file that contains labels and paths to the audio files partition (str): One of 'train', 'validation' or 'test' max_duration (float): In seconds, the maximum duration of utterances to train or test on """ logger = logUtil.getlogger() logger.info('Reading description file: {} for partition: {}' .format(desc_file, partition)) audio_paths, durations, texts = [], [], [] with open(desc_file) as json_line_file: for line_num, json_line in enumerate(json_line_file): try: spec = json.loads(json_line) if float(spec['duration']) > max_duration: continue audio_paths.append(spec['key']) durations.append(float(spec['duration'])) texts.append(spec['text']) except Exception as e: # Change to (KeyError, ValueError) or # (KeyError,json.decoder.JSONDecodeError), depending on # json module version logger.warn('Error reading line #{}: {}' .format(line_num, json_line)) logger.warn(str(e)) if partition == 'train': self.count = len(audio_paths) self.train_audio_paths = audio_paths self.train_durations = durations self.train_texts = texts elif partition == 'validation': self.val_audio_paths = audio_paths self.val_durations = durations self.val_texts = texts self.val_count = len(audio_paths) elif partition == 'test': self.test_audio_paths = audio_paths self.test_durations = durations self.test_texts = texts else: raise Exception("Invalid partition to load metadata. " "Must be train/validation/test")
Featurize a minibatch of audio, zero pad them and return a dictionary Params: audio_paths (list(str)): List of paths to audio files texts (list(str)): List of texts corresponding to the audio files Returns: dict: See below for contents def prepare_minibatch(self, audio_paths, texts, overwrite=False, is_bi_graphemes=False, seq_length=-1, save_feature_as_csvfile=False): """ Featurize a minibatch of audio, zero pad them and return a dictionary Params: audio_paths (list(str)): List of paths to audio files texts (list(str)): List of texts corresponding to the audio files Returns: dict: See below for contents """ assert len(audio_paths) == len(texts),\ "Inputs and outputs to the network must be of the same number" # Features is a list of (timesteps, feature_dim) arrays # Calculate the features for each audio clip, as the log of the # Fourier Transform of the audio features = [self.featurize(a, overwrite=overwrite, save_feature_as_csvfile=save_feature_as_csvfile) for a in audio_paths] input_lengths = [f.shape[0] for f in features] feature_dim = features[0].shape[1] mb_size = len(features) # Pad all the inputs so that they are all the same length if seq_length == -1: x = np.zeros((mb_size, self.max_seq_length, feature_dim)) else: x = np.zeros((mb_size, seq_length, feature_dim)) y = np.zeros((mb_size, self.max_label_length)) labelUtil = LabelUtil.getInstance() label_lengths = [] for i in range(mb_size): feat = features[i] feat = self.normalize(feat) # Center using means and std x[i, :feat.shape[0], :] = feat if is_bi_graphemes: label = generate_bi_graphemes_label(texts[i]) label = labelUtil.convert_bi_graphemes_to_num(label) y[i, :len(label)] = label else: label = labelUtil.convert_word_to_num(texts[i]) y[i, :len(texts[i])] = label label_lengths.append(len(label)) return { 'x': x, # (0-padded features of shape(mb_size,timesteps,feat_dim) 'y': y, # list(int) Flattened labels (integer sequences) 'texts': texts, # list(str) Original texts 'input_lengths': input_lengths, # list(int) Length of each input 'label_lengths': label_lengths, # list(int) Length of each label }
Estimate the mean and std of the features from the training set Params: k_samples (int): Use this number of samples for estimation def sample_normalize(self, k_samples=1000, overwrite=False): """ Estimate the mean and std of the features from the training set Params: k_samples (int): Use this number of samples for estimation """ log = logUtil.getlogger() log.info("Calculating mean and std from samples") # if k_samples is negative then it goes through total dataset if k_samples < 0: audio_paths = self.audio_paths # using sample else: k_samples = min(k_samples, len(self.train_audio_paths)) samples = self.rng.sample(self.train_audio_paths, k_samples) audio_paths = samples manager = Manager() return_dict = manager.dict() jobs = [] for threadIndex in range(cpu_count()): proc = Process(target=self.preprocess_sample_normalize, args=(threadIndex, audio_paths, overwrite, return_dict)) jobs.append(proc) proc.start() for proc in jobs: proc.join() feat = np.sum(np.vstack([item['feat'] for item in return_dict.values()]), axis=0) count = sum([item['count'] for item in return_dict.values()]) feat_squared = np.sum(np.vstack([item['feat_squared'] for item in return_dict.values()]), axis=0) self.feats_mean = feat / float(count) self.feats_std = np.sqrt(feat_squared / float(count) - np.square(self.feats_mean)) np.savetxt( generate_file_path(self.save_dir, self.model_name, 'feats_mean'), self.feats_mean) np.savetxt( generate_file_path(self.save_dir, self.model_name, 'feats_std'), self.feats_std) log.info("End calculating mean and std from samples")
GRU Cell symbol Reference: * Chung, Junyoung, et al. "Empirical evaluation of gated recurrent neural networks on sequence modeling." arXiv preprint arXiv:1412.3555 (2014). def gru(num_hidden, indata, prev_state, param, seqidx, layeridx, dropout=0., is_batchnorm=False, gamma=None, beta=None, name=None): """ GRU Cell symbol Reference: * Chung, Junyoung, et al. "Empirical evaluation of gated recurrent neural networks on sequence modeling." arXiv preprint arXiv:1412.3555 (2014). """ if dropout > 0.: indata = mx.sym.Dropout(data=indata, p=dropout) i2h = mx.sym.FullyConnected(data=indata, weight=param.gates_i2h_weight, bias=param.gates_i2h_bias, num_hidden=num_hidden * 2, name="t%d_l%d_gates_i2h" % (seqidx, layeridx)) if is_batchnorm: if name is not None: i2h = batchnorm(net=i2h, gamma=gamma, beta=beta, name="%s_batchnorm" % name) else: i2h = batchnorm(net=i2h, gamma=gamma, beta=beta) h2h = mx.sym.FullyConnected(data=prev_state.h, weight=param.gates_h2h_weight, bias=param.gates_h2h_bias, num_hidden=num_hidden * 2, name="t%d_l%d_gates_h2h" % (seqidx, layeridx)) gates = i2h + h2h slice_gates = mx.sym.SliceChannel(gates, num_outputs=2, name="t%d_l%d_slice" % (seqidx, layeridx)) update_gate = mx.sym.Activation(slice_gates[0], act_type="sigmoid") reset_gate = mx.sym.Activation(slice_gates[1], act_type="sigmoid") # The transform part of GRU is a little magic htrans_i2h = mx.sym.FullyConnected(data=indata, weight=param.trans_i2h_weight, bias=param.trans_i2h_bias, num_hidden=num_hidden, name="t%d_l%d_trans_i2h" % (seqidx, layeridx)) h_after_reset = prev_state.h * reset_gate htrans_h2h = mx.sym.FullyConnected(data=h_after_reset, weight=param.trans_h2h_weight, bias=param.trans_h2h_bias, num_hidden=num_hidden, name="t%d_l%d_trans_h2h" % (seqidx, layeridx)) h_trans = htrans_i2h + htrans_h2h h_trans_active = mx.sym.Activation(h_trans, act_type="tanh") next_h = prev_state.h + update_gate * (h_trans_active - prev_state.h) return GRUState(h=next_h)
save image def save_image(data, epoch, image_size, batch_size, output_dir, padding=2): """ save image """ data = data.asnumpy().transpose((0, 2, 3, 1)) datanp = np.clip( (data - np.min(data))*(255.0/(np.max(data) - np.min(data))), 0, 255).astype(np.uint8) x_dim = min(8, batch_size) y_dim = int(math.ceil(float(batch_size) / x_dim)) height, width = int(image_size + padding), int(image_size + padding) grid = np.zeros((height * y_dim + 1 + padding // 2, width * x_dim + 1 + padding // 2, 3), dtype=np.uint8) k = 0 for y in range(y_dim): for x in range(x_dim): if k >= batch_size: break start_y = y * height + 1 + padding // 2 end_y = start_y + height - padding start_x = x * width + 1 + padding // 2 end_x = start_x + width - padding np.copyto(grid[start_y:end_y, start_x:end_x, :], datanp[k]) k += 1 imageio.imwrite( '{}/fake_samples_epoch_{}.png'.format(output_dir, epoch), grid)
Traverses the root of directory that contains images and generates image list iterator. Parameters ---------- root: string recursive: bool exts: string Returns ------- image iterator that contains all the image under the specified path def list_image(root, recursive, exts): """Traverses the root of directory that contains images and generates image list iterator. Parameters ---------- root: string recursive: bool exts: string Returns ------- image iterator that contains all the image under the specified path """ i = 0 if recursive: cat = {} for path, dirs, files in os.walk(root, followlinks=True): dirs.sort() files.sort() for fname in files: fpath = os.path.join(path, fname) suffix = os.path.splitext(fname)[1].lower() if os.path.isfile(fpath) and (suffix in exts): if path not in cat: cat[path] = len(cat) yield (i, os.path.relpath(fpath, root), cat[path]) i += 1 for k, v in sorted(cat.items(), key=lambda x: x[1]): print(os.path.relpath(k, root), v) else: for fname in sorted(os.listdir(root)): fpath = os.path.join(root, fname) suffix = os.path.splitext(fname)[1].lower() if os.path.isfile(fpath) and (suffix in exts): yield (i, os.path.relpath(fpath, root), 0) i += 1
Hepler function to write image list into the file. The format is as below, integer_image_index \t float_label_index \t path_to_image Note that the blank between number and tab is only used for readability. Parameters ---------- path_out: string image_list: list def write_list(path_out, image_list): """Hepler function to write image list into the file. The format is as below, integer_image_index \t float_label_index \t path_to_image Note that the blank between number and tab is only used for readability. Parameters ---------- path_out: string image_list: list """ with open(path_out, 'w') as fout: for i, item in enumerate(image_list): line = '%d\t' % item[0] for j in item[2:]: line += '%f\t' % j line += '%s\n' % item[1] fout.write(line)
Generates .lst file. Parameters ---------- args: object that contains all the arguments def make_list(args): """Generates .lst file. Parameters ---------- args: object that contains all the arguments """ image_list = list_image(args.root, args.recursive, args.exts) image_list = list(image_list) if args.shuffle is True: random.seed(100) random.shuffle(image_list) N = len(image_list) chunk_size = (N + args.chunks - 1) // args.chunks for i in range(args.chunks): chunk = image_list[i * chunk_size:(i + 1) * chunk_size] if args.chunks > 1: str_chunk = '_%d' % i else: str_chunk = '' sep = int(chunk_size * args.train_ratio) sep_test = int(chunk_size * args.test_ratio) if args.train_ratio == 1.0: write_list(args.prefix + str_chunk + '.lst', chunk) else: if args.test_ratio: write_list(args.prefix + str_chunk + '_test.lst', chunk[:sep_test]) if args.train_ratio + args.test_ratio < 1.0: write_list(args.prefix + str_chunk + '_val.lst', chunk[sep_test + sep:]) write_list(args.prefix + str_chunk + '_train.lst', chunk[sep_test:sep_test + sep])
Reads the .lst file and generates corresponding iterator. Parameters ---------- path_in: string Returns ------- item iterator that contains information in .lst file def read_list(path_in): """Reads the .lst file and generates corresponding iterator. Parameters ---------- path_in: string Returns ------- item iterator that contains information in .lst file """ with open(path_in) as fin: while True: line = fin.readline() if not line: break line = [i.strip() for i in line.strip().split('\t')] line_len = len(line) # check the data format of .lst file if line_len < 3: print('lst should have at least has three parts, but only has %s parts for %s' % (line_len, line)) continue try: item = [int(line[0])] + [line[-1]] + [float(i) for i in line[1:-1]] except Exception as e: print('Parsing lst met error for %s, detail: %s' % (line, e)) continue yield item
Reads, preprocesses, packs the image and put it back in output queue. Parameters ---------- args: object i: int item: list q_out: queue def image_encode(args, i, item, q_out): """Reads, preprocesses, packs the image and put it back in output queue. Parameters ---------- args: object i: int item: list q_out: queue """ fullpath = os.path.join(args.root, item[1]) if len(item) > 3 and args.pack_label: header = mx.recordio.IRHeader(0, item[2:], item[0], 0) else: header = mx.recordio.IRHeader(0, item[2], item[0], 0) if args.pass_through: try: with open(fullpath, 'rb') as fin: img = fin.read() s = mx.recordio.pack(header, img) q_out.put((i, s, item)) except Exception as e: traceback.print_exc() print('pack_img error:', item[1], e) q_out.put((i, None, item)) return try: img = cv2.imread(fullpath, args.color) except: traceback.print_exc() print('imread error trying to load file: %s ' % fullpath) q_out.put((i, None, item)) return if img is None: print('imread read blank (None) image for file: %s' % fullpath) q_out.put((i, None, item)) return if args.center_crop: if img.shape[0] > img.shape[1]: margin = (img.shape[0] - img.shape[1]) // 2 img = img[margin:margin + img.shape[1], :] else: margin = (img.shape[1] - img.shape[0]) // 2 img = img[:, margin:margin + img.shape[0]] if args.resize: if img.shape[0] > img.shape[1]: newsize = (args.resize, img.shape[0] * args.resize // img.shape[1]) else: newsize = (img.shape[1] * args.resize // img.shape[0], args.resize) img = cv2.resize(img, newsize) try: s = mx.recordio.pack_img(header, img, quality=args.quality, img_fmt=args.encoding) q_out.put((i, s, item)) except Exception as e: traceback.print_exc() print('pack_img error on file: %s' % fullpath, e) q_out.put((i, None, item)) return
Function that will be spawned to fetch the image from the input queue and put it back to output queue. Parameters ---------- args: object q_in: queue q_out: queue def read_worker(args, q_in, q_out): """Function that will be spawned to fetch the image from the input queue and put it back to output queue. Parameters ---------- args: object q_in: queue q_out: queue """ while True: deq = q_in.get() if deq is None: break i, item = deq image_encode(args, i, item, q_out)
Function that will be spawned to fetch processed image from the output queue and write to the .rec file. Parameters ---------- q_out: queue fname: string working_dir: string def write_worker(q_out, fname, working_dir): """Function that will be spawned to fetch processed image from the output queue and write to the .rec file. Parameters ---------- q_out: queue fname: string working_dir: string """ pre_time = time.time() count = 0 fname = os.path.basename(fname) fname_rec = os.path.splitext(fname)[0] + '.rec' fname_idx = os.path.splitext(fname)[0] + '.idx' record = mx.recordio.MXIndexedRecordIO(os.path.join(working_dir, fname_idx), os.path.join(working_dir, fname_rec), 'w') buf = {} more = True while more: deq = q_out.get() if deq is not None: i, s, item = deq buf[i] = (s, item) else: more = False while count in buf: s, item = buf[count] del buf[count] if s is not None: record.write_idx(item[0], s) if count % 1000 == 0: cur_time = time.time() print('time:', cur_time - pre_time, ' count:', count) pre_time = cur_time count += 1
Defines all arguments. Returns ------- args object that contains all the params def parse_args(): """Defines all arguments. Returns ------- args object that contains all the params """ parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter, description='Create an image list or \ make a record database by reading from an image list') parser.add_argument('prefix', help='prefix of input/output lst and rec files.') parser.add_argument('root', help='path to folder containing images.') cgroup = parser.add_argument_group('Options for creating image lists') cgroup.add_argument('--list', action='store_true', help='If this is set im2rec will create image list(s) by traversing root folder\ and output to <prefix>.lst.\ Otherwise im2rec will read <prefix>.lst and create a database at <prefix>.rec') cgroup.add_argument('--exts', nargs='+', default=['.jpeg', '.jpg', '.png'], help='list of acceptable image extensions.') cgroup.add_argument('--chunks', type=int, default=1, help='number of chunks.') cgroup.add_argument('--train-ratio', type=float, default=1.0, help='Ratio of images to use for training.') cgroup.add_argument('--test-ratio', type=float, default=0, help='Ratio of images to use for testing.') cgroup.add_argument('--recursive', action='store_true', help='If true recursively walk through subdirs and assign an unique label\ to images in each folder. Otherwise only include images in the root folder\ and give them label 0.') cgroup.add_argument('--no-shuffle', dest='shuffle', action='store_false', help='If this is passed, \ im2rec will not randomize the image order in <prefix>.lst') rgroup = parser.add_argument_group('Options for creating database') rgroup.add_argument('--pass-through', action='store_true', help='whether to skip transformation and save image as is') rgroup.add_argument('--resize', type=int, default=0, help='resize the shorter edge of image to the newsize, original images will\ be packed by default.') rgroup.add_argument('--center-crop', action='store_true', help='specify whether to crop the center image to make it rectangular.') rgroup.add_argument('--quality', type=int, default=95, help='JPEG quality for encoding, 1-100; or PNG compression for encoding, 1-9') rgroup.add_argument('--num-thread', type=int, default=1, help='number of thread to use for encoding. order of images will be different\ from the input list if >1. the input list will be modified to match the\ resulting order.') rgroup.add_argument('--color', type=int, default=1, choices=[-1, 0, 1], help='specify the color mode of the loaded image.\ 1: Loads a color image. Any transparency of image will be neglected. It is the default flag.\ 0: Loads image in grayscale mode.\ -1:Loads image as such including alpha channel.') rgroup.add_argument('--encoding', type=str, default='.jpg', choices=['.jpg', '.png'], help='specify the encoding of the images.') rgroup.add_argument('--pack-label', action='store_true', help='Whether to also pack multi dimensional label in the record file') args = parser.parse_args() args.prefix = os.path.abspath(args.prefix) args.root = os.path.abspath(args.root) return args
Crop and normnalize an image nd array. def transform(data, target_wd, target_ht, is_train, box): """Crop and normnalize an image nd array.""" if box is not None: x, y, w, h = box data = data[y:min(y+h, data.shape[0]), x:min(x+w, data.shape[1])] # Resize to target_wd * target_ht. data = mx.image.imresize(data, target_wd, target_ht) # Normalize in the same way as the pre-trained model. data = data.astype(np.float32) / 255.0 data = (data - mx.nd.array([0.485, 0.456, 0.406])) / mx.nd.array([0.229, 0.224, 0.225]) if is_train: if random.random() < 0.5: data = nd.flip(data, axis=1) data, _ = mx.image.random_crop(data, (224, 224)) else: data, _ = mx.image.center_crop(data, (224, 224)) # Transpose from (target_wd, target_ht, 3) # to (3, target_wd, target_ht). data = nd.transpose(data, (2, 0, 1)) # If image is greyscale, repeat 3 times to get RGB image. if data.shape[0] == 1: data = nd.tile(data, (3, 1, 1)) return data.reshape((1,) + data.shape)
Return training and testing iterator for the CUB200-2011 dataset. def cub200_iterator(data_path, batch_k, batch_size, data_shape): """Return training and testing iterator for the CUB200-2011 dataset.""" return (CUB200Iter(data_path, batch_k, batch_size, data_shape, is_train=True), CUB200Iter(data_path, batch_k, batch_size, data_shape, is_train=False))
Load and transform an image. def get_image(self, img, is_train): """Load and transform an image.""" img_arr = mx.image.imread(img) img_arr = transform(img_arr, 256, 256, is_train, self.boxes[img]) return img_arr
Sample a training batch (data and label). def sample_train_batch(self): """Sample a training batch (data and label).""" batch = [] labels = [] num_groups = self.batch_size // self.batch_k # For CUB200, we use the first 100 classes for training. sampled_classes = np.random.choice(100, num_groups, replace=False) for i in range(num_groups): img_fnames = np.random.choice(self.train_image_files[sampled_classes[i]], self.batch_k, replace=False) batch += [self.get_image(img_fname, is_train=True) for img_fname in img_fnames] labels += [sampled_classes[i] for _ in range(self.batch_k)] return nd.concatenate(batch, axis=0), labels
Return a batch. def next(self): """Return a batch.""" if self.is_train: data, labels = self.sample_train_batch() else: if self.test_count * self.batch_size < len(self.test_image_files): data, labels = self.get_test_batch() self.test_count += 1 else: self.test_count = 0 raise StopIteration return mx.io.DataBatch(data=[data], label=[labels])
Load mnist dataset def load_mnist(training_num=50000): """Load mnist dataset""" data_path = os.path.join(os.path.dirname(os.path.realpath('__file__')), 'mnist.npz') if not os.path.isfile(data_path): from six.moves import urllib origin = ( 'https://github.com/sxjscience/mxnet/raw/master/example/bayesian-methods/mnist.npz' ) print('Downloading data from %s to %s' % (origin, data_path)) ctx = ssl._create_unverified_context() with urllib.request.urlopen(origin, context=ctx) as u, open(data_path, 'wb') as f: f.write(u.read()) print('Done!') dat = numpy.load(data_path) X = (dat['X'][:training_num] / 126.0).astype('float32') Y = dat['Y'][:training_num] X_test = (dat['X_test'] / 126.0).astype('float32') Y_test = dat['Y_test'] Y = Y.reshape((Y.shape[0],)) Y_test = Y_test.reshape((Y_test.shape[0],)) return X, Y, X_test, Y_test
Check the library for compile-time features. The list of features are maintained in libinfo.h and libinfo.cc Returns ------- list List of :class:`.Feature` objects def feature_list(): """ Check the library for compile-time features. The list of features are maintained in libinfo.h and libinfo.cc Returns ------- list List of :class:`.Feature` objects """ lib_features_c_array = ctypes.POINTER(Feature)() lib_features_size = ctypes.c_size_t() check_call(_LIB.MXLibInfoFeatures(ctypes.byref(lib_features_c_array), ctypes.byref(lib_features_size))) features = [lib_features_c_array[i] for i in range(lib_features_size.value)] return features
Check for a particular feature by name Parameters ---------- feature_name: str The name of a valid feature as string for example 'CUDA' Returns ------- Boolean True if it's enabled, False if it's disabled, RuntimeError if the feature is not known def is_enabled(self, feature_name): """ Check for a particular feature by name Parameters ---------- feature_name: str The name of a valid feature as string for example 'CUDA' Returns ------- Boolean True if it's enabled, False if it's disabled, RuntimeError if the feature is not known """ feature_name = feature_name.upper() if feature_name not in self: raise RuntimeError("Feature '{}' is unknown, known features are: {}".format( feature_name, list(self.keys()))) return self[feature_name].enabled
make a directory to store all caches Returns: --------- cache path def cache_path(self): """ make a directory to store all caches Returns: --------- cache path """ cache_path = os.path.join(os.path.dirname(__file__), '..', 'cache') if not os.path.exists(cache_path): os.mkdir(cache_path) return cache_path
find out which indexes correspond to given image set (train or val) Parameters: ---------- shuffle : boolean whether to shuffle the image list Returns: ---------- entire list of images specified in the setting def _load_image_set_index(self, shuffle): """ find out which indexes correspond to given image set (train or val) Parameters: ---------- shuffle : boolean whether to shuffle the image list Returns: ---------- entire list of images specified in the setting """ image_set_index_file = os.path.join(self.data_path, 'ImageSets', 'Main', self.image_set + '.txt') assert os.path.exists(image_set_index_file), 'Path does not exist: {}'.format(image_set_index_file) with open(image_set_index_file) as f: image_set_index = [x.strip() for x in f.readlines()] if shuffle: np.random.shuffle(image_set_index) return image_set_index
given image index, find out full path Parameters: ---------- index: int index of a specific image Returns: ---------- full path of this image def image_path_from_index(self, index): """ given image index, find out full path Parameters: ---------- index: int index of a specific image Returns: ---------- full path of this image """ assert self.image_set_index is not None, "Dataset not initialized" name = self.image_set_index[index] image_file = os.path.join(self.data_path, 'JPEGImages', name + self.extension) assert os.path.exists(image_file), 'Path does not exist: {}'.format(image_file) return image_file
given image index, find out annotation path Parameters: ---------- index: int index of a specific image Returns: ---------- full path of annotation file def _label_path_from_index(self, index): """ given image index, find out annotation path Parameters: ---------- index: int index of a specific image Returns: ---------- full path of annotation file """ label_file = os.path.join(self.data_path, 'Annotations', index + '.xml') assert os.path.exists(label_file), 'Path does not exist: {}'.format(label_file) return label_file
preprocess all ground-truths Returns: ---------- labels packed in [num_images x max_num_objects x 5] tensor def _load_image_labels(self): """ preprocess all ground-truths Returns: ---------- labels packed in [num_images x max_num_objects x 5] tensor """ temp = [] # load ground-truth from xml annotations for idx in self.image_set_index: label_file = self._label_path_from_index(idx) tree = ET.parse(label_file) root = tree.getroot() size = root.find('size') width = float(size.find('width').text) height = float(size.find('height').text) label = [] for obj in root.iter('object'): difficult = int(obj.find('difficult').text) # if not self.config['use_difficult'] and difficult == 1: # continue cls_name = obj.find('name').text if cls_name not in self.classes: continue cls_id = self.classes.index(cls_name) xml_box = obj.find('bndbox') xmin = float(xml_box.find('xmin').text) / width ymin = float(xml_box.find('ymin').text) / height xmax = float(xml_box.find('xmax').text) / width ymax = float(xml_box.find('ymax').text) / height label.append([cls_id, xmin, ymin, xmax, ymax, difficult]) temp.append(np.array(label)) return temp
top level evaluations Parameters: ---------- detections: list result list, each entry is a matrix of detections Returns: ---------- None def evaluate_detections(self, detections): """ top level evaluations Parameters: ---------- detections: list result list, each entry is a matrix of detections Returns: ---------- None """ # make all these folders for results result_dir = os.path.join(self.devkit_path, 'results') if not os.path.exists(result_dir): os.mkdir(result_dir) year_folder = os.path.join(self.devkit_path, 'results', 'VOC' + self.year) if not os.path.exists(year_folder): os.mkdir(year_folder) res_file_folder = os.path.join(self.devkit_path, 'results', 'VOC' + self.year, 'Main') if not os.path.exists(res_file_folder): os.mkdir(res_file_folder) self.write_pascal_results(detections) self.do_python_eval()
this is a template VOCdevkit/results/VOC2007/Main/<comp_id>_det_test_aeroplane.txt Returns: ---------- a string template def get_result_file_template(self): """ this is a template VOCdevkit/results/VOC2007/Main/<comp_id>_det_test_aeroplane.txt Returns: ---------- a string template """ res_file_folder = os.path.join(self.devkit_path, 'results', 'VOC' + self.year, 'Main') comp_id = self.config['comp_id'] filename = comp_id + '_det_' + self.image_set + '_{:s}.txt' path = os.path.join(res_file_folder, filename) return path
write results files in pascal devkit path Parameters: ---------- all_boxes: list boxes to be processed [bbox, confidence] Returns: ---------- None def write_pascal_results(self, all_boxes): """ write results files in pascal devkit path Parameters: ---------- all_boxes: list boxes to be processed [bbox, confidence] Returns: ---------- None """ for cls_ind, cls in enumerate(self.classes): print('Writing {} VOC results file'.format(cls)) filename = self.get_result_file_template().format(cls) with open(filename, 'wt') as f: for im_ind, index in enumerate(self.image_set_index): dets = all_boxes[im_ind] if dets.shape[0] < 1: continue h, w = self._get_imsize(self.image_path_from_index(im_ind)) # the VOCdevkit expects 1-based indices for k in range(dets.shape[0]): if (int(dets[k, 0]) == cls_ind): f.write('{:s} {:.3f} {:.1f} {:.1f} {:.1f} {:.1f}\n'. format(index, dets[k, 1], int(dets[k, 2] * w) + 1, int(dets[k, 3] * h) + 1, int(dets[k, 4] * w) + 1, int(dets[k, 5] * h) + 1))
python evaluation wrapper Returns: ---------- None def do_python_eval(self): """ python evaluation wrapper Returns: ---------- None """ annopath = os.path.join(self.data_path, 'Annotations', '{:s}.xml') imageset_file = os.path.join(self.data_path, 'ImageSets', 'Main', self.image_set + '.txt') cache_dir = os.path.join(self.cache_path, self.name) aps = [] # The PASCAL VOC metric changed in 2010 use_07_metric = True if int(self.year) < 2010 else False print('VOC07 metric? ' + ('Y' if use_07_metric else 'No')) for cls_ind, cls in enumerate(self.classes): filename = self.get_result_file_template().format(cls) rec, prec, ap = voc_eval(filename, annopath, imageset_file, cls, cache_dir, ovthresh=0.5, use_07_metric=use_07_metric) aps += [ap] print('AP for {} = {:.4f}'.format(cls, ap)) print('Mean AP = {:.4f}'.format(np.mean(aps)))
get image size info Returns: ---------- tuple of (height, width) def _get_imsize(self, im_name): """ get image size info Returns: ---------- tuple of (height, width) """ img = cv2.imread(im_name) return (img.shape[0], img.shape[1])
parser : argparse.ArgumentParser return a parser added with args required by fit def add_fit_args(parser): """ parser : argparse.ArgumentParser return a parser added with args required by fit """ train = parser.add_argument_group('Training', 'model training') train.add_argument('--network', type=str, help='the neural network to use') train.add_argument('--num-layers', type=int, help='number of layers in the neural network, \ required by some networks such as resnet') train.add_argument('--gpus', type=str, help='list of gpus to run, e.g. 0 or 0,2,5. empty means using cpu') train.add_argument('--kv-store', type=str, default='device', help='key-value store type') train.add_argument('--num-epochs', type=int, default=100, help='max num of epochs') train.add_argument('--lr', type=float, default=0.1, help='initial learning rate') train.add_argument('--lr-factor', type=float, default=0.1, help='the ratio to reduce lr on each step') train.add_argument('--lr-step-epochs', type=str, help='the epochs to reduce the lr, e.g. 30,60') train.add_argument('--initializer', type=str, default='default', help='the initializer type') train.add_argument('--optimizer', type=str, default='sgd', help='the optimizer type') train.add_argument('--mom', type=float, default=0.9, help='momentum for sgd') train.add_argument('--wd', type=float, default=0.0001, help='weight decay for sgd') train.add_argument('--batch-size', type=int, default=128, help='the batch size') train.add_argument('--disp-batches', type=int, default=20, help='show progress for every n batches') train.add_argument('--model-prefix', type=str, help='model prefix') train.add_argument('--save-period', type=int, default=1, help='params saving period') parser.add_argument('--monitor', dest='monitor', type=int, default=0, help='log network parameters every N iters if larger than 0') train.add_argument('--load-epoch', type=int, help='load the model on an epoch using the model-load-prefix') train.add_argument('--top-k', type=int, default=0, help='report the top-k accuracy. 0 means no report.') train.add_argument('--loss', type=str, default='', help='show the cross-entropy or nll loss. ce strands for cross-entropy, nll-loss stands for likelihood loss') train.add_argument('--test-io', type=int, default=0, help='1 means test reading speed without training') train.add_argument('--dtype', type=str, default='float32', help='precision: float32 or float16') train.add_argument('--gc-type', type=str, default='none', help='type of gradient compression to use, \ takes `2bit` or `none` for now') train.add_argument('--gc-threshold', type=float, default=0.5, help='threshold for 2bit gradient compression') # additional parameters for large batch sgd train.add_argument('--macrobatch-size', type=int, default=0, help='distributed effective batch size') train.add_argument('--warmup-epochs', type=int, default=5, help='the epochs to ramp-up lr to scaled large-batch value') train.add_argument('--warmup-strategy', type=str, default='linear', help='the ramping-up strategy for large batch sgd') train.add_argument('--profile-worker-suffix', type=str, default='', help='profile workers actions into this file. During distributed training\ filename saved will be rank1_ followed by this suffix') train.add_argument('--profile-server-suffix', type=str, default='', help='profile server actions into a file with name like rank1_ followed by this suffix \ during distributed training') return train
train a model args : argparse returns network : the symbol definition of the nerual network data_loader : function that returns the train and val data iterators def fit(args, network, data_loader, **kwargs): """ train a model args : argparse returns network : the symbol definition of the nerual network data_loader : function that returns the train and val data iterators """ # kvstore kv = mx.kvstore.create(args.kv_store) if args.gc_type != 'none': kv.set_gradient_compression({'type': args.gc_type, 'threshold': args.gc_threshold}) if args.profile_server_suffix: mx.profiler.set_config(filename=args.profile_server_suffix, profile_all=True, profile_process='server') mx.profiler.set_state(state='run', profile_process='server') if args.profile_worker_suffix: if kv.num_workers > 1: filename = 'rank' + str(kv.rank) + '_' + args.profile_worker_suffix else: filename = args.profile_worker_suffix mx.profiler.set_config(filename=filename, profile_all=True, profile_process='worker') mx.profiler.set_state(state='run', profile_process='worker') # logging head = '%(asctime)-15s Node[' + str(kv.rank) + '] %(message)s' logging.basicConfig(level=logging.DEBUG, format=head) logging.info('start with arguments %s', args) epoch_size = get_epoch_size(args, kv) # data iterators (train, val) = data_loader(args, kv) if 'dist' in args.kv_store and not 'async' in args.kv_store: logging.info('Resizing training data to %d batches per machine', epoch_size) # resize train iter to ensure each machine has same number of batches per epoch # if not, dist_sync can hang at the end with one machine waiting for other machines train = mx.io.ResizeIter(train, epoch_size) if args.test_io: tic = time.time() for i, batch in enumerate(train): if isinstance(batch, list): for b in batch: for j in b.data: j.wait_to_read() else: for j in batch.data: j.wait_to_read() if (i + 1) % args.disp_batches == 0: logging.info('Batch [%d]\tSpeed: %.2f samples/sec', i, args.disp_batches * args.batch_size / (time.time() - tic)) tic = time.time() return # load model if 'arg_params' in kwargs and 'aux_params' in kwargs: arg_params = kwargs['arg_params'] aux_params = kwargs['aux_params'] else: sym, arg_params, aux_params = _load_model(args, kv.rank) if sym is not None: assert sym.tojson() == network.tojson() # save model checkpoint = _save_model(args, kv.rank) # devices for training devs = mx.cpu() if args.gpus is None or args.gpus == "" else [ mx.gpu(int(i)) for i in args.gpus.split(',')] # learning rate lr, lr_scheduler = _get_lr_scheduler(args, kv) # create model model = mx.mod.Module( context=devs, symbol=network ) lr_scheduler = lr_scheduler optimizer_params = { 'learning_rate': lr, 'wd': args.wd, 'lr_scheduler': lr_scheduler, 'multi_precision': True} # Only a limited number of optimizers have 'momentum' property has_momentum = {'sgd', 'dcasgd', 'nag', 'signum', 'lbsgd'} if args.optimizer in has_momentum: optimizer_params['momentum'] = args.mom monitor = mx.mon.Monitor( args.monitor, pattern=".*") if args.monitor > 0 else None # A limited number of optimizers have a warmup period has_warmup = {'lbsgd', 'lbnag'} if args.optimizer in has_warmup: nworkers = kv.num_workers if epoch_size < 1: epoch_size = 1 macrobatch_size = args.macrobatch_size if macrobatch_size < args.batch_size * nworkers: macrobatch_size = args.batch_size * nworkers #batch_scale = round(float(macrobatch_size) / args.batch_size / nworkers +0.4999) batch_scale = math.ceil( float(macrobatch_size) / args.batch_size / nworkers) optimizer_params['updates_per_epoch'] = epoch_size optimizer_params['begin_epoch'] = args.load_epoch if args.load_epoch else 0 optimizer_params['batch_scale'] = batch_scale optimizer_params['warmup_strategy'] = args.warmup_strategy optimizer_params['warmup_epochs'] = args.warmup_epochs optimizer_params['num_epochs'] = args.num_epochs if args.initializer == 'default': if args.network == 'alexnet': # AlexNet will not converge using Xavier initializer = mx.init.Normal() # VGG will not trend to converge using Xavier-Gaussian elif args.network and 'vgg' in args.network: initializer = mx.init.Xavier() else: initializer = mx.init.Xavier( rnd_type='gaussian', factor_type="in", magnitude=2) # initializer = mx.init.Xavier(factor_type="in", magnitude=2.34), elif args.initializer == 'xavier': initializer = mx.init.Xavier() elif args.initializer == 'msra': initializer = mx.init.MSRAPrelu() elif args.initializer == 'orthogonal': initializer = mx.init.Orthogonal() elif args.initializer == 'normal': initializer = mx.init.Normal() elif args.initializer == 'uniform': initializer = mx.init.Uniform() elif args.initializer == 'one': initializer = mx.init.One() elif args.initializer == 'zero': initializer = mx.init.Zero() # evaluation metrices eval_metrics = ['accuracy'] if args.top_k > 0: eval_metrics.append(mx.metric.create( 'top_k_accuracy', top_k=args.top_k)) supported_loss = ['ce', 'nll_loss'] if len(args.loss) > 0: # ce or nll loss is only applicable to softmax output loss_type_list = args.loss.split(',') if 'softmax_output' in network.list_outputs(): for loss_type in loss_type_list: loss_type = loss_type.strip() if loss_type == 'nll': loss_type = 'nll_loss' if loss_type not in supported_loss: logging.warning(loss_type + ' is not an valid loss type, only cross-entropy or ' \ 'negative likelihood loss is supported!') else: eval_metrics.append(mx.metric.create(loss_type)) else: logging.warning("The output is not softmax_output, loss argument will be skipped!") # callbacks that run after each batch batch_end_callbacks = [mx.callback.Speedometer( args.batch_size, args.disp_batches)] if 'batch_end_callback' in kwargs: cbs = kwargs['batch_end_callback'] batch_end_callbacks += cbs if isinstance(cbs, list) else [cbs] # run model.fit(train, begin_epoch=args.load_epoch if args.load_epoch else 0, num_epoch=args.num_epochs, eval_data=val, eval_metric=eval_metrics, kvstore=kv, optimizer=args.optimizer, optimizer_params=optimizer_params, initializer=initializer, arg_params=arg_params, aux_params=aux_params, batch_end_callback=batch_end_callbacks, epoch_end_callback=checkpoint, allow_missing=True, monitor=monitor) if args.profile_server_suffix: mx.profiler.set_state(state='run', profile_process='server') if args.profile_worker_suffix: mx.profiler.set_state(state='run', profile_process='worker')
Helper function to create multiple random crop augmenters. Parameters ---------- min_object_covered : float or list of float, default=0.1 The cropped area of the image must contain at least this fraction of any bounding box supplied. The value of this parameter should be non-negative. In the case of 0, the cropped area does not need to overlap any of the bounding boxes supplied. min_eject_coverage : float or list of float, default=0.3 The minimum coverage of cropped sample w.r.t its original size. With this constraint, objects that have marginal area after crop will be discarded. aspect_ratio_range : tuple of floats or list of tuple of floats, default=(0.75, 1.33) The cropped area of the image must have an aspect ratio = width / height within this range. area_range : tuple of floats or list of tuple of floats, default=(0.05, 1.0) The cropped area of the image must contain a fraction of the supplied image within in this range. max_attempts : int or list of int, default=50 Number of attempts at generating a cropped/padded region of the image of the specified constraints. After max_attempts failures, return the original image. Examples -------- >>> # An example of creating multiple random crop augmenters >>> min_object_covered = [0.1, 0.3, 0.5, 0.7, 0.9] # use 5 augmenters >>> aspect_ratio_range = (0.75, 1.33) # use same range for all augmenters >>> area_range = [(0.1, 1.0), (0.2, 1.0), (0.2, 1.0), (0.3, 0.9), (0.5, 1.0)] >>> min_eject_coverage = 0.3 >>> max_attempts = 50 >>> aug = mx.image.det.CreateMultiRandCropAugmenter(min_object_covered=min_object_covered, aspect_ratio_range=aspect_ratio_range, area_range=area_range, min_eject_coverage=min_eject_coverage, max_attempts=max_attempts, skip_prob=0) >>> aug.dumps() # show some details def CreateMultiRandCropAugmenter(min_object_covered=0.1, aspect_ratio_range=(0.75, 1.33), area_range=(0.05, 1.0), min_eject_coverage=0.3, max_attempts=50, skip_prob=0): """Helper function to create multiple random crop augmenters. Parameters ---------- min_object_covered : float or list of float, default=0.1 The cropped area of the image must contain at least this fraction of any bounding box supplied. The value of this parameter should be non-negative. In the case of 0, the cropped area does not need to overlap any of the bounding boxes supplied. min_eject_coverage : float or list of float, default=0.3 The minimum coverage of cropped sample w.r.t its original size. With this constraint, objects that have marginal area after crop will be discarded. aspect_ratio_range : tuple of floats or list of tuple of floats, default=(0.75, 1.33) The cropped area of the image must have an aspect ratio = width / height within this range. area_range : tuple of floats or list of tuple of floats, default=(0.05, 1.0) The cropped area of the image must contain a fraction of the supplied image within in this range. max_attempts : int or list of int, default=50 Number of attempts at generating a cropped/padded region of the image of the specified constraints. After max_attempts failures, return the original image. Examples -------- >>> # An example of creating multiple random crop augmenters >>> min_object_covered = [0.1, 0.3, 0.5, 0.7, 0.9] # use 5 augmenters >>> aspect_ratio_range = (0.75, 1.33) # use same range for all augmenters >>> area_range = [(0.1, 1.0), (0.2, 1.0), (0.2, 1.0), (0.3, 0.9), (0.5, 1.0)] >>> min_eject_coverage = 0.3 >>> max_attempts = 50 >>> aug = mx.image.det.CreateMultiRandCropAugmenter(min_object_covered=min_object_covered, aspect_ratio_range=aspect_ratio_range, area_range=area_range, min_eject_coverage=min_eject_coverage, max_attempts=max_attempts, skip_prob=0) >>> aug.dumps() # show some details """ def align_parameters(params): """Align parameters as pairs""" out_params = [] num = 1 for p in params: if not isinstance(p, list): p = [p] out_params.append(p) num = max(num, len(p)) # align for each param for k, p in enumerate(out_params): if len(p) != num: assert len(p) == 1 out_params[k] = p * num return out_params aligned_params = align_parameters([min_object_covered, aspect_ratio_range, area_range, min_eject_coverage, max_attempts]) augs = [] for moc, arr, ar, mec, ma in zip(*aligned_params): augs.append(DetRandomCropAug(min_object_covered=moc, aspect_ratio_range=arr, area_range=ar, min_eject_coverage=mec, max_attempts=ma)) return DetRandomSelectAug(augs, skip_prob=skip_prob)
Create augmenters for detection. Parameters ---------- data_shape : tuple of int Shape for output data resize : int Resize shorter edge if larger than 0 at the begining rand_crop : float [0, 1], probability to apply random cropping rand_pad : float [0, 1], probability to apply random padding rand_gray : float [0, 1], probability to convert to grayscale for all channels rand_mirror : bool Whether to apply horizontal flip to image with probability 0.5 mean : np.ndarray or None Mean pixel values for [r, g, b] std : np.ndarray or None Standard deviations for [r, g, b] brightness : float Brightness jittering range (percent) contrast : float Contrast jittering range (percent) saturation : float Saturation jittering range (percent) hue : float Hue jittering range (percent) pca_noise : float Pca noise level (percent) inter_method : int, default=2(Area-based) Interpolation method for all resizing operations Possible values: 0: Nearest Neighbors Interpolation. 1: Bilinear interpolation. 2: Area-based (resampling using pixel area relation). It may be a preferred method for image decimation, as it gives moire-free results. But when the image is zoomed, it is similar to the Nearest Neighbors method. (used by default). 3: Bicubic interpolation over 4x4 pixel neighborhood. 4: Lanczos interpolation over 8x8 pixel neighborhood. 9: Cubic for enlarge, area for shrink, bilinear for others 10: Random select from interpolation method metioned above. Note: When shrinking an image, it will generally look best with AREA-based interpolation, whereas, when enlarging an image, it will generally look best with Bicubic (slow) or Bilinear (faster but still looks OK). min_object_covered : float The cropped area of the image must contain at least this fraction of any bounding box supplied. The value of this parameter should be non-negative. In the case of 0, the cropped area does not need to overlap any of the bounding boxes supplied. min_eject_coverage : float The minimum coverage of cropped sample w.r.t its original size. With this constraint, objects that have marginal area after crop will be discarded. aspect_ratio_range : tuple of floats The cropped area of the image must have an aspect ratio = width / height within this range. area_range : tuple of floats The cropped area of the image must contain a fraction of the supplied image within in this range. max_attempts : int Number of attempts at generating a cropped/padded region of the image of the specified constraints. After max_attempts failures, return the original image. pad_val: float Pixel value to be filled when padding is enabled. pad_val will automatically be subtracted by mean and divided by std if applicable. Examples -------- >>> # An example of creating multiple augmenters >>> augs = mx.image.CreateDetAugmenter(data_shape=(3, 300, 300), rand_crop=0.5, ... rand_pad=0.5, rand_mirror=True, mean=True, brightness=0.125, contrast=0.125, ... saturation=0.125, pca_noise=0.05, inter_method=10, min_object_covered=[0.3, 0.5, 0.9], ... area_range=(0.3, 3.0)) >>> # dump the details >>> for aug in augs: ... aug.dumps() def CreateDetAugmenter(data_shape, resize=0, rand_crop=0, rand_pad=0, rand_gray=0, rand_mirror=False, mean=None, std=None, brightness=0, contrast=0, saturation=0, pca_noise=0, hue=0, inter_method=2, min_object_covered=0.1, aspect_ratio_range=(0.75, 1.33), area_range=(0.05, 3.0), min_eject_coverage=0.3, max_attempts=50, pad_val=(127, 127, 127)): """Create augmenters for detection. Parameters ---------- data_shape : tuple of int Shape for output data resize : int Resize shorter edge if larger than 0 at the begining rand_crop : float [0, 1], probability to apply random cropping rand_pad : float [0, 1], probability to apply random padding rand_gray : float [0, 1], probability to convert to grayscale for all channels rand_mirror : bool Whether to apply horizontal flip to image with probability 0.5 mean : np.ndarray or None Mean pixel values for [r, g, b] std : np.ndarray or None Standard deviations for [r, g, b] brightness : float Brightness jittering range (percent) contrast : float Contrast jittering range (percent) saturation : float Saturation jittering range (percent) hue : float Hue jittering range (percent) pca_noise : float Pca noise level (percent) inter_method : int, default=2(Area-based) Interpolation method for all resizing operations Possible values: 0: Nearest Neighbors Interpolation. 1: Bilinear interpolation. 2: Area-based (resampling using pixel area relation). It may be a preferred method for image decimation, as it gives moire-free results. But when the image is zoomed, it is similar to the Nearest Neighbors method. (used by default). 3: Bicubic interpolation over 4x4 pixel neighborhood. 4: Lanczos interpolation over 8x8 pixel neighborhood. 9: Cubic for enlarge, area for shrink, bilinear for others 10: Random select from interpolation method metioned above. Note: When shrinking an image, it will generally look best with AREA-based interpolation, whereas, when enlarging an image, it will generally look best with Bicubic (slow) or Bilinear (faster but still looks OK). min_object_covered : float The cropped area of the image must contain at least this fraction of any bounding box supplied. The value of this parameter should be non-negative. In the case of 0, the cropped area does not need to overlap any of the bounding boxes supplied. min_eject_coverage : float The minimum coverage of cropped sample w.r.t its original size. With this constraint, objects that have marginal area after crop will be discarded. aspect_ratio_range : tuple of floats The cropped area of the image must have an aspect ratio = width / height within this range. area_range : tuple of floats The cropped area of the image must contain a fraction of the supplied image within in this range. max_attempts : int Number of attempts at generating a cropped/padded region of the image of the specified constraints. After max_attempts failures, return the original image. pad_val: float Pixel value to be filled when padding is enabled. pad_val will automatically be subtracted by mean and divided by std if applicable. Examples -------- >>> # An example of creating multiple augmenters >>> augs = mx.image.CreateDetAugmenter(data_shape=(3, 300, 300), rand_crop=0.5, ... rand_pad=0.5, rand_mirror=True, mean=True, brightness=0.125, contrast=0.125, ... saturation=0.125, pca_noise=0.05, inter_method=10, min_object_covered=[0.3, 0.5, 0.9], ... area_range=(0.3, 3.0)) >>> # dump the details >>> for aug in augs: ... aug.dumps() """ auglist = [] if resize > 0: auglist.append(DetBorrowAug(ResizeAug(resize, inter_method))) if rand_crop > 0: crop_augs = CreateMultiRandCropAugmenter(min_object_covered, aspect_ratio_range, area_range, min_eject_coverage, max_attempts, skip_prob=(1 - rand_crop)) auglist.append(crop_augs) if rand_mirror > 0: auglist.append(DetHorizontalFlipAug(0.5)) # apply random padding as late as possible to save computation if rand_pad > 0: pad_aug = DetRandomPadAug(aspect_ratio_range, (1.0, area_range[1]), max_attempts, pad_val) auglist.append(DetRandomSelectAug([pad_aug], 1 - rand_pad)) # force resize auglist.append(DetBorrowAug(ForceResizeAug((data_shape[2], data_shape[1]), inter_method))) auglist.append(DetBorrowAug(CastAug())) if brightness or contrast or saturation: auglist.append(DetBorrowAug(ColorJitterAug(brightness, contrast, saturation))) if hue: auglist.append(DetBorrowAug(HueJitterAug(hue))) if pca_noise > 0: eigval = np.array([55.46, 4.794, 1.148]) eigvec = np.array([[-0.5675, 0.7192, 0.4009], [-0.5808, -0.0045, -0.8140], [-0.5836, -0.6948, 0.4203]]) auglist.append(DetBorrowAug(LightingAug(pca_noise, eigval, eigvec))) if rand_gray > 0: auglist.append(DetBorrowAug(RandomGrayAug(rand_gray))) if mean is True: mean = np.array([123.68, 116.28, 103.53]) elif mean is not None: assert isinstance(mean, np.ndarray) and mean.shape[0] in [1, 3] if std is True: std = np.array([58.395, 57.12, 57.375]) elif std is not None: assert isinstance(std, np.ndarray) and std.shape[0] in [1, 3] if mean is not None or std is not None: auglist.append(DetBorrowAug(ColorNormalizeAug(mean, std))) return auglist
Override default. def dumps(self): """Override default.""" return [self.__class__.__name__.lower(), [x.dumps() for x in self.aug_list]]
Calculate areas for multiple labels def _calculate_areas(self, label): """Calculate areas for multiple labels""" heights = np.maximum(0, label[:, 3] - label[:, 1]) widths = np.maximum(0, label[:, 2] - label[:, 0]) return heights * widths
Calculate intersect areas, normalized. def _intersect(self, label, xmin, ymin, xmax, ymax): """Calculate intersect areas, normalized.""" left = np.maximum(label[:, 0], xmin) right = np.minimum(label[:, 2], xmax) top = np.maximum(label[:, 1], ymin) bot = np.minimum(label[:, 3], ymax) invalid = np.where(np.logical_or(left >= right, top >= bot))[0] out = label.copy() out[:, 0] = left out[:, 1] = top out[:, 2] = right out[:, 3] = bot out[invalid, :] = 0 return out
Check if constrains are satisfied def _check_satisfy_constraints(self, label, xmin, ymin, xmax, ymax, width, height): """Check if constrains are satisfied""" if (xmax - xmin) * (ymax - ymin) < 2: return False # only 1 pixel x1 = float(xmin) / width y1 = float(ymin) / height x2 = float(xmax) / width y2 = float(ymax) / height object_areas = self._calculate_areas(label[:, 1:]) valid_objects = np.where(object_areas * width * height > 2)[0] if valid_objects.size < 1: return False intersects = self._intersect(label[valid_objects, 1:], x1, y1, x2, y2) coverages = self._calculate_areas(intersects) / object_areas[valid_objects] coverages = coverages[np.where(coverages > 0)[0]] return coverages.size > 0 and np.amin(coverages) > self.min_object_covered
Convert labels according to crop box def _update_labels(self, label, crop_box, height, width): """Convert labels according to crop box""" xmin = float(crop_box[0]) / width ymin = float(crop_box[1]) / height w = float(crop_box[2]) / width h = float(crop_box[3]) / height out = label.copy() out[:, (1, 3)] -= xmin out[:, (2, 4)] -= ymin out[:, (1, 3)] /= w out[:, (2, 4)] /= h out[:, 1:5] = np.maximum(0, out[:, 1:5]) out[:, 1:5] = np.minimum(1, out[:, 1:5]) coverage = self._calculate_areas(out[:, 1:]) * w * h / self._calculate_areas(label[:, 1:]) valid = np.logical_and(out[:, 3] > out[:, 1], out[:, 4] > out[:, 2]) valid = np.logical_and(valid, coverage > self.min_eject_coverage) valid = np.where(valid)[0] if valid.size < 1: return None out = out[valid, :] return out
Propose cropping areas def _random_crop_proposal(self, label, height, width): """Propose cropping areas""" from math import sqrt if not self.enabled or height <= 0 or width <= 0: return () min_area = self.area_range[0] * height * width max_area = self.area_range[1] * height * width for _ in range(self.max_attempts): ratio = random.uniform(*self.aspect_ratio_range) if ratio <= 0: continue h = int(round(sqrt(min_area / ratio))) max_h = int(round(sqrt(max_area / ratio))) if round(max_h * ratio) > width: # find smallest max_h satifying round(max_h * ratio) <= width max_h = int((width + 0.4999999) / ratio) if max_h > height: max_h = height if h > max_h: h = max_h if h < max_h: # generate random h in range [h, max_h] h = random.randint(h, max_h) w = int(round(h * ratio)) assert w <= width # trying to fix rounding problems area = w * h if area < min_area: h += 1 w = int(round(h * ratio)) area = w * h if area > max_area: h -= 1 w = int(round(h * ratio)) area = w * h if not (min_area <= area <= max_area and 0 <= w <= width and 0 <= h <= height): continue y = random.randint(0, max(0, height - h)) x = random.randint(0, max(0, width - w)) if self._check_satisfy_constraints(label, x, y, x + w, y + h, width, height): new_label = self._update_labels(label, (x, y, w, h), height, width) if new_label is not None: return (x, y, w, h, new_label) return ()
Update label according to padding region def _update_labels(self, label, pad_box, height, width): """Update label according to padding region""" out = label.copy() out[:, (1, 3)] = (out[:, (1, 3)] * width + pad_box[0]) / pad_box[2] out[:, (2, 4)] = (out[:, (2, 4)] * height + pad_box[1]) / pad_box[3] return out
Generate random padding region def _random_pad_proposal(self, label, height, width): """Generate random padding region""" from math import sqrt if not self.enabled or height <= 0 or width <= 0: return () min_area = self.area_range[0] * height * width max_area = self.area_range[1] * height * width for _ in range(self.max_attempts): ratio = random.uniform(*self.aspect_ratio_range) if ratio <= 0: continue h = int(round(sqrt(min_area / ratio))) max_h = int(round(sqrt(max_area / ratio))) if round(h * ratio) < width: h = int((width + 0.499999) / ratio) if h < height: h = height if h > max_h: h = max_h if h < max_h: h = random.randint(h, max_h) w = int(round(h * ratio)) if (h - height) < 2 or (w - width) < 2: continue # marginal padding is not helpful y = random.randint(0, max(0, h - height)) x = random.randint(0, max(0, w - width)) new_label = self._update_labels(label, (x, y, w, h), height, width) return (x, y, w, h, new_label) return ()