Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def evaluate(data_loader): translation_out = [] all_inst_ids = [] avg_loss_denom = 0 avg_loss = 0.0 for _, (src_seq, tgt_seq, src_valid_length, tgt_valid_length, inst_ids) \ in enumerate(data_loader): src_seq = src_seq.as_in_conte...
[ "Evaluate given the data loader\n\n Parameters\n ----------\n data_loader : DataLoader\n\n Returns\n -------\n avg_loss : float\n Average loss\n real_translation_out : list of list of str\n The translation output\n " ]
Please provide a description of the function:def train(): trainer = gluon.Trainer(model.collect_params(), args.optimizer, {'learning_rate': args.lr}) train_data_loader, val_data_loader, test_data_loader \ = dataprocessor.make_dataloader(data_train, data_val, data_test, args) best_valid_bleu =...
[ "Training function." ]
Please provide a description of the function:def get_cache_model(name, dataset_name='wikitext-2', window=2000, theta=0.6, lambdas=0.2, ctx=mx.cpu(), **kwargs): r lm_model, vocab = nlp.model.\ get_model(name, dataset_name=dataset_name, pretrained=True, ctx=ctx, **kwargs) cache_cel...
[ "Returns a cache model using a pre-trained language model.\n\n We implement the neural cache language model proposed in the following work::\n\n @article{grave2016improving,\n title={Improving neural language models with a continuous cache},\n author={Grave, Edouard and Joulin, Armand and Us...
Please provide a description of the function:def train(args): if not args.model.lower() in ['cbow', 'skipgram']: logging.error('Unsupported model %s.', args.model) sys.exit(1) if args.data.lower() == 'toy': data = mx.gluon.data.SimpleDataset(nlp.data.Text8(segment='train')[:2]) ...
[ "Training helper." ]
Please provide a description of the function:def evaluate(args, embedding, vocab, global_step, eval_analogy=False): if 'eval_tokens' not in globals(): global eval_tokens eval_tokens_set = evaluation.get_tokens_in_evaluation_datasets(args) if not args.no_eval_analogy: eval_t...
[ "Evaluation helper" ]
Please provide a description of the function:def get_field(self, field): idx = self._keys.index(field) return self._data[idx]
[ "Return the dataset corresponds to the provided key.\n\n Example::\n a = np.ones((2,2))\n b = np.zeros((2,2))\n np.savez('data.npz', a=a, b=b)\n dataset = NumpyDataset('data.npz')\n data_a = dataset.get_field('a')\n data_b = dataset.get_field(...
Please provide a description of the function:def get_final_text(pred_text, orig_text, tokenizer): # When we created the data, we kept track of the alignment between original # (whitespace tokenized) tokens and our WordPiece tokenized tokens. So # now `orig_text` contains the span of our original text ...
[ "Project the tokenized prediction back to the original text." ]
Please provide a description of the function:def predictions(dev_dataset, all_results, tokenizer, max_answer_length=64, null_score_diff_threshold=0.0, n_best_size=10, version_2=False): _PrelimPrediction = namedtupl...
[ "Get prediction results\n\n Parameters\n ----------\n dev_dataset: dataset\n Examples of transform.\n all_results: dict\n A dictionary containing model prediction results.\n tokenizer: callable\n Tokenizer function.\n max_answer_length: int, default 64\n Maximum length ...
Please provide a description of the function:def get_F1_EM(dataset, predict_data): f1 = exact_match = total = 0 for record in dataset: total += 1 if record[1] not in predict_data: message = 'Unanswered question ' + record[1] + \ ' will receive score 0.' ...
[ "Calculate the F1 and EM scores of the predicted results.\n Use only with the SQuAD1.1 dataset.\n\n Parameters\n ----------\n dataset_file: string\n Path to the data file.\n predict_data: dict\n All final predictions.\n\n Returns\n -------\n scores: dict\n F1 and EM scor...
Please provide a description of the function:def preprocess_data(tokenizer, task, batch_size, dev_batch_size, max_len, pad=False): # transformation trans = BERTDatasetTransform( tokenizer, max_len, labels=task.get_labels(), pad=pad, pair=task.is_pair, label_d...
[ "Data preparation function." ]
Please provide a description of the function:def evaluate(dataloader_eval, metric): metric.reset() for _, seqs in enumerate(dataloader_eval): input_ids, valid_len, type_ids, label = seqs out = model( input_ids.as_in_context(ctx), type_ids.as_in_context(ctx), valid_le...
[ "Evaluate the model on validation dataset.\n " ]
Please provide a description of the function:def log_train(batch_id, batch_num, metric, step_loss, log_interval, epoch_id, learning_rate): metric_nm, metric_val = metric.get() if not isinstance(metric_nm, list): metric_nm = [metric_nm] metric_val = [metric_val] train_str = '[Epoch %d B...
[ "Generate and print out the log message for training.\n " ]
Please provide a description of the function:def log_inference(batch_id, batch_num, metric, step_loss, log_interval): metric_nm, metric_val = metric.get() if not isinstance(metric_nm, list): metric_nm = [metric_nm] metric_val = [metric_val] eval_str = '[Batch %d/%d] loss=%.4f, metrics:...
[ "Generate and print out the log message for inference.\n " ]
Please provide a description of the function:def train(metric): logging.info('Now we are doing BERT classification training on %s!', ctx) optimizer_params = {'learning_rate': lr, 'epsilon': epsilon, 'wd': 0.01} try: trainer = gluon.Trainer( model.collect_params(), args....
[ "Training function." ]
Please provide a description of the function:def inference(metric): logging.info('Now we are doing BERT classification inference on %s!', ctx) model = BERTClassifier(bert, dropout=0.1, num_classes=len(task.get_labels())) model.hybridize(static_alloc=True) model.load_parameters(model_parameters, ct...
[ "Inference function." ]
Please provide a description of the function:def preprocess_dataset(dataset, question_max_length, context_max_length): vocab_provider = VocabProvider(dataset) transformer = SQuADTransform( vocab_provider, question_max_length, context_max_length) processed_dataset = SimpleDataset( datase...
[ "Process SQuAD dataset by creating NDArray version of data\n\n :param Dataset dataset: SQuAD dataset\n :param int question_max_length: Maximum length of question (padded or trimmed to that size)\n :param int context_max_length: Maximum length of context (padded or trimmed to that size)\n\n Returns\n ...
Please provide a description of the function:def _get_answer_spans(answer_list, answer_start_list): return [(answer_start_list[i], answer_start_list[i] + len(answer)) for i, answer in enumerate(answer_list)]
[ "Find all answer spans from the context, returning start_index and end_index\n\n :param list[str] answer_list: List of all answers\n :param list[int] answer_start_list: List of all answers' start indices\n\n Returns\n -------\n List[Tuple]\n list of Tuple(answer_start_i...
Please provide a description of the function:def get_word_level_vocab(self): def simple_tokenize(source_str, token_delim=' ', seq_delim='\n'): return list(filter(None, re.split(token_delim + '|' + seq_delim, source_str))) return VocabProvider._create_squad_vocab(simple_tokenize, s...
[ "Provides word level vocabulary\n\n Returns\n -------\n Vocab\n Word level vocabulary\n " ]
Please provide a description of the function:def hybrid_forward(self, F, *states): # pylint: disable=arguments-differ # pylint: disable=unused-argument if self._beta != 0: if states: means = [self._beta * (state[1:] - state[:-1]).__pow__(2).mean() ...
[ "\n Parameters\n ----------\n states : list\n the stack outputs from RNN, which consists of output from each time step (TNC).\n\n Returns\n --------\n loss : NDArray\n loss tensor with shape (batch_size,). Dimensions other than batch_axis are averaged ...
Please provide a description of the function:def _tokenize(self, text): text = self._clean_text(text) # This was added on November 1st, 2018 for the multilingual and Chinese # models. This is also applied to the English models now, but it doesn't # matter since the English mode...
[ "Tokenizes a piece of text." ]
Please provide a description of the function:def _clean_text(self, text): output = [] for char in text: cp = ord(char) if cp in (0, 0xfffd) or self._is_control(char): continue if self._is_whitespace(char): output.append(' ') ...
[ "Performs invalid character removal and whitespace cleanup on text." ]
Please provide a description of the function:def _is_control(self, char): # These are technically control characters but we count them as whitespace # characters. if char in ['\t', '\n', '\r']: return False cat = unicodedata.category(char) if cat.startswith('...
[ "Checks whether `chars` is a control character." ]
Please provide a description of the function:def _run_split_on_punc(self, text): chars = list(text) i = 0 start_new_word = True output = [] while i < len(chars): char = chars[i] if self._is_punctuation(char): output.append([char]) ...
[ "Splits punctuation on a piece of text." ]
Please provide a description of the function:def _is_punctuation(self, char): cp = ord(char) # We treat all non-letter/number ASCII as punctuation. # Characters such as "^", "$", and "`" are not in the Unicode # Punctuation class but we treat them as punctuation anyways, for ...
[ "Checks whether `chars` is a punctuation character." ]
Please provide a description of the function:def _is_whitespace(self, char): # \t, \n, and \r are technically contorl characters but we treat them # as whitespace since they are generally considered as such. if char in [' ', '\t', '\n', '\r']: return True cat = unico...
[ "Checks whether `chars` is a whitespace character." ]
Please provide a description of the function:def _whitespace_tokenize(self, text): text = text.strip() tokens = text.split() return tokens
[ "Runs basic whitespace cleaning and splitting on a piece of text." ]
Please provide a description of the function:def _tokenize_wordpiece(self, text): output_tokens = [] for token in self.basic_tokenizer._whitespace_tokenize(text): chars = list(token) if len(chars) > self.max_input_chars_per_word: output_tokens.append(sel...
[ "Tokenizes a piece of text into its word pieces.\n\n This uses a greedy longest-match-first algorithm to perform tokenization\n using the given vocabulary.\n\n For example:\n input = \"unaffable\"\n output = [\"un\", \"##aff\", \"##able\"]\n\n Args:\n text: A s...
Please provide a description of the function:def _truncate_seq_pair(self, tokens_a, tokens_b, max_length): # This is a simple heuristic which will always truncate the longer sequence # one token at a time. This makes more sense than truncating an equal percent # of tokens from each, sin...
[ "Truncates a sequence pair in place to the maximum length." ]
Please provide a description of the function:def get_args(): parser = argparse.ArgumentParser( description='Word embedding evaluation with Gluon.', formatter_class=argparse.ArgumentDefaultsHelpFormatter) # Embeddings arguments group = parser.add_argument_group('Embedding arguments') ...
[ "Construct the argument parser." ]
Please provide a description of the function:def validate_args(args): if args.list_embedding_sources: print('Listing all sources for {} embeddings.'.format( args.embedding_name)) print('Specify --embedding-name if you wish to ' 'list sources of other embeddings') ...
[ "Validate provided arguments and act on --help." ]
Please provide a description of the function:def load_embedding_from_path(args): if args.embedding_path.endswith('.bin'): with utils.print_time('load fastText model.'): model = \ nlp.model.train.FasttextEmbeddingModel.load_fasttext_format( args.embedding_...
[ "Load a TokenEmbedding." ]
Please provide a description of the function:def grad_global_norm(parameters, max_norm): # collect gradient arrays arrays = [] idx = 0 for p in parameters: if p.grad_req != 'null': p_grads = p.list_grad() arrays.append(p_grads[idx % len(p_grads)]) idx += ...
[ "Calculate the 2-norm of gradients of parameters, and how much they should be scaled down\n such that their 2-norm does not exceed `max_norm`.\n\n If gradients exist for more than one context for a parameter, user needs to explicitly call\n ``trainer.allreduce_grads`` so that the gradients are summed first...
Please provide a description of the function:def backward(self, loss): with mx.autograd.record(): if isinstance(loss, (tuple, list)): ls = [l * self._scaler.loss_scale for l in loss] else: ls = loss * self._scaler.loss_scale mx.autograd.ba...
[ "backward propagation with loss" ]
Please provide a description of the function:def step(self, batch_size, max_norm=None): self.fp32_trainer.allreduce_grads() step_size = batch_size * self._scaler.loss_scale if max_norm: norm, ratio, is_finite = grad_global_norm(self.fp32_trainer._params, ...
[ "Makes one step of parameter update. Should be called after\n `fp16_optimizer.backward()`, and outside of `record()` scope.\n\n Parameters\n ----------\n batch_size : int\n Batch size of data processed. Gradient will be normalized by `1/batch_size`.\n Set this to 1 ...
Please provide a description of the function:def has_overflow(self, params): is_not_finite = 0 for param in params: if param.grad_req != 'null': grad = param.list_grad()[0] is_not_finite += mx.nd.contrib.isnan(grad).sum() is_not_finite...
[ " detect inf and nan " ]
Please provide a description of the function:def update_scale(self, overflow): iter_since_rescale = self._num_steps - self._last_rescale_iter if overflow: self._last_overflow_iter = self._num_steps self._overflows_since_rescale += 1 percentage = self._overflo...
[ "dynamically update loss scale" ]
Please provide a description of the function:def stats(self): ret = '{name}:\n' \ ' sample_num={sample_num}, batch_num={batch_num}\n' \ ' key={bucket_keys}\n' \ ' cnt={bucket_counts}\n' \ ' batch_size={bucket_batch_sizes}'\ .format(name=se...
[ "Return a string representing the statistics of the bucketing sampler.\n\n Returns\n -------\n ret : str\n String representing the statistics of the buckets.\n " ]
Please provide a description of the function:def train(): print(model) from_epoch = 0 model.initialize(mx.init.Xavier(factor_type='out'), ctx=context) trainer_params = {'learning_rate': args.lr, 'wd': 0, 'eps': args.eps} trainer = gluon.Trainer(model.collect_params(), 'adagrad', trainer_params)...
[ "Training loop for language model.\n " ]
Please provide a description of the function:def evaluate(): print(eval_model) eval_model.initialize(mx.init.Xavier(), ctx=context[0]) eval_model.hybridize(static_alloc=True, static_shape=True) epoch = args.from_epoch if args.from_epoch else 0 while epoch < args.epochs: checkpoint_name ...
[ " Evaluate loop for the trained model " ]
Please provide a description of the function:def load_dataset(data_name): if data_name == 'MR' or data_name == 'Subj': train_dataset, output_size = _load_file(data_name) vocab, max_len = _build_vocab(data_name, train_dataset, []) train_dataset, train_data_lengths = _preprocess_dataset(t...
[ "Load sentiment dataset." ]
Please provide a description of the function:def get_home_dir(): _home_dir = os.environ.get('MXNET_HOME', os.path.join('~', '.mxnet')) # expand ~ to actual path _home_dir = os.path.expanduser(_home_dir) return _home_dir
[ "Get home directory for storing datasets/models/pre-trained word embeddings" ]
Please provide a description of the function:def read_dataset(args, dataset): path = os.path.join(vars(args)[dataset]) logger.info('reading data from {}'.format(path)) examples = [line.strip().split('\t') for line in open(path)] if args.max_num_examples > 0: examples = examples[:args.max_nu...
[ "\n Read dataset from tokenized files.\n " ]
Please provide a description of the function:def build_vocab(dataset): counter = nlp.data.count_tokens([w for e in dataset for s in e[:2] for w in s], to_lower=True) vocab = nlp.Vocab(counter) return vocab
[ "\n Build vocab given a dataset.\n " ]
Please provide a description of the function:def prepare_data_loader(args, dataset, vocab, test=False): # Preprocess dataset = dataset.transform(lambda s1, s2, label: (vocab(s1), vocab(s2), label), lazy=False) # Batching batchify_fn = btf.Tuple(btf.Pad(), btf.Pad(),...
[ "\n Read data and build data loader.\n " ]
Please provide a description of the function:def mxnet_prefer_gpu(): gpu = int(os.environ.get('MXNET_GPU', default=0)) if gpu in mx.test_utils.list_gpus(): return mx.gpu(gpu) return mx.cpu()
[ "If gpu available return gpu, else cpu\n\n Returns\n -------\n context : Context\n The preferable GPU context.\n " ]
Please provide a description of the function:def init_logger(root_dir, name="train.log"): os.makedirs(root_dir, exist_ok=True) log_formatter = logging.Formatter("%(message)s") logger = logging.getLogger(name) file_handler = logging.FileHandler("{0}/{1}".format(root_dir, name), mode='w') file_ha...
[ "Initialize a logger\n\n Parameters\n ----------\n root_dir : str\n directory for saving log\n name : str\n name of logger\n\n Returns\n -------\n logger : logging.Logger\n a logger\n " ]
Please provide a description of the function:def orthonormal_VanillaLSTMBuilder(lstm_layers, input_dims, lstm_hiddens, dropout_x=0., dropout_h=0., debug=False): assert lstm_layers == 1, 'only accept one layer lstm' W = orthonormal_initializer(lstm_hiddens, lstm_hiddens + input_dims, debug) W_h, W_x = W...
[ "Build a standard LSTM cell, with variational dropout,\n with weights initialized to be orthonormal (https://arxiv.org/abs/1312.6120)\n\n Parameters\n ----------\n lstm_layers : int\n Currently only support one layer\n input_dims : int\n word vector dimensions\n lstm_hiddens : int\n ...
Please provide a description of the function:def biLSTM(f_lstm, b_lstm, inputs, batch_size=None, dropout_x=0., dropout_h=0.): for f, b in zip(f_lstm, b_lstm): inputs = nd.Dropout(inputs, dropout_x, axes=[0]) # important for variational dropout fo, fs = f.unroll(length=inputs.shape[0], inputs=i...
[ "Feature extraction through BiLSTM\n\n Parameters\n ----------\n f_lstm : VariationalDropoutCell\n Forward cell\n b_lstm : VariationalDropoutCell\n Backward cell\n inputs : NDArray\n seq_len x batch_size\n dropout_x : float\n Variational dropout on inputs\n dropout_h...
Please provide a description of the function:def bilinear(x, W, y, input_size, seq_len, batch_size, num_outputs=1, bias_x=False, bias_y=False): if bias_x: x = nd.concat(x, nd.ones((1, seq_len, batch_size)), dim=0) if bias_y: y = nd.concat(y, nd.ones((1, seq_len, batch_size)), dim=0) nx...
[ "Do xWy\n\n Parameters\n ----------\n x : NDArray\n (input_size x seq_len) x batch_size\n W : NDArray\n (num_outputs x ny) x nx\n y : NDArray\n (input_size x seq_len) x batch_size\n input_size : int\n input dimension\n seq_len : int\n sequence length\n batc...
Please provide a description of the function:def arc_argmax(parse_probs, length, tokens_to_keep, ensure_tree=True): if ensure_tree: I = np.eye(len(tokens_to_keep)) # block loops and pad heads parse_probs = parse_probs * tokens_to_keep * (1 - I) parse_preds = np.argmax(parse_prob...
[ "MST\n Adopted from Timothy Dozat https://github.com/tdozat/Parser/blob/master/lib/models/nn.py\n\n Parameters\n ----------\n parse_probs : NDArray\n seq_len x seq_len, the probability of arcs\n length : NDArray\n real sentence length\n tokens_to_keep : NDArray\n mask matrix\n...
Please provide a description of the function:def rel_argmax(rel_probs, length, ensure_tree=True): if ensure_tree: rel_probs[:, ParserVocabulary.PAD] = 0 root = ParserVocabulary.ROOT tokens = np.arange(1, length) rel_preds = np.argmax(rel_probs, axis=1) roots = np.where(r...
[ "Fix the relation prediction by heuristic rules\n\n Parameters\n ----------\n rel_probs : NDArray\n seq_len x rel_size\n length :\n real sentence length\n ensure_tree :\n whether to apply rules\n Returns\n -------\n rel_preds : np.ndarray\n prediction of relations...
Please provide a description of the function:def reshape_fortran(tensor, shape): return tensor.T.reshape(tuple(reversed(shape))).T
[ "The missing Fortran reshape for mx.NDArray\n\n Parameters\n ----------\n tensor : NDArray\n source tensor\n shape : NDArray\n desired shape\n\n Returns\n -------\n output : NDArray\n reordered result\n " ]
Please provide a description of the function:def update(self, current, values=[], exact=[], strict=[]): for k, v in values: if k not in self.sum_values: self.sum_values[k] = [v * (current - self.seen_so_far), current - self.seen_so_far] self.unique_values.ap...
[ "\n Updates the progress bar.\n # Arguments\n current: Index of current step.\n values: List of tuples (name, value_for_last_step).\n The progress bar will display averages for these values.\n exact: List of tuples (name, value_for_last_step).\n ...
Please provide a description of the function:def get_batch(data_source, i, seq_len=None): seq_len = min(seq_len if seq_len else args.bptt, len(data_source) - 1 - i) data = data_source[i:i+seq_len] target = data_source[i+1:i+1+seq_len] return data, target
[ "Get mini-batches of the dataset.\n\n Parameters\n ----------\n data_source : NDArray\n The dataset is evaluated on.\n i : int\n The index of the batch, starting from 0.\n seq_len : int\n The length of each sample in the batch.\n\n Returns\n -------\n data: NDArray\n ...
Please provide a description of the function:def evaluate(data_source, batch_size, params_file_name, ctx=None): total_L = 0.0 ntotal = 0 model_eval.load_parameters(params_file_name, context) hidden = model_eval.begin_state(batch_size=batch_size, func=mx.nd.zeros, ctx=context[0]) i = 0 wh...
[ "Evaluate the model on the dataset.\n\n Parameters\n ----------\n data_source : NDArray\n The dataset is evaluated on.\n batch_size : int\n The size of the mini-batch.\n params_file_name : str\n The parameter file to use to evaluate,\n e.g., val.params or args.save\n ct...
Please provide a description of the function:def train(): ntasgd = False best_val = float('Inf') start_train_time = time.time() parameters = model.collect_params() param_dict_avg = None t = 0 avg_trigger = 0 n = 5 valid_losses = [] for epoch in range(args.epochs): to...
[ "Training loop for awd language model.\n\n " ]
Please provide a description of the function:def register(class_): if issubclass(class_, WordEmbeddingSimilarityFunction): register_ = registry.get_register_func( WordEmbeddingSimilarityFunction, 'word embedding similarity evaluation function') elif issubclass(class_, WordE...
[ "Registers a new word embedding evaluation function.\n\n Once registered, we can create an instance with\n :func:`~gluonnlp.embedding.evaluation.create`.\n\n Examples\n --------\n >>> @gluonnlp.embedding.evaluation.register\n ... class MySimilarityFunction(gluonnlp.embedding.evaluation.WordEmbeddi...
Please provide a description of the function:def create(kind, name, **kwargs): if kind not in _REGSITRY_KIND_CLASS_MAP.keys(): raise KeyError( 'Cannot find `kind` {}. Use ' '`list_evaluation_functions(kind=None).keys()` to get' 'all the valid kinds of evaluation func...
[ "Creates an instance of a registered word embedding evaluation function.\n\n Parameters\n ----------\n kind : ['similarity', 'analogy']\n Return only valid names for similarity, analogy or both kinds of\n functions.\n name : str\n The evaluation function name (case-insensitive).\n\n...
Please provide a description of the function:def list_evaluation_functions(kind=None): if kind is None: kind = tuple(_REGSITRY_KIND_CLASS_MAP.keys()) if not isinstance(kind, tuple): if kind not in _REGSITRY_KIND_CLASS_MAP.keys(): raise KeyError( 'Cannot find `k...
[ "Get valid word embedding functions names.\n\n Parameters\n ----------\n kind : ['similarity', 'analogy', None]\n Return only valid names for similarity, analogy or both kinds of functions.\n\n Returns\n -------\n dict or list:\n A list of all the valid evaluation function names for ...
Please provide a description of the function:def hybrid_forward(self, F, words1, words2, weight): # pylint: disable=arguments-differ embeddings_words1 = F.Embedding(words1, weight, input_dim=self._vocab_size, output_dim=se...
[ "Predict the similarity of words1 and words2.\n\n Parameters\n ----------\n words1 : Symbol or NDArray\n The indices of the words the we wish to compare to the words in words2.\n words2 : Symbol or NDArray\n The indices of the words the we wish to compare to the wor...
Please provide a description of the function:def hybrid_forward(self, F, words1, words2, words3): # pylint: disable=arguments-differ, unused-argument return self.analogy(words1, words2, words3)
[ "Compute analogies for given question words.\n\n Parameters\n ----------\n words1 : Symbol or NDArray\n Word indices of first question words. Shape (batch_size, ).\n words2 : Symbol or NDArray\n Word indices of second question words. Shape (batch_size, ).\n w...
Please provide a description of the function:def evaluate(data_source, batch_size, ctx=None): total_L = 0 hidden = cache_cell.\ begin_state(func=mx.nd.zeros, batch_size=batch_size, ctx=context[0]) next_word_history = None cache_history = None for i in range(0, len(data_source) - 1, args...
[ "Evaluate the model on the dataset with cache model.\n\n Parameters\n ----------\n data_source : NDArray\n The dataset is evaluated on.\n batch_size : int\n The size of the mini-batch.\n ctx : mx.cpu() or mx.gpu()\n The context of the computation.\n\n Returns\n -------\n ...
Please provide a description of the function:def get_model(name, dataset_name='wikitext-2', **kwargs): models = {'bert_12_768_12': bert_12_768_12, 'bert_24_1024_16': bert_24_1024_16} name = name.lower() if name not in models: raise ValueError( 'Model %s is not supporte...
[ "Returns a pre-defined model by name.\n\n Parameters\n ----------\n name : str\n Name of the model.\n dataset_name : str or None, default 'wikitext-2'.\n If None, then vocab is required, for specifying embedding weight size, and is directly\n returned.\n vocab : gluonnlp.Vocab or...
Please provide a description of the function:def bert_12_768_12(dataset_name=None, vocab=None, pretrained=True, ctx=mx.cpu(), root=os.path.join(get_home_dir(), 'models'), use_pooler=True, use_decoder=True, use_classifier=True, input_size=None, seq_length=None, **...
[ "Static BERT BASE model.\n\n The number of layers (L) is 12, number of units (H) is 768, and the\n number of self-attention heads (A) is 12.\n\n Parameters\n ----------\n dataset_name : str or None, default None\n Options include 'book_corpus_wiki_en_cased', 'book_corpus_wiki_en_uncased',\n ...
Please provide a description of the function:def hybrid_forward(self, F, inputs, token_types, valid_length=None, masked_positions=None): # pylint: disable=arguments-differ # pylint: disable=unused-argument outputs = [] seq_out, attention_out = self._encode_sequence(F, inputs, to...
[ "Generate the representation given the inputs.\n\n This is used in training or fine-tuning a static (hybridized) BERT model.\n " ]
Please provide a description of the function:def load_parameters(self, filename, ctx=mx.cpu()): # pylint: disable=arguments-differ self.lm_model.load_parameters(filename, ctx=ctx)
[ "Load parameters from file.\n\n filename : str\n Path to parameter file.\n ctx : Context or list of Context, default cpu()\n Context(s) initialize loaded parameters on.\n " ]
Please provide a description of the function:def forward(self, inputs, target, next_word_history, cache_history, begin_state=None): # pylint: disable=arguments-differ output, hidden, encoder_hs, _ = \ super(self.lm_model.__class__, self.lm_model).\ forward(inputs, begin_stat...
[ "Defines the forward computation for cache cell. Arguments can be either\n :py:class:`NDArray` or :py:class:`Symbol`.\n\n Parameters\n ----------\n inputs: NDArray\n The input data\n target: NDArray\n The label\n next_word_history: NDArray\n ...
Please provide a description of the function:def put(self, x): if self._num_serial > 0 or len(self._threads) == 0: self._num_serial -= 1 out = self._parallizable.forward_backward(x) self._out_queue.put(out) else: self._in_queue.put(x)
[ "Assign input `x` to an available worker and invoke\n `parallizable.forward_backward` with x. " ]
Please provide a description of the function:def from_json(cls, json_str): vocab_dict = json.loads(json_str) unknown_token = vocab_dict.get('unknown_token') bert_vocab = cls(unknown_token=unknown_token) bert_vocab._idx_to_token = vocab_dict.get('idx_to_token') bert_voca...
[ "Deserialize BERTVocab object from json string.\n\n Parameters\n ----------\n json_str : str\n Serialized json string of a BERTVocab object.\n\n Returns\n -------\n BERTVocab\n " ]
Please provide a description of the function:def forward(self, inputs, begin_state=None): # pylint: disable=arguments-differ encoded = self.embedding(inputs) if not begin_state: begin_state = self.begin_state(batch_size=inputs.shape[1]) encoded_raw = [] encoded_dropp...
[ "Defines the forward computation. Arguments can be either\n :py:class:`NDArray` or :py:class:`Symbol`.\n\n Parameters\n -----------\n inputs : NDArray\n input tensor with shape `(sequence_length, batch_size)`\n when `layout` is \"TNC\".\n begin_state : list\n...
Please provide a description of the function:def forward(self, inputs, label, begin_state, sampled_values): # pylint: disable=arguments-differ encoded = self.embedding(inputs) length = inputs.shape[0] batch_size = inputs.shape[1] encoded, out_states = self.encoder.unroll(length,...
[ "Defines the forward computation.\n\n Parameters\n -----------\n inputs : NDArray\n input tensor with shape `(sequence_length, batch_size)`\n when `layout` is \"TNC\".\n begin_state : list\n initial recurrent state tensor with length equals to num_layers*...
Please provide a description of the function:def hybrid_forward(self, F, center, context, center_words): # negatives sampling negatives = [] mask = [] for _ in range(self._kwargs['num_negatives']): negatives.append(self.negatives_sampler(center_words)) m...
[ "SkipGram forward pass.\n\n Parameters\n ----------\n center : mxnet.nd.NDArray or mxnet.sym.Symbol\n Sparse CSR array of word / subword indices of shape (batch_size,\n len(token_to_idx) + num_subwords). Embedding for center words are\n computed via F.sparse.dot...
Please provide a description of the function:def evaluate(dataloader): total_L = 0.0 total_sample_num = 0 total_correct_num = 0 start_log_interval_time = time.time() print('Begin Testing...') for i, ((data, valid_length), label) in enumerate(dataloader): data = mx.nd.transpose(data....
[ "Evaluate network on the specified dataset" ]
Please provide a description of the function:def train(): start_pipeline_time = time.time() # Training/Testing best_valid_acc = 0 stop_early = 0 for epoch in range(args.epochs): # Epoch training stats start_epoch_time = time.time() epoch_L = 0.0 epoch_sent_num =...
[ "Training process" ]
Please provide a description of the function:def hybrid_forward(self, F, data, valid_length): # pylint: disable=arguments-differ # Data will have shape (T, N, C) if self._use_mean_pool: masked_encoded = F.SequenceMask(data, sequence_length...
[ "Forward logic" ]
Please provide a description of the function:def hybrid_forward(self, F, inputs, states, i2h_weight, h2h_weight, h2r_weight, i2h_bias, h2h_bias): r prefix = 't%d_'%self._counter i2h = F.FullyConnected(data=inputs, weight=i2h_weight, bias=i2h_bias, ...
[ "Hybrid forward computation for Long-Short Term Memory Projected network cell\n with cell clip and projection clip.\n\n Parameters\n ----------\n inputs : input tensor with shape `(batch_size, input_size)`.\n states : a list of two initial recurrent state tensors, with shape\n ...
Please provide a description of the function:def clip_grad_global_norm(parameters, max_norm, check_isfinite=True): def _norm(array): if array.stype == 'default': x = array.reshape((-1)) return nd.dot(x, x) return array.norm().square() arrays = [] i = 0 for p...
[ "Rescales gradients of parameters so that the sum of their 2-norm is smaller than `max_norm`.\n If gradients exist for more than one context for a parameter, user needs to explicitly call\n ``trainer.allreduce_grads`` so that the gradients are summed first before calculating\n the 2-norm.\n\n .. note::\...
Please provide a description of the function:def train(data_train, model, nsp_loss, mlm_loss, vocab_size, ctx, store): mlm_metric = nlp.metric.MaskedAccuracy() nsp_metric = nlp.metric.MaskedAccuracy() mlm_metric.reset() nsp_metric.reset() lr = args.lr optim_params = {'learning_rate': lr, '...
[ "Training function." ]
Please provide a description of the function:def forward_backward(self, x): with mx.autograd.record(): (ls, next_sentence_label, classified, masked_id, decoded, \ masked_weight, ls1, ls2, valid_length) = forward(x, self._model, self._mlm_loss, ...
[ "forward backward implementation" ]
Please provide a description of the function:def log_info(self, logger): logger.info('#words in training set: %d' % self._words_in_train_data) logger.info("Vocab info: #words %d, #tags %d #rels %d" % (self.vocab_size, self.tag_size, self.rel_size))
[ "Print statistical information via the provided logger\n\n Parameters\n ----------\n logger : logging.Logger\n logger created using logging.getLogger()\n " ]
Please provide a description of the function:def _add_pret_words(self, pret_embeddings): words_in_train_data = set(self._id2word) pret_embeddings = gluonnlp.embedding.create(pret_embeddings[0], source=pret_embeddings[1]) for idx, token in enumerate(pret_embeddings.idx_to_token): ...
[ "Read pre-trained embedding file for extending vocabulary\n\n Parameters\n ----------\n pret_embeddings : tuple\n (embedding_name, source), used for gluonnlp.embedding.create(embedding_name, source)\n " ]
Please provide a description of the function:def get_pret_embs(self, word_dims=None): assert (self._pret_embeddings is not None), "No pretrained file provided." pret_embeddings = gluonnlp.embedding.create(self._pret_embeddings[0], source=self._pret_embeddings[1]) embs = [None] * len(sel...
[ "Read pre-trained embedding file\n\n Parameters\n ----------\n word_dims : int or None\n vector size. Use `None` for auto-infer\n Returns\n -------\n numpy.ndarray\n T x C numpy NDArray\n " ]
Please provide a description of the function:def get_word_embs(self, word_dims): if self._pret_embeddings is not None: return np.random.randn(self.words_in_train, word_dims).astype(np.float32) return np.zeros((self.words_in_train, word_dims), dtype=np.float32)
[ "Get randomly initialized embeddings when pre-trained embeddings are used, otherwise zero vectors\n\n Parameters\n ----------\n word_dims : int\n word vector size\n Returns\n -------\n numpy.ndarray\n T x C numpy NDArray\n " ]
Please provide a description of the function:def get_tag_embs(self, tag_dims): return np.random.randn(self.tag_size, tag_dims).astype(np.float32)
[ "Randomly initialize embeddings for tag\n\n Parameters\n ----------\n tag_dims : int\n tag vector size\n\n Returns\n -------\n numpy.ndarray\n random embeddings\n " ]
Please provide a description of the function:def word2id(self, xs): if isinstance(xs, list): return [self._word2id.get(x, self.UNK) for x in xs] return self._word2id.get(xs, self.UNK)
[ "Map word(s) to its id(s)\n\n Parameters\n ----------\n xs : str or list\n word or a list of words\n\n Returns\n -------\n int or list\n id or a list of ids\n " ]
Please provide a description of the function:def id2word(self, xs): if isinstance(xs, list): return [self._id2word[x] for x in xs] return self._id2word[xs]
[ "Map id(s) to word(s)\n\n Parameters\n ----------\n xs : int\n id or a list of ids\n\n Returns\n -------\n str or list\n word or a list of words\n " ]
Please provide a description of the function:def rel2id(self, xs): if isinstance(xs, list): return [self._rel2id[x] for x in xs] return self._rel2id[xs]
[ "Map relation(s) to id(s)\n\n Parameters\n ----------\n xs : str or list\n relation\n\n Returns\n -------\n int or list\n id(s) of relation\n " ]
Please provide a description of the function:def id2rel(self, xs): if isinstance(xs, list): return [self._id2rel[x] for x in xs] return self._id2rel[xs]
[ "Map id(s) to relation(s)\n\n Parameters\n ----------\n xs : int\n id or a list of ids\n\n Returns\n -------\n str or list\n relation or a list of relations\n " ]
Please provide a description of the function:def tag2id(self, xs): if isinstance(xs, list): return [self._tag2id.get(x, self.UNK) for x in xs] return self._tag2id.get(xs, self.UNK)
[ "Map tag(s) to id(s)\n\n Parameters\n ----------\n xs : str or list\n tag or tags\n\n Returns\n -------\n int or list\n id(s) of tag(s)\n " ]
Please provide a description of the function:def idx_sequence(self): return [x[1] for x in sorted(zip(self._record, list(range(len(self._record)))))]
[ "Indices of sentences when enumerating data set from batches.\n Useful when retrieving the correct order of sentences\n\n Returns\n -------\n list\n List of ids ranging from 0 to #sent -1\n " ]
Please provide a description of the function:def get_batches(self, batch_size, shuffle=True): batches = [] for bkt_idx, bucket in enumerate(self._buckets): bucket_size = bucket.shape[1] n_tokens = bucket_size * self._bucket_lengths[bkt_idx] n_splits = min(max...
[ "Get batch iterator\n\n Parameters\n ----------\n batch_size : int\n size of one batch\n shuffle : bool\n whether to shuffle batches. Don't set to True when evaluating on dev or test set.\n Returns\n -------\n tuple\n word_inputs, tag...
Please provide a description of the function:def create_ngram_set(input_list, ngram_value=2): return set(zip(*[input_list[i:] for i in range(ngram_value)]))
[ "\n Extract a set of n-grams from a list of integers.\n >>> create_ngram_set([1, 4, 9, 4, 1, 4], ngram_value=2)\n {(4, 9), (4, 1), (1, 4), (9, 4)}\n >>> create_ngram_set([1, 4, 9, 4, 1, 4], ngram_value=3)\n [(1, 4, 9), (4, 9, 4), (9, 4, 1), (4, 1, 4)]\n " ]
Please provide a description of the function:def add_ngram(sequences, token_indice, ngram_range=2): new_sequences = [] for input_list in sequences: new_list = input_list[:] for i in range(len(new_list) - ngram_range + 1): for ngram_value in range(2, ngram_range + 1): ...
[ "\n Augment the input list of list (sequences) by appending n-grams values.\n Example: adding bi-gram\n >>> sequences = [[1, 3, 4, 5], [1, 3, 7, 9, 2]]\n >>> token_indice = {(1, 3): 1337, (9, 2): 42, (4, 5): 2017}\n >>> add_ngram(sequences, token_indice, ngram_range=2)\n [[1, 3, 4, 5, 1337, 2017],...
Please provide a description of the function:def evaluate_accuracy(data_iterator, net, ctx, loss_fun, num_classes): acc = mx.metric.Accuracy() loss_avg = 0. for i, ((data, length), label) in enumerate(data_iterator): data = data.as_in_context(ctx) # .reshape((-1,784)) length = length.a...
[ "\n This function is used for evaluating accuracy of\n a given data iterator. (Either Train/Test data)\n It takes in the loss function used too!\n " ]
Please provide a description of the function:def read_input_data(filename): logging.info('Opening file %s for reading input', filename) input_file = open(filename, 'r') data = [] labels = [] for line in input_file: tokens = line.split(',', 1) labels.append(tokens[0].strip()) ...
[ "Helper function to get training data" ]
Please provide a description of the function:def parse_args(): parser = argparse.ArgumentParser( description='Text Classification with FastText', formatter_class=argparse.ArgumentDefaultsHelpFormatter) # Computation options group = parser.add_argument_group('Computation arguments') ...
[ "Parse command line arguments." ]
Please provide a description of the function:def get_label_mapping(train_labels): sorted_labels = np.sort(np.unique(train_labels)) label_mapping = {} for i, label in enumerate(sorted_labels): label_mapping[label] = i logging.info('Label mapping:%s', format(label_mapping)) return label_m...
[ "\n Create the mapping from label to numeric label\n " ]
Please provide a description of the function:def convert_to_sequences(dataset, vocab): start = time.time() dataset_vocab = map(lambda x: (x, vocab), dataset) with mp.Pool() as pool: # Each sample is processed in an asynchronous manner. output = pool.map(get_sequence, dataset_vocab) ...
[ "This function takes a dataset and converts\n it into sequences via multiprocessing\n " ]
Please provide a description of the function:def preprocess_dataset(dataset, labels): start = time.time() with mp.Pool() as pool: # Each sample is processed in an asynchronous manner. dataset = gluon.data.SimpleDataset(list(zip(dataset, labels))) lengths = gluon.data.SimpleDataset(p...
[ " Preprocess and prepare a dataset" ]
Please provide a description of the function:def get_dataloader(train_dataset, train_data_lengths, test_dataset, batch_size): bucket_num, bucket_ratio = 20, 0.2 batchify_fn = gluonnlp.data.batchify.Tuple( gluonnlp.data.batchify.Pad(axis=0, ret_length=True), gluonnlp.data....
[ " Construct the DataLoader. Pad data, stack label and lengths" ]