text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tic(self): """Start collecting stats for current batch. Call before calling forward."""
if self.step % self.interval == 0: for exe in self.exes: for array in exe.arg_arrays: array.wait_to_read() for array in exe.aux_arrays: array.wait_to_read() self.queue = [] self.activated = True ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def toc(self): """End collecting for current batch and return results. Call after computation of current batch. Returns ------- res : list of """
if not self.activated: return [] for exe in self.exes: for array in exe.arg_arrays: array.wait_to_read() for array in exe.aux_arrays: array.wait_to_read() for exe in self.exes: for name, array in zip(exe._symbol.lis...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def toc_print(self): """End collecting and print results."""
res = self.toc() for n, k, v in res: logging.info('Batch: {:7d} {:30s} {:s}'.format(n, k, v))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def make_data_iter_plan(self): "make a random data iteration plan" # truncate each bucket into multiple of batch-size bucket_n_batches = [] for i in range(len(self.data)): bucket_n_batches.append(np.floor((self.data[i]) / self.batch_size)) self.data[i] = self.data...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def expand(x, pending, stage): """ Expand the pending files in the current stage. Parameters x: str The file to expand. pending : str The list of pending files t...
if x in history and x not in ['mshadow/mshadow/expr_scalar-inl.h']: # MULTIPLE includes return if x in pending: #print('loop found: {} in {}'.format(x, pending)) return whtspace = ' ' * expand.treeDepth expand.fileCount += 1 comment = u"//=====[{:3d}] STAGE:{:>4} {}EXPAND...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_imagenet_iterator(root, batch_size, num_workers, data_shape=224, dtype='float32'): """Dataset loader with preprocessing."""
train_dir = os.path.join(root, 'train') train_transform, val_transform = get_imagenet_transforms(data_shape, dtype) logging.info("Loading image folder %s, this may take a bit long...", train_dir) train_dataset = ImageFolderDataset(train_dir, transform=train_transform) train_data = DataLoader(train_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _load_embedding(self, pretrained_file_path, elem_delim, init_unknown_vec, encoding='utf8'): """Load embedding vectors from the pre-trained token embedding fi...
pretrained_file_path = os.path.expanduser(pretrained_file_path) if not os.path.isfile(pretrained_file_path): raise ValueError('`pretrained_file_path` must be a valid path to ' 'the pre-trained token embedding file.') logging.info('Loading pre-trained ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _set_idx_to_vec_by_embeddings(self, token_embeddings, vocab_len, vocab_idx_to_token): """Sets the mapping between token indices and token embedding vectors. ...
new_vec_len = sum(embed.vec_len for embed in token_embeddings) new_idx_to_vec = nd.zeros(shape=(vocab_len, new_vec_len)) col_start = 0 # Concatenate all the embedding vectors in token_embeddings. for embed in token_embeddings: col_end = col_start + embed.vec_len ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_vecs_by_tokens(self, tokens, lower_case_backup=False): """Look up embedding vectors of tokens. Parameters tokens : str or list of strs A token or a list ...
to_reduce = False if not isinstance(tokens, list): tokens = [tokens] to_reduce = True if not lower_case_backup: indices = [self.token_to_idx.get(token, C.UNKNOWN_IDX) for token in tokens] else: indices = [self.token_to_idx[token] if toke...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_token_vectors(self, tokens, new_vectors): """Updates embedding vectors for tokens. Parameters tokens : str or a list of strs A token or a list of toke...
assert self.idx_to_vec is not None, 'The property `idx_to_vec` has not been properly set.' if not isinstance(tokens, list) or len(tokens) == 1: assert isinstance(new_vectors, nd.NDArray) and len(new_vectors.shape) in [1, 2], \ '`new_vectors` must be a 1-D or 2-D NDArray if...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _check_pretrained_file_names(cls, pretrained_file_name): """Checks if a pre-trained token embedding file name is valid. Parameters pretrained_file_name : str...
embedding_name = cls.__name__.lower() if pretrained_file_name not in cls.pretrained_file_name_sha1: raise KeyError('Cannot find pretrained file %s for token embedding %s. Valid ' 'pretrained files for embedding %s: %s' % (pretrained_fil...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def step_HMC(exe, exe_params, exe_grads, label_key, noise_precision, prior_precision, L=10, eps=1E-6): """Generate the implementation of step HMC"""
init_params = {k: v.copyto(v.context) for k, v in exe_params.items()} end_params = {k: v.copyto(v.context) for k, v in exe_params.items()} init_momentums = {k: mx.random.normal(0, 1, v.shape) for k, v in init_params.items()} end_momentums = {k: v.copyto(v.context) for k, v in init_momentums.items()} ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def HMC(sym, data_inputs, X, Y, X_test, Y_test, sample_num, initializer=None, noise_precision=1 / 9.0, prior_precision=0.1, learning_rate=1E-6, L=10, dev=mx.gpu()...
label_key = list(set(data_inputs.keys()) - set(['data']))[0] exe, exe_params, exe_grads, _ = get_executor(sym, dev, data_inputs, initializer) exe.arg_dict['data'][:] = X exe.arg_dict[label_key][:] = Y sample_pool = [] accept_num = 0 start = time.time() for i in range(sample_num): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def SGD(sym, data_inputs, X, Y, X_test, Y_test, total_iter_num, lr=None, lr_scheduler=None, prior_precision=1, out_grad_f=None, initializer=None, minibatch_size=1...
if out_grad_f is None: label_key = list(set(data_inputs.keys()) - set(['data']))[0] exe, params, params_grad, _ = get_executor(sym, dev, data_inputs, initializer) optimizer = mx.optimizer.create('sgd', learning_rate=lr, rescale_grad=X.shape[0] / minibatch_size, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def SGLD(sym, X, Y, X_test, Y_test, total_iter_num, data_inputs=None, learning_rate=None, lr_scheduler=None, prior_precision=1, out_grad_f=None, initializer=None,...
if out_grad_f is None: label_key = list(set(data_inputs.keys()) - set(['data']))[0] exe, params, params_grad, _ = get_executor(sym, dev, data_inputs, initializer) optimizer = mx.optimizer.create('sgld', learning_rate=learning_rate, rescale_grad=X.shape[0] / minib...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_platforms(path: str = get_dockerfiles_path()) -> List[str]: """Get a list of architectures given our dockerfiles"""
dockerfiles = glob.glob(os.path.join(path, "Dockerfile.*")) dockerfiles = list(filter(lambda x: x[-1] != '~', dockerfiles)) files = list(map(lambda x: re.sub(r"Dockerfile.(.*)", r"\1", x), dockerfiles)) platforms = list(map(lambda x: os.path.split(x)[1], sorted(files))) return platforms
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_docker_cache(tag, docker_registry) -> None: """Imports tagged container from the given docker registry"""
if docker_registry: # noinspection PyBroadException try: import docker_cache logging.info('Docker cache download is enabled from registry %s', docker_registry) docker_cache.load_docker_cache(registry=docker_registry, docker_tag=tag) except Exception: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _load_data(batch, targets, major_axis): """Load data into sliced arrays."""
if isinstance(batch, list): new_batch = [] for i in range(len(targets)): new_batch.append([b.data[i] for b in batch]) new_targets = [[dst for _, dst in d_target] for d_target in targets] _load_general(new_batch, new_targets, major_axis) else: _load_general(ba...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _merge_multi_context(outputs, major_axis): """Merge outputs that lives on multiple context into one, so that they look like living on one context. """
rets = [] for tensors, axis in zip(outputs, major_axis): if axis >= 0: # pylint: disable=no-member,protected-access if len(tensors) == 1: rets.append(tensors[0]) else: # Concatenate if necessary rets.append(nd.concat(*[...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _prepare_group2ctxs(group2ctxs, ctx_len): """Prepare the group2contexts, will duplicate the context if some ctx_group map to only one context. """
if group2ctxs is None: return [None] * ctx_len elif isinstance(group2ctxs, list): assert(len(group2ctxs) == ctx_len), "length of group2ctxs\ should be %d" % ctx_len return group2ctxs elif isinstance(group2ctxs, dict): ret = [{} for i in range(ctx_len)] fo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def decide_slices(self, data_shapes): """Decide the slices for each context according to the workload. Parameters data_shapes : list list of (name, shape) specif...
assert len(data_shapes) > 0 major_axis = [DataDesc.get_batch_axis(x.layout) for x in data_shapes] for (name, shape), axis in zip(data_shapes, major_axis): if axis == -1: continue batch_size = shape[axis] if self.batch_size is not None: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _collect_arrays(self): """Collect internal arrays from executors."""
# convenient data structures self.data_arrays = [[(self.slices[i], e.arg_dict[name]) for i, e in enumerate(self.execs)] for name, _ in self.data_shapes] self.state_arrays = [[e.arg_dict[name] for e in self.execs] for name in self.state_n...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bind_exec(self, data_shapes, label_shapes, shared_group=None, reshape=False): """Bind executors on their respective devices. Parameters data_shapes : list la...
assert reshape or not self.execs self.batch_size = None # calculate workload and bind executors self.data_layouts = self.decide_slices(data_shapes) if label_shapes is not None: # call it to make sure labels has the same batch size as data self.label_layo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reshape(self, data_shapes, label_shapes): """Reshape executors. Parameters data_shapes : list label_shapes : list """
if data_shapes == self.data_shapes and label_shapes == self.label_shapes: return if self._default_execs is None: self._default_execs = [i for i in self.execs] self.bind_exec(data_shapes, label_shapes, reshape=True)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_params(self, arg_params, aux_params, allow_extra=False): """Assign, i.e. copy parameters to all the executors. Parameters arg_params : dict A dictionary ...
for exec_ in self.execs: exec_.copy_params_from(arg_params, aux_params, allow_extra_params=allow_extra)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_params(self, arg_params, aux_params): """ Copy data from each executor to `arg_params` and `aux_params`. Parameters arg_params : list of NDArray Target p...
for name, block in zip(self.param_names, self.param_arrays): weight = sum(w.copyto(ctx.cpu()) for w in block) / len(block) weight.astype(arg_params[name].dtype).copyto(arg_params[name]) for name, block in zip(self.aux_names, self.aux_arrays): weight = sum(w.copyto(ct...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def forward(self, data_batch, is_train=None): """Split `data_batch` according to workload and run forward on each devices. Parameters data_batch : DataBatch Or c...
_load_data(data_batch, self.data_arrays, self.data_layouts) if is_train is None: is_train = self.for_training if isinstance(data_batch, list): if self.label_arrays is not None and data_batch is not None and data_batch[0].label: _load_label(data_batch, se...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_output_shapes(self): """Get the shapes of the outputs."""
outputs = self.execs[0].outputs shapes = [out.shape for out in outputs] concat_shapes = [] for key, the_shape, axis in zip(self.symbol.list_outputs(), shapes, self.output_layouts): the_shape = list(the_shape) if axis >= 0: the_shape[axis] = self....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_outputs(self, merge_multi_context=True, begin=0, end=None): """Get outputs of the previous forward computation. If begin or end is specified, return [beg...
if end is None: end = self.num_outputs outputs = [[exec_.outputs[i] for exec_ in self.execs] for i in range(begin, end)] if merge_multi_context: outputs = _merge_multi_context(outputs, self.output_layouts) return outputs
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_states(self, states=None, value=None): """Set value for states. Only one of states & value can be specified. Parameters states : list of list of NDArrays...
if states is not None: assert value is None, "Only one of states & value can be specified." _load_general(states, self.state_arrays, (0,)*len(states)) else: assert value is not None, "At least one of states & value must be specified." assert states is Non...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_input_grads(self, merge_multi_context=True): """Get the gradients with respect to the inputs of the module. Parameters merge_multi_context : bool Default...
assert self.inputs_need_grad if merge_multi_context: return _merge_multi_context(self.input_grad_arrays, self.data_layouts) return self.input_grad_arrays
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def backward(self, out_grads=None): """Run backward on all devices. A backward should be called after a call to the forward function. Backward cannot be called u...
assert self.for_training, 're-bind with for_training=True to run backward' if out_grads is None: out_grads = [] for i, (exec_, islice) in enumerate(zip(self.execs, self.slices)): out_grads_slice = [] for grad, axis in zip(out_grads, self.output_layouts): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_metric(self, eval_metric, labels, pre_sliced): """Accumulate the performance according to `eval_metric` on all devices by comparing outputs from [begi...
for current_exec, (texec, islice) in enumerate(zip(self.execs, self.slices)): if not pre_sliced: labels_slice = [] for label, axis in zip(labels, self.label_layouts): if axis == 0: # slicing NDArray along axis 0 can avoid c...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _bind_ith_exec(self, i, data_shapes, label_shapes, shared_group): """Internal utility function to bind the i-th executor. This function utilizes simple_bind ...
shared_exec = None if shared_group is None else shared_group.execs[i] context = self.contexts[i] shared_data_arrays = self.shared_data_arrays[i] input_shapes = dict(data_shapes) if label_shapes is not None: input_shapes.update(dict(label_shapes)) input_type...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _sliced_shape(self, shapes, i, major_axis): """Get the sliced shapes for the i-th executor. Parameters shapes : list of (str, tuple) The original (name, shap...
sliced_shapes = [] for desc, axis in zip(shapes, major_axis): shape = list(desc.shape) if axis >= 0: shape[axis] = self.slices[i].stop - self.slices[i].start sliced_shapes.append(DataDesc(desc.name, tuple(shape), desc.dtype, desc.layout)) retu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get(self, name, hint): """Get the canonical name for a symbol. This is the default implementation. If the user specifies a name, the user-specified name will...
if name: return name if hint not in self._counter: self._counter[hint] = 0 name = '%s%d' % (hint, self._counter[hint]) self._counter[hint] += 1 return name
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_param(params, ctx=None): """same as mx.model.load_checkpoint, but do not load symnet and will convert context"""
if ctx is None: ctx = mx.cpu() save_dict = mx.nd.load(params) arg_params = {} aux_params = {} for k, v in save_dict.items(): tp, name = k.split(':', 1) if tp == 'arg': arg_params[name] = v.as_in_context(ctx) if tp == 'aux': aux_params[name] = ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rnn_unroll(cell, length, inputs=None, begin_state=None, input_prefix='', layout='NTC'): """Deprecated. Please use cell.unroll instead"""
warnings.warn('rnn_unroll is deprecated. Please call cell.unroll directly.') return cell.unroll(length=length, inputs=inputs, begin_state=begin_state, input_prefix=input_prefix, layout=layout)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save_rnn_checkpoint(cells, prefix, epoch, symbol, arg_params, aux_params): """Save checkpoint for model using RNN cells. Unpacks weight before saving. Parame...
if isinstance(cells, BaseRNNCell): cells = [cells] for cell in cells: arg_params = cell.unpack_weights(arg_params) save_checkpoint(prefix, epoch, symbol, arg_params, aux_params)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_rnn_checkpoint(cells, prefix, epoch): """Load model checkpoint from file. Pack weights after loading. Parameters cells : mxnet.rnn.RNNCell or list of RN...
sym, arg, aux = load_checkpoint(prefix, epoch) if isinstance(cells, BaseRNNCell): cells = [cells] for cell in cells: arg = cell.pack_weights(arg) return sym, arg, aux
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_rnn_checkpoint(cells, prefix, period=1): """Make a callback to checkpoint Module to prefix every epoch. unpacks weights used by cells before saving. Param...
period = int(max(1, period)) # pylint: disable=unused-argument def _callback(iter_no, sym=None, arg=None, aux=None): """The checkpoint function.""" if (iter_no + 1) % period == 0: save_rnn_checkpoint(cells, prefix, iter_no+1, sym, arg, aux) return _callback
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def hybridize(self, active=True, **kwargs): """Activates or deactivates `HybridBlock` s recursively. Has no effect on non-hybrid children. Parameters active : bo...
if self._children and all(isinstance(c, HybridBlock) for c in self._children.values()): warnings.warn( "All children of this Sequential layer '%s' are HybridBlocks. Consider " "using HybridSequential for the best performance."%self.prefix, stacklevel=2) super...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_img(path): """ Reads image specified by path into numpy.ndarray"""
img = cv2.resize(cv2.imread(path, 0), (80, 30)).astype(np.float32) / 255 img = np.expand_dims(img.transpose(1, 0), 0) return img
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lstm_init_states(batch_size): """ Returns a tuple of names and zero arrays for LSTM init states"""
hp = Hyperparams() init_shapes = lstm.init_states(batch_size=batch_size, num_lstm_layer=hp.num_lstm_layer, num_hidden=hp.num_hidden) init_names = [s[0] for s in init_shapes] init_arrays = [mx.nd.zeros(x[1]) for x in init_shapes] return init_names, init_arrays
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_module(prefix, epoch, data_names, data_shapes): """Loads the model from checkpoint specified by prefix and epoch, binds it to an executor, and sets its ...
sym, arg_params, aux_params = mx.model.load_checkpoint(prefix, epoch) # We don't need CTC loss for prediction, just a simple softmax will suffice. # We get the output of the layer just before the loss layer ('pred_fc') and add softmax on top pred_fc = sym.get_internals()['pred_fc_output'] sym = mx...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def c_str(string): """"Convert a python string to C string."""
if not isinstance(string, str): string = string.decode('ascii') return ctypes.c_char_p(string.encode('utf-8'))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _find_lib_path(): """Find mxnet library."""
curr_path = os.path.dirname(os.path.abspath(os.path.expanduser(__file__))) amalgamation_lib_path = os.path.join(curr_path, '../../lib/libmxnet_predict.so') if os.path.exists(amalgamation_lib_path) and os.path.isfile(amalgamation_lib_path): lib_path = [amalgamation_lib_path] return lib_path ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _load_lib(): """Load libary by searching possible path."""
lib_path = _find_lib_path() lib = ctypes.cdll.LoadLibrary(lib_path[0]) # DMatrix functions lib.MXGetLastError.restype = ctypes.c_char_p return lib
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_ndarray_file(nd_bytes): """Load ndarray file and return as list of numpy array. Parameters nd_bytes : str or bytes The internal ndarray bytes Returns --...
handle = NDListHandle() olen = mx_uint() nd_bytes = bytearray(nd_bytes) ptr = (ctypes.c_char * len(nd_bytes)).from_buffer(nd_bytes) _check_call(_LIB.MXNDListCreate( ptr, len(nd_bytes), ctypes.byref(handle), ctypes.byref(olen))) keys = [] arrs = [] for i in range(olen.va...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def forward(self, **kwargs): """Perform forward to get the output. Parameters **kwargs Keyword arguments of input variable name to data. Examples -------- """
for k, v in kwargs.items(): if not isinstance(v, np.ndarray): raise ValueError("Expect numpy ndarray as input") v = np.asarray(v, dtype=np.float32, order='C') _check_call(_LIB.MXPredSetInput( self.handle, c_str(k), v.ctypes.dat...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reshape(self, input_shapes): """Change the input shape of the predictor. Parameters input_shapes : dict of str to tuple The new shape of input data. Examples...
indptr = [0] sdata = [] keys = [] for k, v in input_shapes.items(): if not isinstance(v, tuple): raise ValueError("Expect input_shapes to be dict str->tuple") keys.append(c_str(k)) sdata.extend(v) indptr.append(len(sdata))...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_output(self, index): """Get the index-th output. Parameters index : int The index of output. Returns ------- out : numpy array. The output array. """
pdata = ctypes.POINTER(mx_uint)() ndim = mx_uint() _check_call(_LIB.MXPredGetOutputShape( self.handle, index, ctypes.byref(pdata), ctypes.byref(ndim))) shape = tuple(pdata[:ndim.value]) data = np.empty(shape, dtype=np.float32) _check_c...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def begin_episode(self, max_episode_step=DEFAULT_MAX_EPISODE_STEP): """ Begin an episode of a game instance. We can play the game for a maximum of `max_episode_s...
if self.episode_step > self.max_episode_step or self.ale.game_over(): self.start() else: for i in range(self.screen_buffer_length): self.ale.act(0) self.ale.getScreenGrayscale(self.screen_buffer[i % self.screen_buffer_length, :, :]) self.m...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def forward(self, inputs, states): """Unrolls the recurrent cell for one time step. Parameters inputs : sym.Variable Input symbol, 2D, of shape (batch_size * num...
# pylint: disable= arguments-differ self._counter += 1 return super(RecurrentCell, self).forward(inputs, states)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _check_input_names(symbol, names, typename, throw): """Check that all input names are in symbol's arguments."""
args = symbol.list_arguments() for name in names: if name in args: continue candidates = [arg for arg in args if not arg.endswith('_weight') and not arg.endswith('_bias') and not arg.endswith('_gamma') and ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _check_names_match(data_names, data_shapes, name, throw): """Check that input names matches input data descriptors."""
actual = [x[0] for x in data_shapes] if sorted(data_names) != sorted(actual): msg = "Data provided by %s_shapes don't match names specified by %s_names (%s vs. %s)"%( name, name, str(data_shapes), str(data_names)) if throw: raise ValueError(msg) else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _parse_data_desc(data_names, label_names, data_shapes, label_shapes): """parse data_attrs into DataDesc format and check that names match"""
data_shapes = [x if isinstance(x, DataDesc) else DataDesc(*x) for x in data_shapes] _check_names_match(data_names, data_shapes, 'data', True) if label_shapes is not None: label_shapes = [x if isinstance(x, DataDesc) else DataDesc(*x) for x in label_shapes] _check_names_match(label_names, la...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def forward_backward(self, data_batch): """A convenient function that calls both ``forward`` and ``backward``."""
self.forward(data_batch, is_train=True) self.backward()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def score(self, eval_data, eval_metric, num_batch=None, batch_end_callback=None, score_end_callback=None, reset=True, epoch=0, sparse_row_id_fn=None): """Runs pr...
assert self.binded and self.params_initialized if reset: eval_data.reset() if not isinstance(eval_metric, metric.EvalMetric): eval_metric = metric.create(eval_metric) eval_metric.reset() actual_num_batch = 0 for nbatch, eval_batch in enumerate...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def iter_predict(self, eval_data, num_batch=None, reset=True, sparse_row_id_fn=None): """Iterates over predictions. Examples -------- Parameters eval_data : Data...
assert self.binded and self.params_initialized if reset: eval_data.reset() for nbatch, eval_batch in enumerate(eval_data): if num_batch is not None and nbatch == num_batch: break self.prepare(eval_batch, sparse_row_id_fn=sparse_row_id_fn) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def predict(self, eval_data, num_batch=None, merge_batches=True, reset=True, always_output_list=False, sparse_row_id_fn=None): """Runs prediction and collects th...
assert self.binded and self.params_initialized if isinstance(eval_data, (ndarray.NDArray, np.ndarray)): if isinstance(eval_data, np.ndarray): eval_data = ndarray.array(eval_data) self.forward(DataBatch([eval_data])) return self.get_outputs()[0] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_params(self, fname): """Loads model parameters from file. Parameters fname : str Path to input param file. Examples -------- """
save_dict = ndarray.load(fname) arg_params = {} aux_params = {} for k, value in save_dict.items(): arg_type, name = k.split(':', 1) if arg_type == 'arg': arg_params[name] = value elif arg_type == 'aux': aux_params[name]...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_include_path(): """Find MXNet included header files. Returns ------- incl_path : string Path to the header files. """
incl_from_env = os.environ.get('MXNET_INCLUDE_PATH') if incl_from_env: if os.path.isdir(incl_from_env): if not os.path.isabs(incl_from_env): logging.warning("MXNET_INCLUDE_PATH should be an absolute path, instead of: %s", incl_from_env) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def image(self, captcha_str): """Generate a greyscale captcha image representing number string Parameters captcha_str: str string a characters for captcha image ...
img = self.captcha.generate(captcha_str) img = np.fromstring(img.getvalue(), dtype='uint8') img = cv2.imdecode(img, cv2.IMREAD_GRAYSCALE) img = cv2.resize(img, (self.h, self.w)) img = img.transpose(1, 0) img = np.multiply(img, 1 / 255.0) return img
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register(klass): """Registers a new optimizer. Once an optimizer is registered, we can create an instance of this optimizer with `create_optimizer` later. Ex...
assert(isinstance(klass, type)) name = klass.__name__.lower() if name in Optimizer.opt_registry: warnings.warn('WARNING: New optimizer %s.%s is overriding ' 'existing optimizer %s.%s' % (klass.__module__, klass.__name__, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_optimizer(name, **kwargs): """Instantiates an optimizer with a given name and kwargs. .. note:: We can use the alias `create` for ``Optimizer.create_o...
if name.lower() in Optimizer.opt_registry: return Optimizer.opt_registry[name.lower()](**kwargs) else: raise ValueError('Cannot find optimizer %s' % name)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_state_multi_precision(self, index, weight): """Creates auxiliary state for a given weight, including FP32 high precision copy if original weight is FP...
weight_master_copy = None if self.multi_precision and weight.dtype == numpy.float16: weight_master_copy = weight.astype(numpy.float32) return (weight_master_copy,) + (self.create_state(index, weight_master_copy),) if weight.dtype == numpy.float16 and not self.multi_preci...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_multi_precision(self, index, weight, grad, state): """Updates the given parameter using the corresponding gradient and state. Mixed precision version....
if self.multi_precision and weight.dtype == numpy.float16: # Wrapper for mixed precision weight_master_copy = state[0] original_state = state[1] grad32 = grad.astype(numpy.float32) self.update(index, weight_master_copy, grad32, original_state) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_lr_mult(self, args_lr_mult): """Sets an individual learning rate multiplier for each parameter. If you specify a learning rate multiplier for a parameter...
self.lr_mult = {} if self.sym_info: attr, arg_names = self.sym_info for name in arg_names: if name in attr and '__lr_mult__' in attr[name]: self.lr_mult[name] = float(attr[name]['__lr_mult__']) self.lr_mult.update(args_lr_mult)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_wd_mult(self, args_wd_mult): """Sets an individual weight decay multiplier for each parameter. By default, if `param_idx2name` was provided in the constr...
self.wd_mult = {} for n in self.idx2name.values(): if not (n.endswith('_weight') or n.endswith('_gamma')): self.wd_mult[n] = 0.0 if self.sym_info: attr, arg_names = self.sym_info for name in arg_names: if name in attr and '__wd...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _set_current_context(self, device_id): """Sets the number of the currently handled device. Parameters device_id : int The number of current device. """
if device_id not in self._all_index_update_counts: self._all_index_update_counts[device_id] = {} self._index_update_count = self._all_index_update_counts[device_id]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _update_count(self, index): """Updates num_update. Parameters index : int or list of int The index to be updated. """
if not isinstance(index, (list, tuple)): index = [index] for idx in index: if idx not in self._index_update_count: self._index_update_count[idx] = self.begin_num_update self._index_update_count[idx] += 1 self.num_update = max(self._index_u...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_lrs(self, indices): """Gets the learning rates given the indices of the weights. Parameters indices : list of int Indices corresponding to weights. Retu...
if self.lr_scheduler is not None: lr = self.lr_scheduler(self.num_update) else: lr = self.lr lrs = [lr for _ in indices] for i, index in enumerate(indices): if index in self.param_dict: lrs[i] *= self.param_dict[index].lr_mult ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sync_state_context(self, state, context): """sync state context."""
if isinstance(state, NDArray): return state.as_in_context(context) elif isinstance(state, (tuple, list)): synced_state = (self.sync_state_context(i, context) for i in state) if isinstance(state, tuple): return tuple(synced_state) else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_states(self, states): """Sets updater states."""
states = pickle.loads(states) if isinstance(states, tuple) and len(states) == 2: self.states, self.optimizer = states else: self.states = states self.states_synced = dict.fromkeys(self.states.keys(), False)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_states(self, dump_optimizer=False): """Gets updater states. Parameters dump_optimizer : bool, default False Whether to also save the optimizer itself. Th...
return pickle.dumps((self.states, self.optimizer) if dump_optimizer else self.states)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_frames(self, path): """ Read from frames """
frames_path = sorted([os.path.join(path, x) for x in os.listdir(path)]) frames = [ndimage.imread(frame_path) for frame_path in frames_path] self.handle_type(frames) return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_video(self, path): """ Read from videos """
frames = self.get_video_frames(path) self.handle_type(frames) return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def handle_type(self, frames): """ Config video types """
if self.vtype == 'mouth': self.process_frames_mouth(frames) elif self.vtype == 'face': self.process_frames_face(frames) else: raise Exception('Video type not found')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def process_frames_face(self, frames): """ Preprocess from frames using face detector """
detector = dlib.get_frontal_face_detector() predictor = dlib.shape_predictor(self.face_predictor_path) mouth_frames = self.get_frames_mouth(detector, predictor, frames) self.face = np.array(frames) self.mouth = np.array(mouth_frames) if mouth_frames[0] is not None: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def process_frames_mouth(self, frames): """ Preprocess from frames using mouth detector """
self.face = np.array(frames) self.mouth = np.array(frames) self.set_data(frames)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_frames_mouth(self, detector, predictor, frames): """ Get frames using mouth crop """
mouth_width = 100 mouth_height = 50 horizontal_pad = 0.19 normalize_ratio = None mouth_frames = [] for frame in frames: dets = detector(frame, 1) shape = None for det in dets: shape = predictor(frame, det) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_video_frames(self, path): """ Get video frames """
videogen = skvideo.io.vreader(path) frames = np.array([frame for frame in videogen]) return frames
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_data(self, frames): """ Prepare the input of model """
data_frames = [] for frame in frames: #frame H x W x C frame = frame.swapaxes(0, 1) # swap width and height to form format W x H x C if len(frame.shape) < 3: frame = np.array([frame]).swapaxes(0, 2).swapaxes(0, 1) # Add grayscale channel d...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def subtract_imagenet_mean_preprocess_batch(batch): """Subtract ImageNet mean pixel-wise from a BGR image."""
batch = F.swapaxes(batch,0, 1) (r, g, b) = F.split(batch, num_outputs=3, axis=0) r = r - 123.680 g = g - 116.779 b = b - 103.939 batch = F.concat(b, g, r, dim=0) batch = F.swapaxes(batch,0, 1) return batch
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def imagenet_clamp_batch(batch, low, high): """ Not necessary in practice """
F.clip(batch[:,0,:,:],low-123.680, high-123.680) F.clip(batch[:,1,:,:],low-116.779, high-116.779) F.clip(batch[:,2,:,:],low-103.939, high-103.939)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def evaluate_accuracy(data_iterator, net): """Function to evaluate accuracy of any data iterator passed to it as an argument"""
acc = mx.metric.Accuracy() for data, label in data_iterator: output = net(data) predictions = nd.argmax(output, axis=1) predictions = predictions.reshape((-1, 1)) acc.update(preds=predictions, labels=label) return acc.get()[1]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_bulk_size(size): """Set size limit on bulk execution. Bulk execution bundles many operators to run together. This can improve performance when running a ...
prev = ctypes.c_int() check_call(_LIB.MXEngineSetBulkSize( ctypes.c_int(size), ctypes.byref(prev))) return prev.value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def applyLM(parentBeam, childBeam, classes, lm): """ calculate LM score of child beam by taking score from parent beam and bigram probability of last two chars "...
if lm and not childBeam.lmApplied: c1 = classes[parentBeam.labeling[-1] if parentBeam.labeling else classes.index(' ')] # first char c2 = classes[childBeam.labeling[-1]] # second char lmFactor = 0.01 # influence of language model bigramProb = lm.getCharBigram(c1, c2) ** lmFactor # p...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def addBeam(beamState, labeling): """ add beam if it does not yet exist """
if labeling not in beamState.entries: beamState.entries[labeling] = BeamEntry()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ctcBeamSearch(mat, classes, lm, k, beamWidth): """ beam search as described by the paper of Hwang et al. and the paper of Graves et al. """
blankIdx = len(classes) maxT, maxC = mat.shape # initialise beam state last = BeamState() labeling = () last.entries[labeling] = BeamEntry() last.entries[labeling].prBlank = 1 last.entries[labeling].prTotal = 1 # go over all time-steps for t in range(maxT): curr = Bea...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def norm(self): """ length-normalise LM score """
for (k, _) in self.entries.items(): labelingLen = len(self.entries[k].labeling) self.entries[k].prText = self.entries[k].prText ** (1.0 / (labelingLen if labelingLen else 1.0))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sort(self): """ return beam-labelings, sorted by probability """
beams = [v for (_, v) in self.entries.items()] sortedBeams = sorted(beams, reverse=True, key=lambda x: x.prTotal*x.prText) return [x.labeling for x in sortedBeams]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_loc(data, attr={'lr_mult':'0.01'}): """ the localisation network in lenet-stn, it will increase acc about more than 1%, when num-epoch >=15 """
loc = mx.symbol.Convolution(data=data, num_filter=30, kernel=(5, 5), stride=(2,2)) loc = mx.symbol.Activation(data = loc, act_type='relu') loc = mx.symbol.Pooling(data=loc, kernel=(2, 2), stride=(2, 2), pool_type='max') loc = mx.symbol.Convolution(data=loc, num_filter=60, kernel=(3, 3), stride=(1,1), p...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_detector(net, prefix, epoch, data_shape, mean_pixels, ctx, num_class, nms_thresh=0.5, force_nms=True, nms_topk=400): """ wrapper for initialize a detecto...
if net is not None: if isinstance(data_shape, tuple): data_shape = data_shape[0] net = get_symbol(net, data_shape, num_classes=num_class, nms_thresh=nms_thresh, force_nms=force_nms, nms_topk=nms_topk) detector = Detector(net, prefix, epoch, data_shape, mean_pixels, ctx=c...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_data_shape(data_shape_str): """Parse string to tuple or int"""
ds = data_shape_str.strip().split(',') if len(ds) == 1: data_shape = (int(ds[0]), int(ds[0])) elif len(ds) == 2: data_shape = (int(ds[0]), int(ds[1])) else: raise ValueError("Unexpected data_shape: %s", data_shape_str) return data_shape
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_lenet(): """ A lenet style net, takes difference of each frame as input. """
source = mx.sym.Variable("data") source = (source - 128) * (1.0/128) frames = mx.sym.SliceChannel(source, num_outputs=30) diffs = [frames[i+1] - frames[i] for i in range(29)] source = mx.sym.Concat(*diffs) net = mx.sym.Convolution(source, kernel=(5, 5), num_filter=40) net = mx.sym.BatchNorm...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def CRPS(label, pred): """ Custom evaluation metric on CRPS. """
for i in range(pred.shape[0]): for j in range(pred.shape[1] - 1): if pred[i, j] > pred[i, j + 1]: pred[i, j + 1] = pred[i, j] return np.sum(np.square(label - pred)) / label.size
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def encode_label(label_data): """Run encoding to encode the label into the CDF target. """
systole = label_data[:, 1] diastole = label_data[:, 2] systole_encode = np.array([ (x < np.arange(600)) for x in systole ], dtype=np.uint8) diastole_encode = np.array([ (x < np.arange(600)) for x in diastole ], dtype=np.uint8) return systole_encode, diastole_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def foreach(body, data, init_states): """Run a for loop with user-defined computation over NDArrays on dimension 0. This operator simulates a for loop and body h...
def check_input(inputs, in_type, msg): is_NDArray_or_list = True if isinstance(inputs, list): for i in inputs: if not isinstance(i, in_type): is_NDArray_or_list = False break else: is_NDArray_or_list = isinstan...