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 get_register_func(base_class, nickname): """Get registrator function. Parameters base_class : type base class for classes that will be reigstered nickname : ...
if base_class not in _REGISTRY: _REGISTRY[base_class] = {} registry = _REGISTRY[base_class] def register(klass, name=None): """Register functions""" assert issubclass(klass, base_class), \ "Can only register subclass of %s"%base_class.__name__ if name is 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 get_alias_func(base_class, nickname): """Get registrator function that allow aliases. Parameters base_class : type base class for classes that will be reigst...
register = get_register_func(base_class, nickname) def alias(*aliases): """alias registrator""" def reg(klass): """registrator function""" for name in aliases: register(klass, name) return klass return reg return alias
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pad_sentences(sentences, padding_word="</s>"): """Pads all sentences to the same length. The length is defined by the longest sentence. Returns padded senten...
sequence_length = max(len(x) for x in sentences) padded_sentences = [] for i, sentence in enumerate(sentences): num_padding = sequence_length - len(sentence) new_sentence = sentence + [padding_word] * num_padding padded_sentences.append(new_sentence) return padded_sentences
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def build_input_data(sentences, labels, vocabulary): """Maps sentencs and labels to vectors based on a vocabulary."""
x = np.array([[vocabulary[word] for word in sentence] for sentence in sentences]) y = np.array(labels) return [x, y]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def build_input_data_with_word2vec(sentences, labels, word2vec_list): """ Map sentences and labels to vectors based on a pretrained word2vec """
x_vec = [] for sent in sentences: vec = [] for word in sent: if word in word2vec_list: vec.append(word2vec_list[word]) else: vec.append(word2vec_list['</s>']) x_vec.append(vec) x_vec = np.array(x_vec) y_vec = np.array(label...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def batch_iter(data, batch_size, num_epochs): """Generates a batch iterator for a dataset."""
data = np.array(data) data_size = len(data) num_batches_per_epoch = int(len(data)/batch_size) + 1 for epoch in range(num_epochs): # Shuffle the data at each epoch shuffle_indices = np.random.permutation(np.arange(data_size)) shuffled_data = data[shuffle_indices] for batc...
<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_pretrained_word2vec(infile): """Load the pre-trained word2vec from file."""
if isinstance(infile, str): infile = open(infile) word2vec_list = {} for idx, line in enumerate(infile): if idx == 0: vocab_size, dim = line.strip().split() else: tks = line.strip().split() word2vec_list[tks[0]] = map(float, tks[1:]) return ...
<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_mlp(): """Get multi-layer perceptron"""
data = mx.symbol.Variable('data') fc1 = mx.symbol.CaffeOp(data_0=data, num_weight=2, name='fc1', prototxt="layer{type:\"InnerProduct\" inner_product_param{num_output: 128} }") act1 = mx.symbol.CaffeOp(data_0=fc1, prototxt="layer{type:\"TanH\"}") fc2 = mx.symbol.CaffeOp(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 forward(self, is_train, req, in_data, out_data, aux): """Implements forward computation. is_train : bool, whether forwarding for training or testing. req : l...
data = in_data[0] label = in_data[1] pred = mx.nd.SoftmaxOutput(data, label) self.assign(out_data[0], req[0], pred)
<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, req, out_grad, in_data, out_data, in_grad, aux): """Implements backward computation req : list of {'null', 'write', 'inplace', 'add'}, how to ...
label = in_data[1] pred = out_data[0] dx = pred - mx.nd.one_hot(label, 2) pos_cls_weight = self.positive_cls_weight scale_factor = ((1 + label * pos_cls_weight) / pos_cls_weight).reshape((pred.shape[0],1)) rescaled_dx = scale_factor * dx self.assign(in_grad[0], r...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _reset_bind(self): """Internal utility function to reset binding."""
self.binded = False self._buckets = {} self._curr_module = None self._curr_bucket_key = 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 data_names(self): """A list of names for data required by this module."""
if self.binded: return self._curr_module.data_names else: _, data_names, _ = self._call_sym_gen(self._default_bucket_key) return data_names
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def output_names(self): """A list of names for the outputs of this module."""
if self.binded: return self._curr_module.output_names else: symbol, _, _ = self._call_sym_gen(self._default_bucket_key) return symbol.list_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): """Sets value for states. Only one of states & values can be specified. Parameters states : list of list of NDArra...
assert self.binded and self.params_initialized self._curr_module.set_states(states, 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 bind(self, data_shapes, label_shapes=None, for_training=True, inputs_need_grad=False, force_rebind=False, shared_module=None, grad_req='write'): """Binding f...
# in case we already initialized params, keep it if self.params_initialized: arg_params, aux_params = self.get_params() # force rebinding is typically used when one want to switch from # training to prediction phase. if force_rebind: self._reset_bind() ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def switch_bucket(self, bucket_key, data_shapes, label_shapes=None): """Switches to a different bucket. This will change ``self.curr_module``. Parameters bucket_...
assert self.binded, 'call bind before switching bucket' if not bucket_key in self._buckets: symbol, data_names, label_names = self._call_sym_gen(bucket_key) module = Module(symbol, data_names, label_names, logger=self.logger, context=self._context, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def install_monitor(self, mon): """Installs monitor on all executors """
assert self.binded self._monitor = mon for mod in self._buckets.values(): mod.install_monitor(mon)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mark_variables(variables, gradients, grad_reqs='write'): """Mark NDArrays as variables to compute gradient for autograd. Parameters variables: NDArray or lis...
if isinstance(variables, NDArray): assert isinstance(gradients, NDArray) variables = [variables] gradients = [gradients] if isinstance(grad_reqs, string_types): grad_reqs = [_GRAD_REQ_MAP[grad_reqs]]*len(variables) else: grad_reqs = [_GRAD_REQ_MAP[i] for i in grad_r...
<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_head(heads, head_grads): """parse head gradient for backward and grad."""
if isinstance(heads, NDArray): heads = [heads] if isinstance(head_grads, NDArray): head_grads = [head_grads] head_handles = c_handle_array(heads) if head_grads is None: hgrad_handles = ctypes.c_void_p(0) else: assert len(heads) == len(head_grads), \ "he...
<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(heads, head_grads=None, retain_graph=False, train_mode=True): #pylint: disable=redefined-outer-name """Compute the gradients of heads w.r.t previous...
head_handles, hgrad_handles = _parse_head(heads, head_grads) check_call(_LIB.MXAutogradBackwardEx( len(head_handles), head_handles, hgrad_handles, 0, ctypes.c_void_p(0), ctypes.c_int(retain_graph), ctypes.c_int(0), ctypes.c_int(train_mode), ...
<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_symbol(x): """Retrieve recorded computation history as `Symbol`. Parameters x : NDArray Array representing the head of computation graph. Returns -------...
hdl = SymbolHandle() check_call(_LIB.MXAutogradGetSymbol(x.handle, ctypes.byref(hdl))) return Symbol(hdl)
<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_mldataset(filename): """Not particularly fast code to parse the text file and load it into three NDArray's and product an NDArrayIter """
user = [] item = [] score = [] with open(filename) as f: for line in f: tks = line.strip().split('\t') if len(tks) != 4: continue user.append(int(tks[0])) item.append(int(tks[1])) score.append(float(tks[2])) user = ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def main(): """Read .caffemodel path and .params path as input from command line and use CaffeModelConverter to do the conversion"""
parser = argparse.ArgumentParser(description='.caffemodel to MXNet .params converter.') parser.add_argument('caffemodel', help='Path to the .caffemodel file to convert.') parser.add_argument('output_file_name', help='Name of the output .params file.') args = parser.parse_args() converter = CaffeM...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_param(self, param_name, layer_index, blob_index): """Add a param to the .params file"""
blobs = self.layers[layer_index].blobs self.dict_param[param_name] = mx.nd.array(caffe.io.blobproto_to_array(blobs[blob_index]))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_optional_arg_param(self, param_name, layer_index, blob_index): """Add an arg param. If there is no such param in .caffemodel fie, silently ignore it."""
blobs = self.layers[layer_index].blobs if blob_index < len(blobs): self.add_arg_param(param_name, layer_index, blob_index)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert(self, caffemodel_path, outmodel_path): """Convert a Caffe .caffemodel file to MXNet .params file"""
net_param = caffe_pb2.NetParameter() with open(caffemodel_path, 'rb') as caffe_model_file: net_param.ParseFromString(caffe_model_file.read()) layers = net_param.layer self.layers = layers for idx, layer in enumerate(layers): layer_name = str(layer.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 assign(self, dst, req, src): """Helper function for assigning into dst depending on requirements."""
if req == 'null': return elif req in ('write', 'inplace'): dst[:] = src elif req == 'add': dst[:] += src
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def infer_type(self, in_type): """infer_type interface. override to create new operators Parameters in_type : list of np.dtype list of argument types in the same...
return in_type, [in_type[0]]*len(self.list_outputs()), \ [in_type[0]]*len(self.list_auxiliary_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 infer_storage_type(self, in_stype): """infer_storage_type interface. Used to infer storage type of inputs and outputs in the forward pass. When this interfac...
for i, stype in enumerate(in_stype): assert stype == _STORAGE_TYPE_ID_TO_STR[_STORAGE_TYPE_DEFAULT], \ "Default infer_storage_type implementation doesnt allow non default stypes: " \ "found non default stype '%s' for in_stype[%d]. Please implement " \ "infer_stor...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def infer_storage_type_backward(self, ograd_stype, in_stype, out_stype, igrad_stype, aux_stype): """infer_storage_type_backward interface. Used to infer storage ...
for i, stype in enumerate(ograd_stype): assert stype == _STORAGE_TYPE_ID_TO_STR[_STORAGE_TYPE_DEFAULT], \ "Default infer_storage_type_backward implementation doesnt allow non default stypes: " \ "found non default stype '%s' for ograd_stype[%d]. Please implement " \ ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def inc(self): """Get index for new entry."""
self.lock.acquire() cur = self.counter self.counter += 1 self.lock.release() return cur
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def close(self): """Closes the record and index files."""
if not self.is_open: return super(IndexCreator, self).close() self.fidx.close()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tell(self): """Returns the current position of read head. """
pos = ctypes.c_size_t() check_call(_LIB.MXRecordIOReaderTell(self.handle, ctypes.byref(pos))) return pos.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 create_index(self): """Creates the index file from open record file """
self.reset() counter = 0 pre_time = time.time() while True: if counter % 1000 == 0: cur_time = time.time() print('time:', cur_time - pre_time, ' count:', counter) pos = self.tell() cont = self.read() if cont...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _run_cmd(cmds): """Run commands, raise exception if failed"""
if not isinstance(cmds, str): cmds = "".join(cmds) print("Execute \"%s\"" % cmds) try: subprocess.check_call(cmds, shell=True) except subprocess.CalledProcessError as err: print(err) raise err
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_doxygen(app): """Run the doxygen make commands"""
_run_cmd("cd %s/.. && make doxygen" % app.builder.srcdir) _run_cmd("cp -rf doxygen/html %s/doxygen" % app.builder.outdir)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def build_mxnet(app): """Build mxnet .so lib"""
if not os.path.exists(os.path.join(app.builder.srcdir, '..', 'config.mk')): _run_cmd("cd %s/.. && cp make/config.mk config.mk && make -j$(nproc) USE_MKLDNN=0 USE_CPP_PACKAGE=1 " % app.builder.srcdir) else: _run_cmd("cd %s/.. && make -j$(nproc) USE_MKLDNN=0 USE_CPP_PACKAGE=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 build_r_docs(app): """build r pdf"""
r_root = app.builder.srcdir + '/../R-package' pdf_path = app.builder.srcdir + '/api/r/mxnet-r-reference-manual.pdf' _run_cmd('cd ' + r_root + '; R -e "roxygen2::roxygenize()"; R CMD Rd2pdf . --no-preview -o ' + pdf_path) dest_path = app.builder.outdir + '/api/r/' _run_cmd('mkdir -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 build_scala(app): """build scala for scala docs, java docs, and clojure docs to use"""
if any(v in _BUILD_VER for v in ['1.2.', '1.3.', '1.4.']): _run_cmd("cd %s/.. && make scalapkg" % app.builder.srcdir) _run_cmd("cd %s/.. && make scalainstall" % app.builder.srcdir) else: _run_cmd("cd %s/../scala-package && mvn -B install -DskipTests" % app.builder.srcdir)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def build_scala_docs(app): """build scala doc and then move the outdir"""
scala_path = app.builder.srcdir + '/../scala-package' scala_doc_sources = 'find . -type f -name "*.scala" | egrep \"\.\/core|\.\/infer\" | egrep -v \"\/javaapi\" | egrep -v \"Suite\"' scala_doc_classpath = ':'.join([ '`find native -name "*.jar" | grep "target/lib/" | tr "\\n" ":" `', '`fin...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def build_java_docs(app): """build java docs and then move the outdir"""
java_path = app.builder.srcdir + '/../scala-package' java_doc_sources = 'find . -type f -name "*.scala" | egrep \"\.\/core|\.\/infer\" | egrep \"\/javaapi\" | egrep -v \"Suite\"' java_doc_classpath = ':'.join([ '`find native -name "*.jar" | grep "target/lib/" | tr "\\n" ":" `', '`find macro...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def build_clojure_docs(app): """build clojure doc and then move the outdir"""
clojure_path = app.builder.srcdir + '/../contrib/clojure-package' _run_cmd('cd ' + clojure_path + '; lein codox') dest_path = app.builder.outdir + '/api/clojure/docs' _run_cmd('rm -rf ' + dest_path) _run_cmd('mkdir -p ' + dest_path) clojure_doc_path = app.builder.srcdir + '/../contrib/clojure-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 _convert_md_table_to_rst(table): """Convert a markdown table to rst format"""
if len(table) < 3: return '' out = '```eval_rst\n.. list-table::\n :header-rows: 1\n\n' for i,l in enumerate(table): cols = l.split('|')[1:-1] if i == 0: ncol = len(cols) else: if len(cols) != ncol: return '' if i == 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 convert_table(app, docname, source): """Find tables in a markdown and then convert them into the rst format"""
num_tables = 0 for i,j in enumerate(source): table = [] output = '' in_table = False for l in j.split('\n'): r = l.strip() if r.startswith('|'): table.append(r) in_table = True else: if in_table ...
<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_code_lines(lines): """A iterator that returns if a line is within a code block Returns ------- iterator of (str, bool, str, int) - line: the line - in...
in_code = False lang = None indent = None for l in lines: m = _CODE_MARK.match(l) if m is not None: if not in_code: if m.groups()[1].lower() in _LANGS: lang = m.groups()[1].lower() indent = len(m.groups()[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 _get_blocks(lines): """split lines into code and non-code blocks Returns ------- iterator of (bool, str, list of str) - if it is a code block - source langua...
cur_block = [] pre_lang = None pre_in_code = None for (l, in_code, cur_lang, _) in _parse_code_lines(lines): if in_code != pre_in_code: if pre_in_code and len(cur_block) >= 2: cur_block = cur_block[1:-1] # remove ``` # remove empty lines at head ...
<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_python_block_output(src, global_dict, local_dict): """Evaluate python source codes Returns (bool, str): - True if success - output """
src = '\n'.join([l for l in src.split('\n') if not l.startswith('%') and not 'plt.show()' in l]) ret_status = True err = '' with _string_io() as s: try: exec(src, global_dict, global_dict) except Exception as e: err = str(e) ret_s...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def copy_artifacts(app): """Copies artifacts needed for website presentation"""
dest_path = app.builder.outdir + '/error' source_path = app.builder.srcdir + '/build_version_doc/artifacts' _run_cmd('cd ' + app.builder.srcdir) _run_cmd('rm -rf ' + dest_path) _run_cmd('mkdir -p ' + dest_path) _run_cmd('cp ' + source_path + '/404.html ' + dest_path) _run_cmd('cp ' + source...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def download_caffe_model(model_name, meta_info, dst_dir='./model'): """Download caffe model into disk by the given meta info """
if not os.path.isdir(dst_dir): os.mkdir(dst_dir) model_name = os.path.join(dst_dir, model_name) assert 'prototxt' in meta_info, "missing prototxt url" proto_url, proto_sha1 = meta_info['prototxt'] prototxt = mx.gluon.utils.download(proto_url, model_na...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_caffe_model(model_name, meta_info, dst_dir='./model'): """Download, convert and save a caffe model"""
(prototxt, caffemodel, mean) = download_caffe_model(model_name, meta_info, dst_dir) model_name = os.path.join(dst_dir, model_name) convert_model(prototxt, caffemodel, model_name) if isinstance(mean, str): mx_mean = model_name + '-mean.nd' convert_mean(mean, mx_mean) mean = mx_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 multi_p_run(tot_num, _func, worker, params, n_process): """ Run _func with multi-process using params. """
from multiprocessing import Process, Queue out_q = Queue() procs = [] split_num = split_seq(list(range(0, tot_num)), n_process) print(tot_num, ">>", split_num) split_len = len(split_num) if n_process > split_len: n_process = split_len for i in range(n_process): _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 namedtuple_with_defaults(typename, field_names, default_values=()): """ create a namedtuple with default values """
T = collections.namedtuple(typename, field_names) T.__new__.__defaults__ = (None, ) * len(T._fields) if isinstance(default_values, collections.Mapping): prototype = T(**default_values) else: prototype = T(*default_values) T.__new__.__defaults__ = tuple(prototype) return T
<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_dict(a, b): """ merge dict a, b, with b overriding keys in a """
c = a.copy() c.update(b) return 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 zip_namedtuple(nt_list): """ accept list of namedtuple, return a dict of zipped fields """
if not nt_list: return dict() if not isinstance(nt_list, list): nt_list = [nt_list] for nt in nt_list: assert type(nt) == type(nt_list[0]) ret = {k : [v] for k, v in nt_list[0]._asdict().items()} for nt in nt_list[1:]: for k, v in nt._asdict().items(): re...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def config_as_dict(cfg): """ convert raw configuration to unified dictionary """
ret = cfg.__dict__.copy() # random cropping params del ret['rand_crop_samplers'] assert isinstance(cfg.rand_crop_samplers, list) ret = merge_dict(ret, zip_namedtuple(cfg.rand_crop_samplers)) num_crop_sampler = len(cfg.rand_crop_samplers) ret['num_crop_sampler'] = num_crop_sampler # must sp...
<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_model_metadata(model_file): """ Returns the name and shape information of input and output tensors of the given ONNX model file. Notes ----- This method ...
graph = GraphProto() try: import onnx except ImportError: raise ImportError("Onnx and protobuf need to be installed. " + "Instructions to install - https://github.com/onnx/onnx") model_proto = onnx.load_model(model_file) metadata = graph.get_graph_metadata...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def multi_layer_feature(body, from_layers, num_filters, strides, pads, min_filter=128): """Wrapper function to extract features from base network, attaching extr...
# arguments check assert len(from_layers) > 0 assert isinstance(from_layers[0], str) and len(from_layers[0].strip()) > 0 assert len(from_layers) == len(num_filters) == len(strides) == len(pads) internals = body.get_internals() layers = [] for k, params in enumerate(zip(from_layers, num_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 _apply_weighting(F, loss, weight=None, sample_weight=None): """Apply weighting to loss. Parameters loss : Symbol The loss to be weighted. weight : float or N...
if sample_weight is not None: loss = F.broadcast_mul(loss, sample_weight) if weight is not None: assert isinstance(weight, numeric_types), "weight must be a number" loss = loss * weight return loss
<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_like(F, x, y): """Reshapes x to the same shape as y."""
return x.reshape(y.shape) if F is ndarray else F.reshape_like(x, y)
<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_tv_grad_executor(img, ctx, tv_weight): """create TV gradient executor with input binded on img """
if tv_weight <= 0.0: return None nchannel = img.shape[1] simg = mx.sym.Variable("img") skernel = mx.sym.Variable("kernel") channels = mx.sym.SliceChannel(simg, num_outputs=nchannel) out = mx.sym.Concat(*[ mx.sym.Convolution(data=channels[i], weight=skernel, ...
<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_mnist(): """ Gets MNIST dataset """
np.random.seed(1234) # set seed for deterministic ordering mnist_data = mx.test_utils.get_mnist() X = np.concatenate([mnist_data['train_data'], mnist_data['test_data']]) Y = np.concatenate([mnist_data['train_label'], mnist_data['test_label']]) p = np.random.permutation(X.shape[0]) X = X[p].res...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _split_input_slice(batch_size, work_load_list): """Get input slice from the input shape. Parameters batch_size : int The number of samples in a mini-batch. w...
total_work_load = sum(work_load_list) batch_num_list = [round(work_load * batch_size / total_work_load) for work_load in work_load_list] batch_num_sum = sum(batch_num_list) if batch_num_sum < batch_size: batch_num_list[-1] += batch_size - batch_num_sum slices = [] ...
<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_arguments(symbol): """Check the argument names of symbol. This function checks the duplication of arguments in Symbol. The check is done for feedforwa...
arg_set = set() arg_names = symbol.list_arguments() for name in arg_names: if name in arg_set: raise ValueError(('Find duplicated argument name \"%s\", ' + 'please make the weight name non-duplicated(using name arguments), ' + ...
<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, is_train=False): """Perform a forward pass on each executor."""
for texec in self.train_execs: texec.forward(is_train=is_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 update_metric(self, metric, labels, pre_sliced=False): """Update evaluation metric with label and current outputs."""
for current_exec, (texec, islice) in enumerate(zip(self.train_execs, self.slices)): if not pre_sliced: labels_slice = [label[islice] for label in labels] else: labels_slice = labels[current_exec] metric.update(labels_slice, texec.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 install_monitor(self, monitor): """Install monitor on all executors."""
if self.sym_gen is not None: raise NotImplementedError("Monitoring is not implemented for bucketing") for train_exec in self.execgrp.train_execs: monitor.install(train_exec)
<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): """Set parameter and aux values. Parameters arg_params : list of NDArray Source parameter arrays aux_params : list ...
for texec in self.execgrp.train_execs: texec.copy_params_from(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 update_metric(self, metric, labels, pre_sliced=False): """Update metric with the current executor."""
self.curr_execgrp.update_metric(metric, labels, pre_sliced)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clear(self): """ Clear all contents in the relay memory """
self.states[:] = 0 self.actions[:] = 0 self.rewards[:] = 0 self.terminate_flags[:] = 0 self.top = 0 self.size = 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 process(fname, allow_type): """Process a file."""
fname = str(fname) # HACK: ignore op.h which is automatically generated if fname.endswith('op.h'): return arr = fname.rsplit('.', 1) if fname.find('#') != -1 or arr[-1] not in allow_type: return if arr[-1] in CXX_SUFFIX: _HELPER.process_cpp(fname, arr[-1]) if arr[-1] i...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _print_summary_map(strm, result_map, ftype): """Print summary of certain result map."""
if len(result_map) == 0: return 0 npass = len([x for k, x in result_map.iteritems() if len(x) == 0]) strm.write('=====%d/%d %s files passed check=====\n' % (npass, len(result_map), ftype)) for fname, emap in result_map.iteritems(): if len(emap) == 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 process_cpp(self, path, suffix): """Process a cpp file."""
_cpplint_state.ResetErrorCounts() cpplint.ProcessFile(str(path), _cpplint_state.verbose_level) _cpplint_state.PrintErrorCounts() errors = _cpplint_state.errors_by_category.copy() if suffix == 'h': self.cpp_header_map[str(path)] = errors else: sel...
<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_python(self, path): """Process a python file."""
(pylint_stdout, pylint_stderr) = epylint.py_run( ' '.join([str(path)] + self.pylint_opts), return_std=True) emap = {} print(pylint_stderr.read()) for line in pylint_stdout: sys.stderr.write(line) key = line.split(':')[-1].split('(')[0].strip() ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def print_summary(self, strm): """Print summary of lint."""
nerr = 0 nerr += LintHelper._print_summary_map(strm, self.cpp_header_map, 'cpp-header') nerr += LintHelper._print_summary_map(strm, self.cpp_src_map, 'cpp-soruce') nerr += LintHelper._print_summary_map(strm, self.python_map, 'python') if nerr == 0: strm.write('All pa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _controller(self): """Return the server controller."""
def server_controller(cmd_id, cmd_body, _): """Server controler.""" if not self.init_logginig: # the reason put the codes here is because we cannot get # kvstore.rank earlier head = '%(asctime)-15s Server[' + str( 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 run(self): """Run the server, whose behavior is like. """
_ctrl_proto = ctypes.CFUNCTYPE(None, ctypes.c_int, ctypes.c_char_p, ctypes.c_void_p) check_call(_LIB.MXKVStoreRunServer(self.handle, _ctrl_proto(self._controller()), 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 _make_ndarray_function(handle, name, func_name): """Create a NDArray function from the FunctionHandle."""
code, doc_str = _generate_ndarray_function_code(handle, name, func_name) local = {} exec(code, None, local) # pylint: disable=exec-used ndarray_function = local[func_name] ndarray_function.__name__ = func_name ndarray_function.__doc__ = doc_str ndarray_function.__module__ = 'mxnet.ndarray...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def count_tokens_from_str(source_str, token_delim=' ', seq_delim='\n', to_lower=False, counter_to_update=None): """Counts tokens in the specified string. For tok...
source_str = filter(None, re.split(token_delim + '|' + seq_delim, source_str)) if to_lower: source_str = [t.lower() for t in source_str] if counter_to_update is None: return collections.Counter(source_str) else: counter_to_update.update(source_str) ...
<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(fname): """Loads an array from file. See more details in ``save``. Parameters fname : str The filename. Returns ------- list of NDArray, RowSparseNDArra...
if not isinstance(fname, string_types): raise TypeError('fname required to be a string') out_size = mx_uint() out_name_size = mx_uint() handles = ctypes.POINTER(NDArrayHandle)() names = ctypes.POINTER(ctypes.c_char_p)() check_call(_LIB.MXNDArrayLoad(c_str(fname), ...
<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_frombuffer(buf): """Loads an array dictionary or list from a buffer See more details in ``save``. Parameters buf : str Buffer containing contents of a f...
if not isinstance(buf, string_types + tuple([bytes])): raise TypeError('buf required to be a string or bytes') out_size = mx_uint() out_name_size = mx_uint() handles = ctypes.POINTER(NDArrayHandle)() names = ctypes.POINTER(ctypes.c_char_p)() check_call(_LIB.MXNDArrayLoadFromBuffer(buf, ...
<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(fname, data): """Saves a list of arrays or a dict of str->array to file. Examples of filenames: - ``/path/to/file`` - ``s3://my-bucket/path/to/file`` (i...
if isinstance(data, NDArray): data = [data] handles = c_array(NDArrayHandle, []) if isinstance(data, dict): str_keys = data.keys() nd_vals = data.values() if any(not isinstance(k, string_types) for k in str_keys) or \ any(not isinstance(v, NDArray) for v in nd...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _common_prefix(names): """Get the common prefix for all names"""
if not names: return '' prefix = names[0] for name in names: i = 0 while i < len(prefix) and i < len(name) and prefix[i] == name[i]: i += 1 prefix = prefix[:i] return prefix
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _infer_param_types(in_params, out_params, arg_params, aux_params, default_dtype=mx_real_t): """Utility function that helps in inferring DType of args and aux...
arg_types = None aux_types = None # Get Input symbol details. This will be used to infer types of # other parameters. input_sym_names = [in_param.name for in_param in in_params] # Try to infer input types. If not successful, we will set default dtype. # If successful, we will try to infer...
<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(prefix, params, hint): """Creates prefix and params for new `Block`."""
current = getattr(_BlockScope._current, "value", None) if current is None: if prefix is None: if not hasattr(_name.NameManager._current, "value"): _name.NameManager._current.value = _name.NameManager() prefix = _name.NameManager._current.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 load_parameters(self, filename, ctx=None, allow_missing=False, ignore_extra=False): """Load parameters from file previously saved by `save_parameters`. Param...
loaded = ndarray.load(filename) params = self._collect_params_with_prefix() if not loaded and not params: return if not any('.' in i for i in loaded.keys()): # legacy loading del loaded self.collect_params().load( filename...
<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_forward_pre_hook(self, hook): r"""Registers a forward pre-hook on the block. The hook function is called immediately before :func:`forward`. It shou...
handle = HookHandle() handle.attach(self._forward_pre_hooks, hook) return handle
<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_forward_hook(self, hook): r"""Registers a forward hook on the block. The hook function is called immediately after :func:`forward`. It should not mo...
handle = HookHandle() handle.attach(self._forward_hooks, hook) return handle
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def apply(self, fn): r"""Applies ``fn`` recursively to every child block as well as self. Parameters fn : callable Function to be applied to each submodule, of f...
for cld in self._children.values(): cld.apply(fn) fn(self) 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 cast(self, dtype): """Cast this Block to use another data type. Parameters dtype : str or numpy.dtype The new data type. """
for child in self._children.values(): child.cast(dtype) for _, param in self.params.items(): param.cast(dtype)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _infer_attrs(self, infer_fn, attr, *args): """Generic infer attributes."""
inputs, out = self._get_graph(*args) args, _ = _flatten(args, "input") with warnings.catch_warnings(record=True) as w: arg_attrs, _, aux_attrs = getattr(out, infer_fn)( **{i.name: getattr(j, attr) for i, j in zip(inputs, args)}) if arg_attrs is 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 export(self, path, epoch=0): """Export HybridBlock to json format that can be loaded by `SymbolBlock.imports`, `mxnet.mod.Module` or the C++ interface. .. no...
if not self._cached_graph: raise RuntimeError( "Please first call block.hybridize() and then run forward with " "this block at least once before calling export.") sym = self._cached_graph[1] sym.save('%s-symbol.json'%path) arg_names = set(sym...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def imports(symbol_file, input_names, param_file=None, ctx=None): """Import model previously saved by `HybridBlock.export` or `Module.save_checkpoint` as a Symbo...
sym = symbol.load(symbol_file) if isinstance(input_names, str): input_names = [input_names] inputs = [symbol.var(i) for i in input_names] ret = SymbolBlock(sym, inputs) if param_file is not None: ret.collect_params().load(param_file, ctx=ctx) 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 calc_expectation(grad_dict, num_batches): """Calculates the expectation of the gradients per epoch for each parameter w.r.t number of batches Parameters grad...
for key in grad_dict.keys(): grad_dict[str.format(key+"_expectation")] = mx.ndarray.sum(grad_dict[key], axis=0) / num_batches return grad_dict
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def calc_variance(grad_dict, num_batches, param_names): """Calculates the variance of the gradients per epoch for each parameter w.r.t number of batches Paramete...
for i in range(len(param_names)): diff_sqr = mx.ndarray.square(mx.nd.subtract(grad_dict[param_names[i]], grad_dict[str.format(param_names[i]+"_expectation")])) grad_dict[str.format(param_names[i] + "_variance")] = mx.ndarray.sum(diff_sqr, axis=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 classifer_metrics(label, pred): """ computes f1, precision and recall on the entity class """
prediction = np.argmax(pred, axis=1) label = label.astype(int) pred_is_entity = prediction != not_entity_index label_is_entity = label != not_entity_index corr_pred = (prediction == label) == (pred_is_entity == True) #how many entities are there? num_entities = np.sum(label_is_entity) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def data_iter(batch_size, num_embed, pre_trained_word2vec=False): """Construct data iter Parameters batch_size: int num_embed: int pre_trained_word2vec: boolean ...
print('Loading data...') if pre_trained_word2vec: word2vec = data_helpers.load_pretrained_word2vec('data/rt.vec') x, y = data_helpers.load_data_with_word2vec(word2vec) # reshape for convolution input x = np.reshape(x, (x.shape[0], 1, x.shape[1], x.shape[2])) embedded_siz...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sym_gen(batch_size, sentences_size, num_embed, vocabulary_size, num_label=2, filter_list=None, num_filter=100, dropout=0.0, pre_trained_word2vec=False): """G...
input_x = mx.sym.Variable('data') input_y = mx.sym.Variable('softmax_label') # embedding layer if not pre_trained_word2vec: embed_layer = mx.sym.Embedding(data=input_x, input_dim=vocabulary_size, output_dim=num_embed...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def train(symbol_data, train_iterator, valid_iterator, data_column_names, target_names): """Train cnn model Parameters symbol_data: symbol train_iterator: DataIt...
devs = mx.cpu() # default setting if args.gpus is not None: for i in args.gpus.split(','): mx.gpu(int(i)) devs = mx.gpu() module = mx.mod.Module(symbol_data, data_names=data_column_names, label_names=target_names, context=devs) module.fit(train_data=train_iterator, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def build(args) -> None: """Build using CMake"""
venv_exe = shutil.which('virtualenv') pyexe = shutil.which(args.pyexe) if not venv_exe: logging.warn("virtualenv wasn't found in path, it's recommended to install virtualenv to manage python environments") if not pyexe: logging.warn("Python executable %s not found in path", args.pyexe) ...
<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_helper(attrs, attrs_name, alt_value=None): """Helper function to parse operator attributes in required format."""
tuple_re = re.compile('\([0-9L|,| ]+\)') if not attrs: return alt_value attrs_str = None if attrs.get(attrs_name) is None else str(attrs.get(attrs_name)) if attrs_str is None: return alt_value attrs_match = tuple_re.search(attrs_str) if attrs_match is not None: if attrs_...