partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
train
get_model
Returns a pre-defined model by name. Parameters ---------- name : str Name of the model. dataset_name : str or None, default 'wikitext-2'. If None, then vocab is required, for specifying embedding weight size, and is directly returned. vocab : gluonnlp.Vocab or None, default...
scripts/bert/staticbert/static_bert.py
def get_model(name, dataset_name='wikitext-2', **kwargs): """Returns a pre-defined model by name. Parameters ---------- name : str Name of the model. dataset_name : str or None, default 'wikitext-2'. If None, then vocab is required, for specifying embedding weight size, and is direc...
def get_model(name, dataset_name='wikitext-2', **kwargs): """Returns a pre-defined model by name. Parameters ---------- name : str Name of the model. dataset_name : str or None, default 'wikitext-2'. If None, then vocab is required, for specifying embedding weight size, and is direc...
[ "Returns", "a", "pre", "-", "defined", "model", "by", "name", "." ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/staticbert/static_bert.py#L572-L605
[ "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", ".", "low...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
bert_12_768_12
Static BERT BASE model. The number of layers (L) is 12, number of units (H) is 768, and the number of self-attention heads (A) is 12. Parameters ---------- dataset_name : str or None, default None Options include 'book_corpus_wiki_en_cased', 'book_corpus_wiki_en_uncased', 'wiki_cn_...
scripts/bert/staticbert/static_bert.py
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, **kwargs): """Static BERT BASE model. ...
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, **kwargs): """Static BERT BASE model. ...
[ "Static", "BERT", "BASE", "model", "." ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/staticbert/static_bert.py#L608-L652
[ "def", "bert_12_768_12", "(", "dataset_name", "=", "None", ",", "vocab", "=", "None", ",", "pretrained", "=", "True", ",", "ctx", "=", "mx", ".", "cpu", "(", ")", ",", "root", "=", "os", ".", "path", ".", "join", "(", "get_home_dir", "(", ")", ",",...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
StaticBERTModel.hybrid_forward
Generate the representation given the inputs. This is used in training or fine-tuning a static (hybridized) BERT model.
scripts/bert/staticbert/static_bert.py
def hybrid_forward(self, F, inputs, token_types, valid_length=None, masked_positions=None): # pylint: disable=arguments-differ # pylint: disable=unused-argument """Generate the representation given the inputs. This is used in training or fine-tuning a static (hybridized) BERT model. ...
def hybrid_forward(self, F, inputs, token_types, valid_length=None, masked_positions=None): # pylint: disable=arguments-differ # pylint: disable=unused-argument """Generate the representation given the inputs. This is used in training or fine-tuning a static (hybridized) BERT model. ...
[ "Generate", "the", "representation", "given", "the", "inputs", "." ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/staticbert/static_bert.py#L481-L512
[ "def", "hybrid_forward", "(", "self", ",", "F", ",", "inputs", ",", "token_types", ",", "valid_length", "=", "None", ",", "masked_positions", "=", "None", ")", ":", "# pylint: disable=arguments-differ", "# pylint: disable=unused-argument", "outputs", "=", "[", "]", ...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
CacheCell.load_parameters
Load parameters from file. filename : str Path to parameter file. ctx : Context or list of Context, default cpu() Context(s) initialize loaded parameters on.
src/gluonnlp/model/train/cache.py
def load_parameters(self, filename, ctx=mx.cpu()): # pylint: disable=arguments-differ """Load parameters from file. filename : str Path to parameter file. ctx : Context or list of Context, default cpu() Context(s) initialize loaded parameters on. """ self...
def load_parameters(self, filename, ctx=mx.cpu()): # pylint: disable=arguments-differ """Load parameters from file. filename : str Path to parameter file. ctx : Context or list of Context, default cpu() Context(s) initialize loaded parameters on. """ self...
[ "Load", "parameters", "from", "file", "." ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/train/cache.py#L84-L92
[ "def", "load_parameters", "(", "self", ",", "filename", ",", "ctx", "=", "mx", ".", "cpu", "(", ")", ")", ":", "# pylint: disable=arguments-differ", "self", ".", "lm_model", ".", "load_parameters", "(", "filename", ",", "ctx", "=", "ctx", ")" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
CacheCell.forward
Defines the forward computation for cache cell. Arguments can be either :py:class:`NDArray` or :py:class:`Symbol`. Parameters ---------- inputs: NDArray The input data target: NDArray The label next_word_history: NDArray The next word ...
src/gluonnlp/model/train/cache.py
def forward(self, inputs, target, next_word_history, cache_history, begin_state=None): # pylint: disable=arguments-differ """Defines the forward computation for cache cell. Arguments can be either :py:class:`NDArray` or :py:class:`Symbol`. Parameters ---------- inputs: NDArray ...
def forward(self, inputs, target, next_word_history, cache_history, begin_state=None): # pylint: disable=arguments-differ """Defines the forward computation for cache cell. Arguments can be either :py:class:`NDArray` or :py:class:`Symbol`. Parameters ---------- inputs: NDArray ...
[ "Defines", "the", "forward", "computation", "for", "cache", "cell", ".", "Arguments", "can", "be", "either", ":", "py", ":", "class", ":", "NDArray", "or", ":", "py", ":", "class", ":", "Symbol", "." ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/train/cache.py#L100-L161
[ "def", "forward", "(", "self", ",", "inputs", ",", "target", ",", "next_word_history", ",", "cache_history", ",", "begin_state", "=", "None", ")", ":", "# pylint: disable=arguments-differ", "output", ",", "hidden", ",", "encoder_hs", ",", "_", "=", "super", "(...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
Parallel.put
Assign input `x` to an available worker and invoke `parallizable.forward_backward` with x.
src/gluonnlp/utils/parallel.py
def put(self, x): """Assign input `x` to an available worker and invoke `parallizable.forward_backward` with 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) ...
def put(self, x): """Assign input `x` to an available worker and invoke `parallizable.forward_backward` with 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) ...
[ "Assign", "input", "x", "to", "an", "available", "worker", "and", "invoke", "parallizable", ".", "forward_backward", "with", "x", "." ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/utils/parallel.py#L130-L138
[ "def", "put", "(", "self", ",", "x", ")", ":", "if", "self", ".", "_num_serial", ">", "0", "or", "len", "(", "self", ".", "_threads", ")", "==", "0", ":", "self", ".", "_num_serial", "-=", "1", "out", "=", "self", ".", "_parallizable", ".", "forw...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
BERTVocab.from_json
Deserialize BERTVocab object from json string. Parameters ---------- json_str : str Serialized json string of a BERTVocab object. Returns ------- BERTVocab
src/gluonnlp/vocab/bert.py
def from_json(cls, json_str): """Deserialize BERTVocab object from json string. Parameters ---------- json_str : str Serialized json string of a BERTVocab object. Returns ------- BERTVocab """ vocab_dict = json.loads(json_str) ...
def from_json(cls, json_str): """Deserialize BERTVocab object from json string. Parameters ---------- json_str : str Serialized json string of a BERTVocab object. Returns ------- BERTVocab """ vocab_dict = json.loads(json_str) ...
[ "Deserialize", "BERTVocab", "object", "from", "json", "string", "." ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/vocab/bert.py#L174-L203
[ "def", "from_json", "(", "cls", ",", "json_str", ")", ":", "vocab_dict", "=", "json", ".", "loads", "(", "json_str", ")", "unknown_token", "=", "vocab_dict", ".", "get", "(", "'unknown_token'", ")", "bert_vocab", "=", "cls", "(", "unknown_token", "=", "unk...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
StandardRNN.forward
Defines the forward computation. Arguments can be either :py:class:`NDArray` or :py:class:`Symbol`. Parameters ----------- inputs : NDArray input tensor with shape `(sequence_length, batch_size)` when `layout` is "TNC". begin_state : list init...
src/gluonnlp/model/train/language_model.py
def forward(self, inputs, begin_state=None): # pylint: disable=arguments-differ """Defines the forward computation. Arguments can be either :py:class:`NDArray` or :py:class:`Symbol`. Parameters ----------- inputs : NDArray input tensor with shape `(sequence_length, b...
def forward(self, inputs, begin_state=None): # pylint: disable=arguments-differ """Defines the forward computation. Arguments can be either :py:class:`NDArray` or :py:class:`Symbol`. Parameters ----------- inputs : NDArray input tensor with shape `(sequence_length, b...
[ "Defines", "the", "forward", "computation", ".", "Arguments", "can", "be", "either", ":", "py", ":", "class", ":", "NDArray", "or", ":", "py", ":", "class", ":", "Symbol", "." ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/train/language_model.py#L238-L276
[ "def", "forward", "(", "self", ",", "inputs", ",", "begin_state", "=", "None", ")", ":", "# pylint: disable=arguments-differ", "encoded", "=", "self", ".", "embedding", "(", "inputs", ")", "if", "not", "begin_state", ":", "begin_state", "=", "self", ".", "be...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
BigRNN.forward
Defines the forward computation. Parameters ----------- inputs : NDArray input tensor with shape `(sequence_length, batch_size)` when `layout` is "TNC". begin_state : list initial recurrent state tensor with length equals to num_layers*2. ...
src/gluonnlp/model/train/language_model.py
def forward(self, inputs, label, begin_state, sampled_values): # pylint: disable=arguments-differ """Defines the forward computation. Parameters ----------- inputs : NDArray input tensor with shape `(sequence_length, batch_size)` when `layout` is "TNC". b...
def forward(self, inputs, label, begin_state, sampled_values): # pylint: disable=arguments-differ """Defines the forward computation. Parameters ----------- inputs : NDArray input tensor with shape `(sequence_length, batch_size)` when `layout` is "TNC". b...
[ "Defines", "the", "forward", "computation", "." ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/train/language_model.py#L389-L427
[ "def", "forward", "(", "self", ",", "inputs", ",", "label", ",", "begin_state", ",", "sampled_values", ")", ":", "# pylint: disable=arguments-differ", "encoded", "=", "self", ".", "embedding", "(", "inputs", ")", "length", "=", "inputs", ".", "shape", "[", "...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
SG.hybrid_forward
SkipGram forward pass. Parameters ---------- center : mxnet.nd.NDArray or mxnet.sym.Symbol Sparse CSR array of word / subword indices of shape (batch_size, len(token_to_idx) + num_subwords). Embedding for center words are computed via F.sparse.dot between the...
scripts/word_embeddings/model.py
def hybrid_forward(self, F, center, context, center_words): """SkipGram forward pass. Parameters ---------- center : mxnet.nd.NDArray or mxnet.sym.Symbol Sparse CSR array of word / subword indices of shape (batch_size, len(token_to_idx) + num_subwords). Embedding...
def hybrid_forward(self, F, center, context, center_words): """SkipGram forward pass. Parameters ---------- center : mxnet.nd.NDArray or mxnet.sym.Symbol Sparse CSR array of word / subword indices of shape (batch_size, len(token_to_idx) + num_subwords). Embedding...
[ "SkipGram", "forward", "pass", "." ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/word_embeddings/model.py#L101-L149
[ "def", "hybrid_forward", "(", "self", ",", "F", ",", "center", ",", "context", ",", "center_words", ")", ":", "# negatives sampling", "negatives", "=", "[", "]", "mask", "=", "[", "]", "for", "_", "in", "range", "(", "self", ".", "_kwargs", "[", "'num_...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
evaluate
Evaluate network on the specified dataset
scripts/sentiment_analysis/finetune_lm.py
def evaluate(dataloader): """Evaluate network on the specified dataset""" 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(dat...
def evaluate(dataloader): """Evaluate network on the specified dataset""" 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(dat...
[ "Evaluate", "network", "on", "the", "specified", "dataset" ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/sentiment_analysis/finetune_lm.py#L237-L260
[ "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", ",", "(", ...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
train
Training process
scripts/sentiment_analysis/finetune_lm.py
def train(): """Training process""" 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 = 0 epoch_wc = 0...
def train(): """Training process""" 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 = 0 epoch_wc = 0...
[ "Training", "process" ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/sentiment_analysis/finetune_lm.py#L263-L340
[ "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",...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
AggregationLayer.hybrid_forward
Forward logic
scripts/sentiment_analysis/finetune_lm.py
def hybrid_forward(self, F, data, valid_length): # pylint: disable=arguments-differ """Forward logic""" # Data will have shape (T, N, C) if self._use_mean_pool: masked_encoded = F.SequenceMask(data, sequence_length=valid_length, ...
def hybrid_forward(self, F, data, valid_length): # pylint: disable=arguments-differ """Forward logic""" # Data will have shape (T, N, C) if self._use_mean_pool: masked_encoded = F.SequenceMask(data, sequence_length=valid_length, ...
[ "Forward", "logic" ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/sentiment_analysis/finetune_lm.py#L105-L118
[ "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", "(", "dat...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
LSTMPCellWithClip.hybrid_forward
r"""Hybrid forward computation for Long-Short Term Memory Projected network cell with cell clip and projection clip. Parameters ---------- inputs : input tensor with shape `(batch_size, input_size)`. states : a list of two initial recurrent state tensors, with shape ...
src/gluonnlp/model/lstmpcellwithclip.py
def hybrid_forward(self, F, inputs, states, i2h_weight, h2h_weight, h2r_weight, i2h_bias, h2h_bias): r"""Hybrid forward computation for Long-Short Term Memory Projected network cell with cell clip and projection clip. Parameters ---------- inputs : input t...
def hybrid_forward(self, F, inputs, states, i2h_weight, h2h_weight, h2r_weight, i2h_bias, h2h_bias): r"""Hybrid forward computation for Long-Short Term Memory Projected network cell with cell clip and projection clip. Parameters ---------- inputs : input t...
[ "r", "Hybrid", "forward", "computation", "for", "Long", "-", "Short", "Term", "Memory", "Projected", "network", "cell", "with", "cell", "clip", "and", "projection", "clip", "." ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/lstmpcellwithclip.py#L100-L139
[ "def", "hybrid_forward", "(", "self", ",", "F", ",", "inputs", ",", "states", ",", "i2h_weight", ",", "h2h_weight", ",", "h2r_weight", ",", "i2h_bias", ",", "h2h_bias", ")", ":", "prefix", "=", "'t%d_'", "%", "self", ".", "_counter", "i2h", "=", "F", "...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
clip_grad_global_norm
Rescales gradients of parameters so that the sum of their 2-norm is smaller than `max_norm`. If gradients exist for more than one context for a parameter, user needs to explicitly call ``trainer.allreduce_grads`` so that the gradients are summed first before calculating the 2-norm. .. note:: T...
src/gluonnlp/utils/parameter.py
def clip_grad_global_norm(parameters, max_norm, check_isfinite=True): """Rescales gradients of parameters so that the sum of their 2-norm is smaller than `max_norm`. If gradients exist for more than one context for a parameter, user needs to explicitly call ``trainer.allreduce_grads`` so that the gradients ...
def clip_grad_global_norm(parameters, max_norm, check_isfinite=True): """Rescales gradients of parameters so that the sum of their 2-norm is smaller than `max_norm`. If gradients exist for more than one context for a parameter, user needs to explicitly call ``trainer.allreduce_grads`` so that the gradients ...
[ "Rescales", "gradients", "of", "parameters", "so", "that", "the", "sum", "of", "their", "2", "-", "norm", "is", "smaller", "than", "max_norm", ".", "If", "gradients", "exist", "for", "more", "than", "one", "context", "for", "a", "parameter", "user", "needs...
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/utils/parameter.py#L28-L97
[ "def", "clip_grad_global_norm", "(", "parameters", ",", "max_norm", ",", "check_isfinite", "=", "True", ")", ":", "def", "_norm", "(", "array", ")", ":", "if", "array", ".", "stype", "==", "'default'", ":", "x", "=", "array", ".", "reshape", "(", "(", ...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
train
Training function.
scripts/bert/run_pretraining.py
def train(data_train, model, nsp_loss, mlm_loss, vocab_size, ctx, store): """Training function.""" mlm_metric = nlp.metric.MaskedAccuracy() nsp_metric = nlp.metric.MaskedAccuracy() mlm_metric.reset() nsp_metric.reset() lr = args.lr optim_params = {'learning_rate': lr, 'epsilon': 1e-6, 'wd':...
def train(data_train, model, nsp_loss, mlm_loss, vocab_size, ctx, store): """Training function.""" mlm_metric = nlp.metric.MaskedAccuracy() nsp_metric = nlp.metric.MaskedAccuracy() mlm_metric.reset() nsp_metric.reset() lr = args.lr optim_params = {'learning_rate': lr, 'epsilon': 1e-6, 'wd':...
[ "Training", "function", "." ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/run_pretraining.py#L92-L215
[ "def", "train", "(", "data_train", ",", "model", ",", "nsp_loss", ",", "mlm_loss", ",", "vocab_size", ",", "ctx", ",", "store", ")", ":", "mlm_metric", "=", "nlp", ".", "metric", ".", "MaskedAccuracy", "(", ")", "nsp_metric", "=", "nlp", ".", "metric", ...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
ParallelBERT.forward_backward
forward backward implementation
scripts/bert/run_pretraining.py
def forward_backward(self, x): """forward backward implementation""" 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, ...
def forward_backward(self, x): """forward backward implementation""" 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" ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/run_pretraining.py#L77-L90
[ "def", "forward_backward", "(", "self", ",", "x", ")", ":", "with", "mx", ".", "autograd", ".", "record", "(", ")", ":", "(", "ls", ",", "next_sentence_label", ",", "classified", ",", "masked_id", ",", "decoded", ",", "masked_weight", ",", "ls1", ",", ...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
ParserVocabulary.log_info
Print statistical information via the provided logger Parameters ---------- logger : logging.Logger logger created using logging.getLogger()
scripts/parsing/common/data.py
def log_info(self, logger): """Print statistical information via the provided logger Parameters ---------- logger : logging.Logger logger created using logging.getLogger() """ logger.info('#words in training set: %d' % self._words_in_train_data) logge...
def log_info(self, logger): """Print statistical information via the provided logger Parameters ---------- logger : logging.Logger logger created using logging.getLogger() """ logger.info('#words in training set: %d' % self._words_in_train_data) logge...
[ "Print", "statistical", "information", "via", "the", "provided", "logger" ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/common/data.py#L162-L171
[ "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", ".", ...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
ParserVocabulary._add_pret_words
Read pre-trained embedding file for extending vocabulary Parameters ---------- pret_embeddings : tuple (embedding_name, source), used for gluonnlp.embedding.create(embedding_name, source)
scripts/parsing/common/data.py
def _add_pret_words(self, pret_embeddings): """Read pre-trained embedding file for extending vocabulary Parameters ---------- pret_embeddings : tuple (embedding_name, source), used for gluonnlp.embedding.create(embedding_name, source) """ words_in_train_data ...
def _add_pret_words(self, pret_embeddings): """Read pre-trained embedding file for extending vocabulary Parameters ---------- pret_embeddings : tuple (embedding_name, source), used for gluonnlp.embedding.create(embedding_name, source) """ words_in_train_data ...
[ "Read", "pre", "-", "trained", "embedding", "file", "for", "extending", "vocabulary" ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/common/data.py#L173-L186
[ "def", "_add_pret_words", "(", "self", ",", "pret_embeddings", ")", ":", "words_in_train_data", "=", "set", "(", "self", ".", "_id2word", ")", "pret_embeddings", "=", "gluonnlp", ".", "embedding", ".", "create", "(", "pret_embeddings", "[", "0", "]", ",", "s...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
ParserVocabulary.get_pret_embs
Read pre-trained embedding file Parameters ---------- word_dims : int or None vector size. Use `None` for auto-infer Returns ------- numpy.ndarray T x C numpy NDArray
scripts/parsing/common/data.py
def get_pret_embs(self, word_dims=None): """Read pre-trained embedding file Parameters ---------- word_dims : int or None vector size. Use `None` for auto-infer Returns ------- numpy.ndarray T x C numpy NDArray """ assert (...
def get_pret_embs(self, word_dims=None): """Read pre-trained embedding file Parameters ---------- word_dims : int or None vector size. Use `None` for auto-infer Returns ------- numpy.ndarray T x C numpy NDArray """ assert (...
[ "Read", "pre", "-", "trained", "embedding", "file" ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/common/data.py#L198-L221
[ "def", "get_pret_embs", "(", "self", ",", "word_dims", "=", "None", ")", ":", "assert", "(", "self", ".", "_pret_embeddings", "is", "not", "None", ")", ",", "\"No pretrained file provided.\"", "pret_embeddings", "=", "gluonnlp", ".", "embedding", ".", "create", ...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
ParserVocabulary.get_word_embs
Get randomly initialized embeddings when pre-trained embeddings are used, otherwise zero vectors Parameters ---------- word_dims : int word vector size Returns ------- numpy.ndarray T x C numpy NDArray
scripts/parsing/common/data.py
def get_word_embs(self, word_dims): """Get randomly initialized embeddings when pre-trained embeddings are used, otherwise zero vectors Parameters ---------- word_dims : int word vector size Returns ------- numpy.ndarray T x C numpy NDArra...
def get_word_embs(self, word_dims): """Get randomly initialized embeddings when pre-trained embeddings are used, otherwise zero vectors Parameters ---------- word_dims : int word vector size Returns ------- numpy.ndarray T x C numpy NDArra...
[ "Get", "randomly", "initialized", "embeddings", "when", "pre", "-", "trained", "embeddings", "are", "used", "otherwise", "zero", "vectors" ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/common/data.py#L223-L237
[ "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", "(", ...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
ParserVocabulary.get_tag_embs
Randomly initialize embeddings for tag Parameters ---------- tag_dims : int tag vector size Returns ------- numpy.ndarray random embeddings
scripts/parsing/common/data.py
def get_tag_embs(self, tag_dims): """Randomly initialize embeddings for tag Parameters ---------- tag_dims : int tag vector size Returns ------- numpy.ndarray random embeddings """ return np.random.randn(self.tag_size, tag...
def get_tag_embs(self, tag_dims): """Randomly initialize embeddings for tag Parameters ---------- tag_dims : int tag vector size Returns ------- numpy.ndarray random embeddings """ return np.random.randn(self.tag_size, tag...
[ "Randomly", "initialize", "embeddings", "for", "tag" ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/common/data.py#L239-L252
[ "def", "get_tag_embs", "(", "self", ",", "tag_dims", ")", ":", "return", "np", ".", "random", ".", "randn", "(", "self", ".", "tag_size", ",", "tag_dims", ")", ".", "astype", "(", "np", ".", "float32", ")" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
ParserVocabulary.word2id
Map word(s) to its id(s) Parameters ---------- xs : str or list word or a list of words Returns ------- int or list id or a list of ids
scripts/parsing/common/data.py
def word2id(self, xs): """Map word(s) to its id(s) Parameters ---------- xs : str or list word or a list of words Returns ------- int or list id or a list of ids """ if isinstance(xs, list): return [self._word2...
def word2id(self, xs): """Map word(s) to its id(s) Parameters ---------- xs : str or list word or a list of words Returns ------- int or list id or a list of ids """ if isinstance(xs, list): return [self._word2...
[ "Map", "word", "(", "s", ")", "to", "its", "id", "(", "s", ")" ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/common/data.py#L254-L269
[ "def", "word2id", "(", "self", ",", "xs", ")", ":", "if", "isinstance", "(", "xs", ",", "list", ")", ":", "return", "[", "self", ".", "_word2id", ".", "get", "(", "x", ",", "self", ".", "UNK", ")", "for", "x", "in", "xs", "]", "return", "self",...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
ParserVocabulary.id2word
Map id(s) to word(s) Parameters ---------- xs : int id or a list of ids Returns ------- str or list word or a list of words
scripts/parsing/common/data.py
def id2word(self, xs): """Map id(s) to word(s) Parameters ---------- xs : int id or a list of ids Returns ------- str or list word or a list of words """ if isinstance(xs, list): return [self._id2word[x] for x ...
def id2word(self, xs): """Map id(s) to word(s) Parameters ---------- xs : int id or a list of ids Returns ------- str or list word or a list of words """ if isinstance(xs, list): return [self._id2word[x] for x ...
[ "Map", "id", "(", "s", ")", "to", "word", "(", "s", ")" ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/common/data.py#L271-L286
[ "def", "id2word", "(", "self", ",", "xs", ")", ":", "if", "isinstance", "(", "xs", ",", "list", ")", ":", "return", "[", "self", ".", "_id2word", "[", "x", "]", "for", "x", "in", "xs", "]", "return", "self", ".", "_id2word", "[", "xs", "]" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
ParserVocabulary.rel2id
Map relation(s) to id(s) Parameters ---------- xs : str or list relation Returns ------- int or list id(s) of relation
scripts/parsing/common/data.py
def rel2id(self, xs): """Map relation(s) to id(s) Parameters ---------- xs : str or list relation Returns ------- int or list id(s) of relation """ if isinstance(xs, list): return [self._rel2id[x] for x in xs] ...
def rel2id(self, xs): """Map relation(s) to id(s) Parameters ---------- xs : str or list relation Returns ------- int or list id(s) of relation """ if isinstance(xs, list): return [self._rel2id[x] for x in xs] ...
[ "Map", "relation", "(", "s", ")", "to", "id", "(", "s", ")" ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/common/data.py#L288-L303
[ "def", "rel2id", "(", "self", ",", "xs", ")", ":", "if", "isinstance", "(", "xs", ",", "list", ")", ":", "return", "[", "self", ".", "_rel2id", "[", "x", "]", "for", "x", "in", "xs", "]", "return", "self", ".", "_rel2id", "[", "xs", "]" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
ParserVocabulary.id2rel
Map id(s) to relation(s) Parameters ---------- xs : int id or a list of ids Returns ------- str or list relation or a list of relations
scripts/parsing/common/data.py
def id2rel(self, xs): """Map id(s) to relation(s) Parameters ---------- xs : int id or a list of ids Returns ------- str or list relation or a list of relations """ if isinstance(xs, list): return [self._id2rel...
def id2rel(self, xs): """Map id(s) to relation(s) Parameters ---------- xs : int id or a list of ids Returns ------- str or list relation or a list of relations """ if isinstance(xs, list): return [self._id2rel...
[ "Map", "id", "(", "s", ")", "to", "relation", "(", "s", ")" ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/common/data.py#L305-L320
[ "def", "id2rel", "(", "self", ",", "xs", ")", ":", "if", "isinstance", "(", "xs", ",", "list", ")", ":", "return", "[", "self", ".", "_id2rel", "[", "x", "]", "for", "x", "in", "xs", "]", "return", "self", ".", "_id2rel", "[", "xs", "]" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
ParserVocabulary.tag2id
Map tag(s) to id(s) Parameters ---------- xs : str or list tag or tags Returns ------- int or list id(s) of tag(s)
scripts/parsing/common/data.py
def tag2id(self, xs): """Map tag(s) to id(s) Parameters ---------- xs : str or list tag or tags Returns ------- int or list id(s) of tag(s) """ if isinstance(xs, list): return [self._tag2id.get(x, self.UNK) for...
def tag2id(self, xs): """Map tag(s) to id(s) Parameters ---------- xs : str or list tag or tags Returns ------- int or list id(s) of tag(s) """ if isinstance(xs, list): return [self._tag2id.get(x, self.UNK) for...
[ "Map", "tag", "(", "s", ")", "to", "id", "(", "s", ")" ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/common/data.py#L322-L337
[ "def", "tag2id", "(", "self", ",", "xs", ")", ":", "if", "isinstance", "(", "xs", ",", "list", ")", ":", "return", "[", "self", ".", "_tag2id", ".", "get", "(", "x", ",", "self", ".", "UNK", ")", "for", "x", "in", "xs", "]", "return", "self", ...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
DataLoader.idx_sequence
Indices of sentences when enumerating data set from batches. Useful when retrieving the correct order of sentences Returns ------- list List of ids ranging from 0 to #sent -1
scripts/parsing/common/data.py
def idx_sequence(self): """Indices of sentences when enumerating data set from batches. Useful when retrieving the correct order of sentences Returns ------- list List of ids ranging from 0 to #sent -1 """ return [x[1] for x in sorted(zip(self._record...
def idx_sequence(self): """Indices of sentences when enumerating data set from batches. Useful when retrieving the correct order of sentences Returns ------- list List of ids ranging from 0 to #sent -1 """ return [x[1] for x in sorted(zip(self._record...
[ "Indices", "of", "sentences", "when", "enumerating", "data", "set", "from", "batches", ".", "Useful", "when", "retrieving", "the", "correct", "order", "of", "sentences" ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/common/data.py#L431-L440
[ "def", "idx_sequence", "(", "self", ")", ":", "return", "[", "x", "[", "1", "]", "for", "x", "in", "sorted", "(", "zip", "(", "self", ".", "_record", ",", "list", "(", "range", "(", "len", "(", "self", ".", "_record", ")", ")", ")", ")", ")", ...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
DataLoader.get_batches
Get batch iterator Parameters ---------- batch_size : int size of one batch shuffle : bool whether to shuffle batches. Don't set to True when evaluating on dev or test set. Returns ------- tuple word_inputs, tag_inputs, arc_tar...
scripts/parsing/common/data.py
def get_batches(self, batch_size, shuffle=True): """Get batch iterator Parameters ---------- batch_size : int size of one batch shuffle : bool whether to shuffle batches. Don't set to True when evaluating on dev or test set. Returns ------...
def get_batches(self, batch_size, shuffle=True): """Get batch iterator Parameters ---------- batch_size : int size of one batch shuffle : bool whether to shuffle batches. Don't set to True when evaluating on dev or test set. Returns ------...
[ "Get", "batch", "iterator" ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/common/data.py#L442-L473
[ "def", "get_batches", "(", "self", ",", "batch_size", ",", "shuffle", "=", "True", ")", ":", "batches", "=", "[", "]", "for", "bkt_idx", ",", "bucket", "in", "enumerate", "(", "self", ".", "_buckets", ")", ":", "bucket_size", "=", "bucket", ".", "shape...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
create_ngram_set
Extract a set of n-grams from a list of integers. >>> create_ngram_set([1, 4, 9, 4, 1, 4], ngram_value=2) {(4, 9), (4, 1), (1, 4), (9, 4)} >>> create_ngram_set([1, 4, 9, 4, 1, 4], ngram_value=3) [(1, 4, 9), (4, 9, 4), (9, 4, 1), (4, 1, 4)]
scripts/text_classification/fasttext_word_ngram.py
def create_ngram_set(input_list, ngram_value=2): """ Extract a set of n-grams from a list of integers. >>> create_ngram_set([1, 4, 9, 4, 1, 4], ngram_value=2) {(4, 9), (4, 1), (1, 4), (9, 4)} >>> create_ngram_set([1, 4, 9, 4, 1, 4], ngram_value=3) [(1, 4, 9), (4, 9, 4), (9, 4, 1), (4, 1, 4)] ...
def create_ngram_set(input_list, ngram_value=2): """ Extract a set of n-grams from a list of integers. >>> create_ngram_set([1, 4, 9, 4, 1, 4], ngram_value=2) {(4, 9), (4, 1), (1, 4), (9, 4)} >>> create_ngram_set([1, 4, 9, 4, 1, 4], ngram_value=3) [(1, 4, 9), (4, 9, 4), (9, 4, 1), (4, 1, 4)] ...
[ "Extract", "a", "set", "of", "n", "-", "grams", "from", "a", "list", "of", "integers", ".", ">>>", "create_ngram_set", "(", "[", "1", "4", "9", "4", "1", "4", "]", "ngram_value", "=", "2", ")", "{", "(", "4", "9", ")", "(", "4", "1", ")", "("...
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/text_classification/fasttext_word_ngram.py#L96-L104
[ "def", "create_ngram_set", "(", "input_list", ",", "ngram_value", "=", "2", ")", ":", "return", "set", "(", "zip", "(", "*", "[", "input_list", "[", "i", ":", "]", "for", "i", "in", "range", "(", "ngram_value", ")", "]", ")", ")" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
add_ngram
Augment the input list of list (sequences) by appending n-grams values. Example: adding bi-gram >>> sequences = [[1, 3, 4, 5], [1, 3, 7, 9, 2]] >>> token_indice = {(1, 3): 1337, (9, 2): 42, (4, 5): 2017} >>> add_ngram(sequences, token_indice, ngram_range=2) [[1, 3, 4, 5, 1337, 2017], [1, 3, 7, 9, 2,...
scripts/text_classification/fasttext_word_ngram.py
def add_ngram(sequences, token_indice, ngram_range=2): """ Augment the input list of list (sequences) by appending n-grams values. Example: adding bi-gram >>> sequences = [[1, 3, 4, 5], [1, 3, 7, 9, 2]] >>> token_indice = {(1, 3): 1337, (9, 2): 42, (4, 5): 2017} >>> add_ngram(sequences, token_in...
def add_ngram(sequences, token_indice, ngram_range=2): """ Augment the input list of list (sequences) by appending n-grams values. Example: adding bi-gram >>> sequences = [[1, 3, 4, 5], [1, 3, 7, 9, 2]] >>> token_indice = {(1, 3): 1337, (9, 2): 42, (4, 5): 2017} >>> add_ngram(sequences, token_in...
[ "Augment", "the", "input", "list", "of", "list", "(", "sequences", ")", "by", "appending", "n", "-", "grams", "values", ".", "Example", ":", "adding", "bi", "-", "gram", ">>>", "sequences", "=", "[[", "1", "3", "4", "5", "]", "[", "1", "3", "7", ...
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/text_classification/fasttext_word_ngram.py#L107-L131
[ "def", "add_ngram", "(", "sequences", ",", "token_indice", ",", "ngram_range", "=", "2", ")", ":", "new_sequences", "=", "[", "]", "for", "input_list", "in", "sequences", ":", "new_list", "=", "input_list", "[", ":", "]", "for", "i", "in", "range", "(", ...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
evaluate_accuracy
This function is used for evaluating accuracy of a given data iterator. (Either Train/Test data) It takes in the loss function used too!
scripts/text_classification/fasttext_word_ngram.py
def evaluate_accuracy(data_iterator, net, ctx, loss_fun, num_classes): """ This function is used for evaluating accuracy of a given data iterator. (Either Train/Test data) It takes in the loss function used too! """ acc = mx.metric.Accuracy() loss_avg = 0. for i, ((data, length), label) ...
def evaluate_accuracy(data_iterator, net, ctx, loss_fun, num_classes): """ This function is used for evaluating accuracy of a given data iterator. (Either Train/Test data) It takes in the loss function used too! """ acc = mx.metric.Accuracy() loss_avg = 0. for i, ((data, length), label) ...
[ "This", "function", "is", "used", "for", "evaluating", "accuracy", "of", "a", "given", "data", "iterator", ".", "(", "Either", "Train", "/", "Test", "data", ")", "It", "takes", "in", "the", "loss", "function", "used", "too!" ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/text_classification/fasttext_word_ngram.py#L134-L156
[ "def", "evaluate_accuracy", "(", "data_iterator", ",", "net", ",", "ctx", ",", "loss_fun", ",", "num_classes", ")", ":", "acc", "=", "mx", ".", "metric", ".", "Accuracy", "(", ")", "loss_avg", "=", "0.", "for", "i", ",", "(", "(", "data", ",", "lengt...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
read_input_data
Helper function to get training data
scripts/text_classification/fasttext_word_ngram.py
def read_input_data(filename): """Helper function to get training data""" 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()) ...
def read_input_data(filename): """Helper function to get training data""" 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" ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/text_classification/fasttext_word_ngram.py#L159-L169
[ "def", "read_input_data", "(", "filename", ")", ":", "logging", ".", "info", "(", "'Opening file %s for reading input'", ",", "filename", ")", "input_file", "=", "open", "(", "filename", ",", "'r'", ")", "data", "=", "[", "]", "labels", "=", "[", "]", "for...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
parse_args
Parse command line arguments.
scripts/text_classification/fasttext_word_ngram.py
def parse_args(): """Parse command line arguments.""" parser = argparse.ArgumentParser( description='Text Classification with FastText', formatter_class=argparse.ArgumentDefaultsHelpFormatter) # Computation options group = parser.add_argument_group('Computation arguments') group.add...
def parse_args(): """Parse command line arguments.""" parser = argparse.ArgumentParser( description='Text Classification with FastText', formatter_class=argparse.ArgumentDefaultsHelpFormatter) # Computation options group = parser.add_argument_group('Computation arguments') group.add...
[ "Parse", "command", "line", "arguments", "." ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/text_classification/fasttext_word_ngram.py#L175-L214
[ "def", "parse_args", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'Text Classification with FastText'", ",", "formatter_class", "=", "argparse", ".", "ArgumentDefaultsHelpFormatter", ")", "# Computation options", "group", "=...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
get_label_mapping
Create the mapping from label to numeric label
scripts/text_classification/fasttext_word_ngram.py
def get_label_mapping(train_labels): """ Create the mapping from label to numeric label """ 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)) ...
def get_label_mapping(train_labels): """ Create the mapping from label to numeric label """ 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)) ...
[ "Create", "the", "mapping", "from", "label", "to", "numeric", "label" ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/text_classification/fasttext_word_ngram.py#L217-L226
[ "def", "get_label_mapping", "(", "train_labels", ")", ":", "sorted_labels", "=", "np", ".", "sort", "(", "np", ".", "unique", "(", "train_labels", ")", ")", "label_mapping", "=", "{", "}", "for", "i", ",", "label", "in", "enumerate", "(", "sorted_labels", ...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
convert_to_sequences
This function takes a dataset and converts it into sequences via multiprocessing
scripts/text_classification/fasttext_word_ngram.py
def convert_to_sequences(dataset, vocab): """This function takes a dataset and converts it into sequences via multiprocessing """ start = time.time() dataset_vocab = map(lambda x: (x, vocab), dataset) with mp.Pool() as pool: # Each sample is processed in an asynchronous manner. o...
def convert_to_sequences(dataset, vocab): """This function takes a dataset and converts it into sequences via multiprocessing """ start = time.time() dataset_vocab = map(lambda x: (x, vocab), dataset) with mp.Pool() as pool: # Each sample is processed in an asynchronous manner. o...
[ "This", "function", "takes", "a", "dataset", "and", "converts", "it", "into", "sequences", "via", "multiprocessing" ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/text_classification/fasttext_word_ngram.py#L256-L268
[ "def", "convert_to_sequences", "(", "dataset", ",", "vocab", ")", ":", "start", "=", "time", ".", "time", "(", ")", "dataset_vocab", "=", "map", "(", "lambda", "x", ":", "(", "x", ",", "vocab", ")", ",", "dataset", ")", "with", "mp", ".", "Pool", "...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
preprocess_dataset
Preprocess and prepare a dataset
scripts/text_classification/fasttext_word_ngram.py
def preprocess_dataset(dataset, labels): """ Preprocess and prepare a dataset""" 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(pool.ma...
def preprocess_dataset(dataset, labels): """ Preprocess and prepare a dataset""" 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(pool.ma...
[ "Preprocess", "and", "prepare", "a", "dataset" ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/text_classification/fasttext_word_ngram.py#L271-L281
[ "def", "preprocess_dataset", "(", "dataset", ",", "labels", ")", ":", "start", "=", "time", ".", "time", "(", ")", "with", "mp", ".", "Pool", "(", ")", "as", "pool", ":", "# Each sample is processed in an asynchronous manner.", "dataset", "=", "gluon", ".", ...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
get_dataloader
Construct the DataLoader. Pad data, stack label and lengths
scripts/text_classification/fasttext_word_ngram.py
def get_dataloader(train_dataset, train_data_lengths, test_dataset, batch_size): """ Construct the DataLoader. Pad data, stack label and lengths""" bucket_num, bucket_ratio = 20, 0.2 batchify_fn = gluonnlp.data.batchify.Tuple( gluonnlp.data.batchify.Pad(axis=0, ret_length=True), ...
def get_dataloader(train_dataset, train_data_lengths, test_dataset, batch_size): """ Construct the DataLoader. Pad data, stack label and lengths""" bucket_num, bucket_ratio = 20, 0.2 batchify_fn = gluonnlp.data.batchify.Tuple( gluonnlp.data.batchify.Pad(axis=0, ret_length=True), ...
[ "Construct", "the", "DataLoader", ".", "Pad", "data", "stack", "label", "and", "lengths" ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/text_classification/fasttext_word_ngram.py#L284-L306
[ "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", "(...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
train
Training function that orchestrates the Classification!
scripts/text_classification/fasttext_word_ngram.py
def train(args): """Training function that orchestrates the Classification! """ train_file = args.input test_file = args.validation ngram_range = args.ngrams logging.info('Ngrams range for the training run : %s', ngram_range) logging.info('Loading Training data') train_labels, train_data = r...
def train(args): """Training function that orchestrates the Classification! """ train_file = args.input test_file = args.validation ngram_range = args.ngrams logging.info('Ngrams range for the training run : %s', ngram_range) logging.info('Loading Training data') train_labels, train_data = r...
[ "Training", "function", "that", "orchestrates", "the", "Classification!" ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/text_classification/fasttext_word_ngram.py#L311-L416
[ "def", "train", "(", "args", ")", ":", "train_file", "=", "args", ".", "input", "test_file", "=", "args", ".", "validation", "ngram_range", "=", "args", ".", "ngrams", "logging", ".", "info", "(", "'Ngrams range for the training run : %s'", ",", "ngram_range", ...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
StaticBertForQA.hybrid_forward
Generate the unnormalized score for the given the input sequences. Parameters ---------- inputs : NDArray, shape (batch_size, seq_length) Input words for the sequences. token_types : NDArray, shape (batch_size, seq_length) Token types for the sequences, used to i...
scripts/bert/staticbert/static_bert_qa_model.py
def hybrid_forward(self, F, inputs, token_types, valid_length=None): # pylint: disable=arguments-differ # pylint: disable=unused-argument """Generate the unnormalized score for the given the input sequences. Parameters ---------- inputs : NDArray, shape (batch_size, seq_...
def hybrid_forward(self, F, inputs, token_types, valid_length=None): # pylint: disable=arguments-differ # pylint: disable=unused-argument """Generate the unnormalized score for the given the input sequences. Parameters ---------- inputs : NDArray, shape (batch_size, seq_...
[ "Generate", "the", "unnormalized", "score", "for", "the", "given", "the", "input", "sequences", "." ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/staticbert/static_bert_qa_model.py#L50-L72
[ "def", "hybrid_forward", "(", "self", ",", "F", ",", "inputs", ",", "token_types", ",", "valid_length", "=", "None", ")", ":", "# pylint: disable=arguments-differ", "# pylint: disable=unused-argument", "bert_output", "=", "self", ".", "bert", "(", "inputs", ",", "...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
BertForQALoss.hybrid_forward
Parameters ---------- pred : NDArray, shape (batch_size, seq_length, 2) BERTSquad forward output. label : list, length is 2, each shape is (batch_size,1) label[0] is the starting position of the answer, label[1] is the ending position of the answer. R...
scripts/bert/staticbert/static_bert_qa_model.py
def hybrid_forward(self, F, pred, label): # pylint: disable=arguments-differ """ Parameters ---------- pred : NDArray, shape (batch_size, seq_length, 2) BERTSquad forward output. label : list, length is 2, each shape is (batch_size,1) label[0] is the star...
def hybrid_forward(self, F, pred, label): # pylint: disable=arguments-differ """ Parameters ---------- pred : NDArray, shape (batch_size, seq_length, 2) BERTSquad forward output. label : list, length is 2, each shape is (batch_size,1) label[0] is the star...
[ "Parameters", "----------", "pred", ":", "NDArray", "shape", "(", "batch_size", "seq_length", "2", ")", "BERTSquad", "forward", "output", ".", "label", ":", "list", "length", "is", "2", "each", "shape", "is", "(", "batch_size", "1", ")", "label", "[", "0",...
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/staticbert/static_bert_qa_model.py#L85-L106
[ "def", "hybrid_forward", "(", "self", ",", "F", ",", "pred", ",", "label", ")", ":", "# pylint: disable=arguments-differ", "pred", "=", "F", ".", "split", "(", "pred", ",", "axis", "=", "2", ",", "num_outputs", "=", "2", ")", "start_pred", "=", "pred", ...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
NMTModel.encode
Encode the input sequence. Parameters ---------- inputs : NDArray states : list of NDArrays or None, default None valid_length : NDArray or None, default None Returns ------- outputs : list Outputs of the encoder.
src/gluonnlp/model/translation.py
def encode(self, inputs, states=None, valid_length=None): """Encode the input sequence. Parameters ---------- inputs : NDArray states : list of NDArrays or None, default None valid_length : NDArray or None, default None Returns ------- outputs : ...
def encode(self, inputs, states=None, valid_length=None): """Encode the input sequence. Parameters ---------- inputs : NDArray states : list of NDArrays or None, default None valid_length : NDArray or None, default None Returns ------- outputs : ...
[ "Encode", "the", "input", "sequence", "." ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/translation.py#L129-L143
[ "def", "encode", "(", "self", ",", "inputs", ",", "states", "=", "None", ",", "valid_length", "=", "None", ")", ":", "return", "self", ".", "encoder", "(", "self", ".", "src_embed", "(", "inputs", ")", ",", "states", ",", "valid_length", ")" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
NMTModel.decode_seq
Decode given the input sequence. Parameters ---------- inputs : NDArray states : list of NDArrays valid_length : NDArray or None, default None Returns ------- output : NDArray The output of the decoder. Shape is (batch_size, length, tgt_word_...
src/gluonnlp/model/translation.py
def decode_seq(self, inputs, states, valid_length=None): """Decode given the input sequence. Parameters ---------- inputs : NDArray states : list of NDArrays valid_length : NDArray or None, default None Returns ------- output : NDArray ...
def decode_seq(self, inputs, states, valid_length=None): """Decode given the input sequence. Parameters ---------- inputs : NDArray states : list of NDArrays valid_length : NDArray or None, default None Returns ------- output : NDArray ...
[ "Decode", "given", "the", "input", "sequence", "." ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/translation.py#L145-L168
[ "def", "decode_seq", "(", "self", ",", "inputs", ",", "states", ",", "valid_length", "=", "None", ")", ":", "outputs", ",", "states", ",", "additional_outputs", "=", "self", ".", "decoder", ".", "decode_seq", "(", "inputs", "=", "self", ".", "tgt_embed", ...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
NMTModel.decode_step
One step decoding of the translation model. Parameters ---------- step_input : NDArray Shape (batch_size,) states : list of NDArrays Returns ------- step_output : NDArray Shape (batch_size, C_out) states : list step_additi...
src/gluonnlp/model/translation.py
def decode_step(self, step_input, states): """One step decoding of the translation model. Parameters ---------- step_input : NDArray Shape (batch_size,) states : list of NDArrays Returns ------- step_output : NDArray Shape (batch_...
def decode_step(self, step_input, states): """One step decoding of the translation model. Parameters ---------- step_input : NDArray Shape (batch_size,) states : list of NDArrays Returns ------- step_output : NDArray Shape (batch_...
[ "One", "step", "decoding", "of", "the", "translation", "model", "." ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/translation.py#L170-L190
[ "def", "decode_step", "(", "self", ",", "step_input", ",", "states", ")", ":", "step_output", ",", "states", ",", "step_additional_outputs", "=", "self", ".", "decoder", "(", "self", ".", "tgt_embed", "(", "step_input", ")", ",", "states", ")", "step_output"...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
NMTModel.forward
Generate the prediction given the src_seq and tgt_seq. This is used in training an NMT model. Parameters ---------- src_seq : NDArray tgt_seq : NDArray src_valid_length : NDArray or None tgt_valid_length : NDArray or None Returns ------- ...
src/gluonnlp/model/translation.py
def forward(self, src_seq, tgt_seq, src_valid_length=None, tgt_valid_length=None): #pylint: disable=arguments-differ """Generate the prediction given the src_seq and tgt_seq. This is used in training an NMT model. Parameters ---------- src_seq : NDArray tgt_seq : NDArr...
def forward(self, src_seq, tgt_seq, src_valid_length=None, tgt_valid_length=None): #pylint: disable=arguments-differ """Generate the prediction given the src_seq and tgt_seq. This is used in training an NMT model. Parameters ---------- src_seq : NDArray tgt_seq : NDArr...
[ "Generate", "the", "prediction", "given", "the", "src_seq", "and", "tgt_seq", "." ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/translation.py#L213-L241
[ "def", "forward", "(", "self", ",", "src_seq", ",", "tgt_seq", ",", "src_valid_length", "=", "None", ",", "tgt_valid_length", "=", "None", ")", ":", "#pylint: disable=arguments-differ", "additional_outputs", "=", "[", "]", "encoder_outputs", ",", "encoder_additional...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
create_subword_function
Creates an instance of a subword function.
src/gluonnlp/vocab/subwords.py
def create_subword_function(subword_function_name, **kwargs): """Creates an instance of a subword function.""" create_ = registry.get_create_func(SubwordFunction, 'token embedding') return create_(subword_function_name, **kwargs)
def create_subword_function(subword_function_name, **kwargs): """Creates an instance of a subword function.""" create_ = registry.get_create_func(SubwordFunction, 'token embedding') return create_(subword_function_name, **kwargs)
[ "Creates", "an", "instance", "of", "a", "subword", "function", "." ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/vocab/subwords.py#L43-L47
[ "def", "create_subword_function", "(", "subword_function_name", ",", "*", "*", "kwargs", ")", ":", "create_", "=", "registry", ".", "get_create_func", "(", "SubwordFunction", ",", "'token embedding'", ")", "return", "create_", "(", "subword_function_name", ",", "*",...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
Vocab._index_special_tokens
Indexes unknown and reserved tokens.
src/gluonnlp/vocab/vocab.py
def _index_special_tokens(self, unknown_token, special_tokens): """Indexes unknown and reserved tokens.""" self._idx_to_token = [unknown_token] if unknown_token else [] if not special_tokens: self._reserved_tokens = None else: self._reserved_tokens = special_toke...
def _index_special_tokens(self, unknown_token, special_tokens): """Indexes unknown and reserved tokens.""" self._idx_to_token = [unknown_token] if unknown_token else [] if not special_tokens: self._reserved_tokens = None else: self._reserved_tokens = special_toke...
[ "Indexes", "unknown", "and", "reserved", "tokens", "." ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/vocab/vocab.py#L163-L177
[ "def", "_index_special_tokens", "(", "self", ",", "unknown_token", ",", "special_tokens", ")", ":", "self", ".", "_idx_to_token", "=", "[", "unknown_token", "]", "if", "unknown_token", "else", "[", "]", "if", "not", "special_tokens", ":", "self", ".", "_reserv...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
Vocab._index_counter_keys
Indexes keys of `counter`. Indexes keys of `counter` according to frequency thresholds such as `max_size` and `min_freq`.
src/gluonnlp/vocab/vocab.py
def _index_counter_keys(self, counter, unknown_token, special_tokens, max_size, min_freq): """Indexes keys of `counter`. Indexes keys of `counter` according to frequency thresholds such as `max_size` and `min_freq`. """ unknown_and_special_tokens = ...
def _index_counter_keys(self, counter, unknown_token, special_tokens, max_size, min_freq): """Indexes keys of `counter`. Indexes keys of `counter` according to frequency thresholds such as `max_size` and `min_freq`. """ unknown_and_special_tokens = ...
[ "Indexes", "keys", "of", "counter", "." ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/vocab/vocab.py#L179-L204
[ "def", "_index_counter_keys", "(", "self", ",", "counter", ",", "unknown_token", ",", "special_tokens", ",", "max_size", ",", "min_freq", ")", ":", "unknown_and_special_tokens", "=", "set", "(", "special_tokens", ")", "if", "special_tokens", "else", "set", "(", ...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
Vocab.set_embedding
Attaches one or more embeddings to the indexed text tokens. Parameters ---------- embeddings : None or tuple of :class:`gluonnlp.embedding.TokenEmbedding` instances The embedding to be attached to the indexed tokens. If a tuple of multiple embeddings are provided, their...
src/gluonnlp/vocab/vocab.py
def set_embedding(self, *embeddings): """Attaches one or more embeddings to the indexed text tokens. Parameters ---------- embeddings : None or tuple of :class:`gluonnlp.embedding.TokenEmbedding` instances The embedding to be attached to the indexed tokens. If a tuple of mu...
def set_embedding(self, *embeddings): """Attaches one or more embeddings to the indexed text tokens. Parameters ---------- embeddings : None or tuple of :class:`gluonnlp.embedding.TokenEmbedding` instances The embedding to be attached to the indexed tokens. If a tuple of mu...
[ "Attaches", "one", "or", "more", "embeddings", "to", "the", "indexed", "text", "tokens", "." ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/vocab/vocab.py#L281-L328
[ "def", "set_embedding", "(", "self", ",", "*", "embeddings", ")", ":", "if", "len", "(", "embeddings", ")", "==", "1", "and", "embeddings", "[", "0", "]", "is", "None", ":", "self", ".", "_embedding", "=", "None", "return", "for", "embs", "in", "embe...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
Vocab.to_tokens
Converts token indices to tokens according to the vocabulary. Parameters ---------- indices : int or list of ints A source token index or token indices to be converted. Returns ------- str or list of strs A token or a list of tokens according t...
src/gluonnlp/vocab/vocab.py
def to_tokens(self, indices): """Converts token indices to tokens according to the vocabulary. Parameters ---------- indices : int or list of ints A source token index or token indices to be converted. Returns ------- str or list of strs ...
def to_tokens(self, indices): """Converts token indices to tokens according to the vocabulary. Parameters ---------- indices : int or list of ints A source token index or token indices to be converted. Returns ------- str or list of strs ...
[ "Converts", "token", "indices", "to", "tokens", "according", "to", "the", "vocabulary", "." ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/vocab/vocab.py#L330-L360
[ "def", "to_tokens", "(", "self", ",", "indices", ")", ":", "to_reduce", "=", "False", "if", "not", "isinstance", "(", "indices", ",", "(", "list", ",", "tuple", ")", ")", ":", "indices", "=", "[", "indices", "]", "to_reduce", "=", "True", "max_idx", ...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
Vocab.to_json
Serialize Vocab object to json string. This method does not serialize the underlying embedding.
src/gluonnlp/vocab/vocab.py
def to_json(self): """Serialize Vocab object to json string. This method does not serialize the underlying embedding. """ if self._embedding: warnings.warn('Serialization of attached embedding ' 'to json is not supported. ' ...
def to_json(self): """Serialize Vocab object to json string. This method does not serialize the underlying embedding. """ if self._embedding: warnings.warn('Serialization of attached embedding ' 'to json is not supported. ' ...
[ "Serialize", "Vocab", "object", "to", "json", "string", "." ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/vocab/vocab.py#L402-L420
[ "def", "to_json", "(", "self", ")", ":", "if", "self", ".", "_embedding", ":", "warnings", ".", "warn", "(", "'Serialization of attached embedding '", "'to json is not supported. '", "'You may serialize the embedding to a binary format '", "'separately using vocab.embedding.seria...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
Vocab.from_json
Deserialize Vocab object from json string. Parameters ---------- json_str : str Serialized json string of a Vocab object. Returns ------- Vocab
src/gluonnlp/vocab/vocab.py
def from_json(cls, json_str): """Deserialize Vocab object from json string. Parameters ---------- json_str : str Serialized json string of a Vocab object. Returns ------- Vocab """ vocab_dict = json.loads(json_str) unknown_t...
def from_json(cls, json_str): """Deserialize Vocab object from json string. Parameters ---------- json_str : str Serialized json string of a Vocab object. Returns ------- Vocab """ vocab_dict = json.loads(json_str) unknown_t...
[ "Deserialize", "Vocab", "object", "from", "json", "string", "." ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/vocab/vocab.py#L423-L449
[ "def", "from_json", "(", "cls", ",", "json_str", ")", ":", "vocab_dict", "=", "json", ".", "loads", "(", "json_str", ")", "unknown_token", "=", "vocab_dict", ".", "get", "(", "'unknown_token'", ")", "vocab", "=", "cls", "(", "unknown_token", "=", "unknown_...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
train
Training function.
scripts/bert/run_pretraining_hvd.py
def train(data_train, model, nsp_loss, mlm_loss, vocab_size, ctx): """Training function.""" hvd.broadcast_parameters(model.collect_params(), root_rank=0) mlm_metric = nlp.metric.MaskedAccuracy() nsp_metric = nlp.metric.MaskedAccuracy() mlm_metric.reset() nsp_metric.reset() logging.debug('C...
def train(data_train, model, nsp_loss, mlm_loss, vocab_size, ctx): """Training function.""" hvd.broadcast_parameters(model.collect_params(), root_rank=0) mlm_metric = nlp.metric.MaskedAccuracy() nsp_metric = nlp.metric.MaskedAccuracy() mlm_metric.reset() nsp_metric.reset() logging.debug('C...
[ "Training", "function", "." ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/run_pretraining_hvd.py#L71-L204
[ "def", "train", "(", "data_train", ",", "model", ",", "nsp_loss", ",", "mlm_loss", ",", "vocab_size", ",", "ctx", ")", ":", "hvd", ".", "broadcast_parameters", "(", "model", ".", "collect_params", "(", ")", ",", "root_rank", "=", "0", ")", "mlm_metric", ...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
train
Training function.
scripts/bert/staticbert/static_finetune_squad.py
def train(): """Training function.""" log.info('Loader Train data...') if version_2: train_data = SQuAD('train', version='2.0') else: train_data = SQuAD('train', version='1.1') log.info('Number of records in Train data:{}'.format(len(train_data))) train_data_transform, _ = prepr...
def train(): """Training function.""" log.info('Loader Train data...') if version_2: train_data = SQuAD('train', version='2.0') else: train_data = SQuAD('train', version='1.1') log.info('Number of records in Train data:{}'.format(len(train_data))) train_data_transform, _ = prepr...
[ "Training", "function", "." ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/staticbert/static_finetune_squad.py#L301-L426
[ "def", "train", "(", ")", ":", "log", ".", "info", "(", "'Loader Train data...'", ")", "if", "version_2", ":", "train_data", "=", "SQuAD", "(", "'train'", ",", "version", "=", "'2.0'", ")", "else", ":", "train_data", "=", "SQuAD", "(", "'train'", ",", ...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
evaluate
Evaluate the model on validation dataset.
scripts/bert/staticbert/static_finetune_squad.py
def evaluate(): """Evaluate the model on validation dataset. """ log.info('Loader dev data...') if version_2: dev_data = SQuAD('dev', version='2.0') else: dev_data = SQuAD('dev', version='1.1') log.info('Number of records in Train data:{}'.format(len(dev_data))) dev_dataset ...
def evaluate(): """Evaluate the model on validation dataset. """ log.info('Loader dev data...') if version_2: dev_data = SQuAD('dev', version='2.0') else: dev_data = SQuAD('dev', version='1.1') log.info('Number of records in Train data:{}'.format(len(dev_data))) dev_dataset ...
[ "Evaluate", "the", "model", "on", "validation", "dataset", "." ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/staticbert/static_finetune_squad.py#L429-L517
[ "def", "evaluate", "(", ")", ":", "log", ".", "info", "(", "'Loader dev data...'", ")", "if", "version_2", ":", "dev_data", "=", "SQuAD", "(", "'dev'", ",", "version", "=", "'2.0'", ")", "else", ":", "dev_data", "=", "SQuAD", "(", "'dev'", ",", "versio...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
_pad_arrs_to_max_length
Inner Implementation of the Pad batchify Parameters ---------- arrs : list pad_axis : int pad_val : number use_shared_mem : bool, default False Returns ------- ret : NDArray original_length : NDArray
src/gluonnlp/data/batchify/batchify.py
def _pad_arrs_to_max_length(arrs, pad_axis, pad_val, use_shared_mem, dtype): """Inner Implementation of the Pad batchify Parameters ---------- arrs : list pad_axis : int pad_val : number use_shared_mem : bool, default False Returns ------- ret : NDArray original_length : ND...
def _pad_arrs_to_max_length(arrs, pad_axis, pad_val, use_shared_mem, dtype): """Inner Implementation of the Pad batchify Parameters ---------- arrs : list pad_axis : int pad_val : number use_shared_mem : bool, default False Returns ------- ret : NDArray original_length : ND...
[ "Inner", "Implementation", "of", "the", "Pad", "batchify" ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/data/batchify/batchify.py#L29-L75
[ "def", "_pad_arrs_to_max_length", "(", "arrs", ",", "pad_axis", ",", "pad_val", ",", "use_shared_mem", ",", "dtype", ")", ":", "if", "isinstance", "(", "arrs", "[", "0", "]", ",", "mx", ".", "nd", ".", "NDArray", ")", ":", "dtype", "=", "arrs", "[", ...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
DepParser.train
Train a deep biaffine dependency parser Parameters ---------- train_file : str path to training set dev_file : str path to dev set test_file : str path to test set save_dir : str a directory for saving model and related met...
scripts/parsing/parser/dep_parser.py
def train(self, train_file, dev_file, test_file, save_dir, pretrained_embeddings=None, min_occur_count=2, lstm_layers=3, word_dims=100, tag_dims=100, dropout_emb=0.33, lstm_hiddens=400, dropout_lstm_input=0.33, dropout_lstm_hidden=0.33, mlp_arc_size=500, mlp_rel_size=100, dropo...
def train(self, train_file, dev_file, test_file, save_dir, pretrained_embeddings=None, min_occur_count=2, lstm_layers=3, word_dims=100, tag_dims=100, dropout_emb=0.33, lstm_hiddens=400, dropout_lstm_input=0.33, dropout_lstm_hidden=0.33, mlp_arc_size=500, mlp_rel_size=100, dropo...
[ "Train", "a", "deep", "biaffine", "dependency", "parser" ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/parser/dep_parser.py#L44-L199
[ "def", "train", "(", "self", ",", "train_file", ",", "dev_file", ",", "test_file", ",", "save_dir", ",", "pretrained_embeddings", "=", "None", ",", "min_occur_count", "=", "2", ",", "lstm_layers", "=", "3", ",", "word_dims", "=", "100", ",", "tag_dims", "=...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
DepParser.load
Load from disk Parameters ---------- path : str path to the directory which typically contains a config.pkl file and a model.bin file Returns ------- DepParser parser itself
scripts/parsing/parser/dep_parser.py
def load(self, path): """Load from disk Parameters ---------- path : str path to the directory which typically contains a config.pkl file and a model.bin file Returns ------- DepParser parser itself """ config = _Config.lo...
def load(self, path): """Load from disk Parameters ---------- path : str path to the directory which typically contains a config.pkl file and a model.bin file Returns ------- DepParser parser itself """ config = _Config.lo...
[ "Load", "from", "disk" ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/parser/dep_parser.py#L201-L224
[ "def", "load", "(", "self", ",", "path", ")", ":", "config", "=", "_Config", ".", "load", "(", "os", ".", "path", ".", "join", "(", "path", ",", "'config.pkl'", ")", ")", "config", ".", "save_dir", "=", "path", "# redirect root path to what user specified"...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
DepParser.evaluate
Run evaluation on test set Parameters ---------- test_file : str path to test set save_dir : str where to store intermediate results and log logger : logging.logger logger for printing results num_buckets_test : int number ...
scripts/parsing/parser/dep_parser.py
def evaluate(self, test_file, save_dir=None, logger=None, num_buckets_test=10, test_batch_size=5000): """Run evaluation on test set Parameters ---------- test_file : str path to test set save_dir : str where to store intermediate results and log l...
def evaluate(self, test_file, save_dir=None, logger=None, num_buckets_test=10, test_batch_size=5000): """Run evaluation on test set Parameters ---------- test_file : str path to test set save_dir : str where to store intermediate results and log l...
[ "Run", "evaluation", "on", "test", "set" ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/parser/dep_parser.py#L226-L256
[ "def", "evaluate", "(", "self", ",", "test_file", ",", "save_dir", "=", "None", ",", "logger", "=", "None", ",", "num_buckets_test", "=", "10", ",", "test_batch_size", "=", "5000", ")", ":", "parser", "=", "self", ".", "_parser", "vocab", "=", "self", ...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
DepParser.parse
Parse raw sentence into ConllSentence Parameters ---------- sentence : list a list of (word, tag) tuples Returns ------- ConllSentence ConllSentence object
scripts/parsing/parser/dep_parser.py
def parse(self, sentence): """Parse raw sentence into ConllSentence Parameters ---------- sentence : list a list of (word, tag) tuples Returns ------- ConllSentence ConllSentence object """ words = np.zeros((len(sentence) ...
def parse(self, sentence): """Parse raw sentence into ConllSentence Parameters ---------- sentence : list a list of (word, tag) tuples Returns ------- ConllSentence ConllSentence object """ words = np.zeros((len(sentence) ...
[ "Parse", "raw", "sentence", "into", "ConllSentence" ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/parser/dep_parser.py#L258-L285
[ "def", "parse", "(", "self", ",", "sentence", ")", ":", "words", "=", "np", ".", "zeros", "(", "(", "len", "(", "sentence", ")", "+", "1", ",", "1", ")", ",", "np", ".", "int32", ")", "tags", "=", "np", ".", "zeros", "(", "(", "len", "(", "...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
apply_weight_drop
Apply weight drop to the parameter of a block. Parameters ---------- block : Block or HybridBlock The block whose parameter is to be applied weight-drop. local_param_regex : str The regex for parameter names used in the self.params.get(), such as 'weight'. rate : float Fract...
src/gluonnlp/model/utils.py
def apply_weight_drop(block, local_param_regex, rate, axes=(), weight_dropout_mode='training'): """Apply weight drop to the parameter of a block. Parameters ---------- block : Block or HybridBlock The block whose parameter is to be applied weight-drop. local_param_rege...
def apply_weight_drop(block, local_param_regex, rate, axes=(), weight_dropout_mode='training'): """Apply weight drop to the parameter of a block. Parameters ---------- block : Block or HybridBlock The block whose parameter is to be applied weight-drop. local_param_rege...
[ "Apply", "weight", "drop", "to", "the", "parameter", "of", "a", "block", "." ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/utils.py#L36-L114
[ "def", "apply_weight_drop", "(", "block", ",", "local_param_regex", ",", "rate", ",", "axes", "=", "(", ")", ",", "weight_dropout_mode", "=", "'training'", ")", ":", "if", "not", "rate", ":", "return", "existing_params", "=", "_find_params", "(", "block", ",...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
_get_rnn_cell
create rnn cell given specs Parameters ---------- mode : str The type of RNN cell to use. Options are 'lstmpc', 'rnn_tanh', 'rnn_relu', 'lstm', 'gru'. num_layers : int The number of RNN cells in the encoder. input_size : int The initial input size of in the RNN cell. hid...
src/gluonnlp/model/utils.py
def _get_rnn_cell(mode, num_layers, input_size, hidden_size, dropout, weight_dropout, var_drop_in, var_drop_state, var_drop_out, skip_connection, proj_size=None, cell_clip=None, proj_clip=None): """create rnn cell given specs Parameters ---------- m...
def _get_rnn_cell(mode, num_layers, input_size, hidden_size, dropout, weight_dropout, var_drop_in, var_drop_state, var_drop_out, skip_connection, proj_size=None, cell_clip=None, proj_clip=None): """create rnn cell given specs Parameters ---------- m...
[ "create", "rnn", "cell", "given", "specs" ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/utils.py#L162-L242
[ "def", "_get_rnn_cell", "(", "mode", ",", "num_layers", ",", "input_size", ",", "hidden_size", ",", "dropout", ",", "weight_dropout", ",", "var_drop_in", ",", "var_drop_state", ",", "var_drop_out", ",", "skip_connection", ",", "proj_size", "=", "None", ",", "cel...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
_get_rnn_layer
create rnn layer given specs
src/gluonnlp/model/utils.py
def _get_rnn_layer(mode, num_layers, input_size, hidden_size, dropout, weight_dropout): """create rnn layer given specs""" if mode == 'rnn_relu': rnn_block = functools.partial(rnn.RNN, activation='relu') elif mode == 'rnn_tanh': rnn_block = functools.partial(rnn.RNN, activation='tanh') e...
def _get_rnn_layer(mode, num_layers, input_size, hidden_size, dropout, weight_dropout): """create rnn layer given specs""" if mode == 'rnn_relu': rnn_block = functools.partial(rnn.RNN, activation='relu') elif mode == 'rnn_tanh': rnn_block = functools.partial(rnn.RNN, activation='tanh') e...
[ "create", "rnn", "layer", "given", "specs" ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/utils.py#L245-L262
[ "def", "_get_rnn_layer", "(", "mode", ",", "num_layers", ",", "input_size", ",", "hidden_size", ",", "dropout", ",", "weight_dropout", ")", ":", "if", "mode", "==", "'rnn_relu'", ":", "rnn_block", "=", "functools", ".", "partial", "(", "rnn", ".", "RNN", "...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
_SampledDenseHelper.hybrid_forward
Forward computation.
src/gluonnlp/model/sampled_block.py
def hybrid_forward(self, F, x, sampled_values, label, w_all, b_all): """Forward computation.""" sampled_candidates, expected_count_sampled, expected_count_true = sampled_values # (num_sampled, in_unit) w_sampled = w_all.slice(begin=(0, 0), end=(self._num_sampled, None)) w_true = ...
def hybrid_forward(self, F, x, sampled_values, label, w_all, b_all): """Forward computation.""" sampled_candidates, expected_count_sampled, expected_count_true = sampled_values # (num_sampled, in_unit) w_sampled = w_all.slice(begin=(0, 0), end=(self._num_sampled, None)) w_true = ...
[ "Forward", "computation", "." ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/sampled_block.py#L52-L95
[ "def", "hybrid_forward", "(", "self", ",", "F", ",", "x", ",", "sampled_values", ",", "label", ",", "w_all", ",", "b_all", ")", ":", "sampled_candidates", ",", "expected_count_sampled", ",", "expected_count_true", "=", "sampled_values", "# (num_sampled, in_unit)", ...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
_SampledDense.hybrid_forward
Forward computation.
src/gluonnlp/model/sampled_block.py
def hybrid_forward(self, F, x, sampled_values, label, weight, bias): """Forward computation.""" sampled_candidates, _, _ = sampled_values # (batch_size,) label = F.reshape(label, shape=(-1,)) # (num_sampled+batch_size,) ids = F.concat(sampled_candidates, label, dim=0) ...
def hybrid_forward(self, F, x, sampled_values, label, weight, bias): """Forward computation.""" sampled_candidates, _, _ = sampled_values # (batch_size,) label = F.reshape(label, shape=(-1,)) # (num_sampled+batch_size,) ids = F.concat(sampled_candidates, label, dim=0) ...
[ "Forward", "computation", "." ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/sampled_block.py#L169-L183
[ "def", "hybrid_forward", "(", "self", ",", "F", ",", "x", ",", "sampled_values", ",", "label", ",", "weight", ",", "bias", ")", ":", "sampled_candidates", ",", "_", ",", "_", "=", "sampled_values", "# (batch_size,)", "label", "=", "F", ".", "reshape", "(...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
_SparseSampledDense.forward
Forward computation.
src/gluonnlp/model/sampled_block.py
def forward(self, x, sampled_values, label): """Forward computation.""" sampled_candidates, _, _ = sampled_values # (batch_size,) label = label.reshape(shape=(-1,)) # (num_sampled+batch_size,) ids = nd.concat(sampled_candidates, label, dim=0) # lookup weights and ...
def forward(self, x, sampled_values, label): """Forward computation.""" sampled_candidates, _, _ = sampled_values # (batch_size,) label = label.reshape(shape=(-1,)) # (num_sampled+batch_size,) ids = nd.concat(sampled_candidates, label, dim=0) # lookup weights and ...
[ "Forward", "computation", "." ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/sampled_block.py#L472-L487
[ "def", "forward", "(", "self", ",", "x", ",", "sampled_values", ",", "label", ")", ":", "sampled_candidates", ",", "_", ",", "_", "=", "sampled_values", "# (batch_size,)", "label", "=", "label", ".", "reshape", "(", "shape", "=", "(", "-", "1", ",", ")...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
_extract_and_flatten_nested_structure
Flatten the structure of a nested container to a list. Parameters ---------- data : A single NDArray/Symbol or nested container with NDArrays/Symbol. The nested container to be flattened. flattened : list or None The container thats holds flattened result. Returns ------- st...
src/gluonnlp/model/sequence_sampler.py
def _extract_and_flatten_nested_structure(data, flattened=None): """Flatten the structure of a nested container to a list. Parameters ---------- data : A single NDArray/Symbol or nested container with NDArrays/Symbol. The nested container to be flattened. flattened : list or None Th...
def _extract_and_flatten_nested_structure(data, flattened=None): """Flatten the structure of a nested container to a list. Parameters ---------- data : A single NDArray/Symbol or nested container with NDArrays/Symbol. The nested container to be flattened. flattened : list or None Th...
[ "Flatten", "the", "structure", "of", "a", "nested", "container", "to", "a", "list", "." ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/sequence_sampler.py#L88-L119
[ "def", "_extract_and_flatten_nested_structure", "(", "data", ",", "flattened", "=", "None", ")", ":", "if", "flattened", "is", "None", ":", "flattened", "=", "[", "]", "structure", "=", "_extract_and_flatten_nested_structure", "(", "data", ",", "flattened", ")", ...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
_reconstruct_flattened_structure
Reconstruct the flattened list back to (possibly) nested structure. Parameters ---------- structure : An integer or a nested container with integers. The extracted structure of the container of `data`. flattened : list or None The container thats holds flattened result. Returns ...
src/gluonnlp/model/sequence_sampler.py
def _reconstruct_flattened_structure(structure, flattened): """Reconstruct the flattened list back to (possibly) nested structure. Parameters ---------- structure : An integer or a nested container with integers. The extracted structure of the container of `data`. flattened : list or None ...
def _reconstruct_flattened_structure(structure, flattened): """Reconstruct the flattened list back to (possibly) nested structure. Parameters ---------- structure : An integer or a nested container with integers. The extracted structure of the container of `data`. flattened : list or None ...
[ "Reconstruct", "the", "flattened", "list", "back", "to", "(", "possibly", ")", "nested", "structure", "." ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/sequence_sampler.py#L122-L145
[ "def", "_reconstruct_flattened_structure", "(", "structure", ",", "flattened", ")", ":", "if", "isinstance", "(", "structure", ",", "list", ")", ":", "return", "list", "(", "_reconstruct_flattened_structure", "(", "x", ",", "flattened", ")", "for", "x", "in", ...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
_expand_to_beam_size
Tile all the states to have batch_size * beam_size on the batch axis. Parameters ---------- data : A single NDArray/Symbol or nested container with NDArrays/Symbol Each NDArray/Symbol should have shape (N, ...) when state_info is None, or same as the layout in state_info when it's not None....
src/gluonnlp/model/sequence_sampler.py
def _expand_to_beam_size(data, beam_size, batch_size, state_info=None): """Tile all the states to have batch_size * beam_size on the batch axis. Parameters ---------- data : A single NDArray/Symbol or nested container with NDArrays/Symbol Each NDArray/Symbol should have shape (N, ...) when stat...
def _expand_to_beam_size(data, beam_size, batch_size, state_info=None): """Tile all the states to have batch_size * beam_size on the batch axis. Parameters ---------- data : A single NDArray/Symbol or nested container with NDArrays/Symbol Each NDArray/Symbol should have shape (N, ...) when stat...
[ "Tile", "all", "the", "states", "to", "have", "batch_size", "*", "beam_size", "on", "the", "batch", "axis", "." ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/sequence_sampler.py#L148-L211
[ "def", "_expand_to_beam_size", "(", "data", ",", "beam_size", ",", "batch_size", ",", "state_info", "=", "None", ")", ":", "assert", "not", "state_info", "or", "isinstance", "(", "state_info", ",", "(", "type", "(", "data", ")", ",", "dict", ")", ")", ",...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
_SamplingStepUpdate.hybrid_forward
Parameters ---------- F samples : NDArray or Symbol The current samples generated by beam search. Shape (batch_size, beam_size, L) valid_length : NDArray or Symbol The current valid lengths of the samples outputs: NDArray or Symbol Decoder outp...
src/gluonnlp/model/sequence_sampler.py
def hybrid_forward(self, F, samples, valid_length, outputs, scores, beam_alive_mask, states): """ Parameters ---------- F samples : NDArray or Symbol The current samples generated by beam search. Shape (batch_size, beam_size, L) valid_length : NDArray or Symbo...
def hybrid_forward(self, F, samples, valid_length, outputs, scores, beam_alive_mask, states): """ Parameters ---------- F samples : NDArray or Symbol The current samples generated by beam search. Shape (batch_size, beam_size, L) valid_length : NDArray or Symbo...
[ "Parameters", "----------", "F", "samples", ":", "NDArray", "or", "Symbol", "The", "current", "samples", "generated", "by", "beam", "search", ".", "Shape", "(", "batch_size", "beam_size", "L", ")", "valid_length", ":", "NDArray", "or", "Symbol", "The", "curren...
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/sequence_sampler.py#L377-L442
[ "def", "hybrid_forward", "(", "self", ",", "F", ",", "samples", ",", "valid_length", ",", "outputs", ",", "scores", ",", "beam_alive_mask", ",", "states", ")", ":", "beam_size", "=", "self", ".", "_beam_size", "# outputs: (batch_size, beam_size, vocab_size)", "out...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
HybridBeamSearchSampler.hybrid_forward
Sample by beam search. Parameters ---------- F inputs : NDArray or Symbol The initial input of the decoder. Shape is (batch_size,). states : Object that contains NDArrays or Symbols The initial states of the decoder. Returns ------- ...
src/gluonnlp/model/sequence_sampler.py
def hybrid_forward(self, F, inputs, states): # pylint: disable=arguments-differ """Sample by beam search. Parameters ---------- F inputs : NDArray or Symbol The initial input of the decoder. Shape is (batch_size,). states : Object that contains NDArrays or ...
def hybrid_forward(self, F, inputs, states): # pylint: disable=arguments-differ """Sample by beam search. Parameters ---------- F inputs : NDArray or Symbol The initial input of the decoder. Shape is (batch_size,). states : Object that contains NDArrays or ...
[ "Sample", "by", "beam", "search", "." ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/sequence_sampler.py#L605-L710
[ "def", "hybrid_forward", "(", "self", ",", "F", ",", "inputs", ",", "states", ")", ":", "# pylint: disable=arguments-differ", "batch_size", "=", "self", ".", "_batch_size", "beam_size", "=", "self", ".", "_beam_size", "vocab_size", "=", "self", ".", "_vocab_size...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
WeightDropParameter.data
Returns a copy of this parameter on one context. Must have been initialized on this context before. Parameters ---------- ctx : Context Desired context. Returns ------- NDArray on ctx
src/gluonnlp/model/parameter.py
def data(self, ctx=None): """Returns a copy of this parameter on one context. Must have been initialized on this context before. Parameters ---------- ctx : Context Desired context. Returns ------- NDArray on ctx """ d = self._...
def data(self, ctx=None): """Returns a copy of this parameter on one context. Must have been initialized on this context before. Parameters ---------- ctx : Context Desired context. Returns ------- NDArray on ctx """ d = self._...
[ "Returns", "a", "copy", "of", "this", "parameter", "on", "one", "context", ".", "Must", "have", "been", "initialized", "on", "this", "context", "before", "." ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/parameter.py#L59-L74
[ "def", "data", "(", "self", ",", "ctx", "=", "None", ")", ":", "d", "=", "self", ".", "_check_and_get", "(", "self", ".", "_data", ",", "ctx", ")", "if", "self", ".", "_rate", ":", "d", "=", "nd", ".", "Dropout", "(", "d", ",", "self", ".", "...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
elmo_2x1024_128_2048cnn_1xhighway
r"""ELMo 2-layer BiLSTM with 1024 hidden units, 128 projection size, 1 highway layer. Parameters ---------- dataset_name : str or None, default None The dataset name on which the pre-trained model is trained. Options are 'gbw'. pretrained : bool, default False Whether to load th...
src/gluonnlp/model/elmo.py
def elmo_2x1024_128_2048cnn_1xhighway(dataset_name=None, pretrained=False, ctx=mx.cpu(), root=os.path.join(get_home_dir(), 'models'), **kwargs): r"""ELMo 2-layer BiLSTM with 1024 hidden units, 128 projection size, 1 highway layer. Parameters ---------- dataset_name...
def elmo_2x1024_128_2048cnn_1xhighway(dataset_name=None, pretrained=False, ctx=mx.cpu(), root=os.path.join(get_home_dir(), 'models'), **kwargs): r"""ELMo 2-layer BiLSTM with 1024 hidden units, 128 projection size, 1 highway layer. Parameters ---------- dataset_name...
[ "r", "ELMo", "2", "-", "layer", "BiLSTM", "with", "1024", "hidden", "units", "128", "projection", "size", "1", "highway", "layer", "." ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/elmo.py#L308-L349
[ "def", "elmo_2x1024_128_2048cnn_1xhighway", "(", "dataset_name", "=", "None", ",", "pretrained", "=", "False", ",", "ctx", "=", "mx", ".", "cpu", "(", ")", ",", "root", "=", "os", ".", "path", ".", "join", "(", "get_home_dir", "(", ")", ",", "'models'", ...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
ELMoCharacterEncoder.hybrid_forward
Compute context insensitive token embeddings for ELMo representations. Parameters ---------- inputs : NDArray Shape (batch_size, sequence_length, max_character_per_token) of character ids representing the current batch. Returns ------- token_embe...
src/gluonnlp/model/elmo.py
def hybrid_forward(self, F, inputs): # pylint: disable=arguments-differ """ Compute context insensitive token embeddings for ELMo representations. Parameters ---------- inputs : NDArray Shape (batch_size, sequence_length, max_character_per_token) ...
def hybrid_forward(self, F, inputs): # pylint: disable=arguments-differ """ Compute context insensitive token embeddings for ELMo representations. Parameters ---------- inputs : NDArray Shape (batch_size, sequence_length, max_character_per_token) ...
[ "Compute", "context", "insensitive", "token", "embeddings", "for", "ELMo", "representations", "." ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/elmo.py#L103-L131
[ "def", "hybrid_forward", "(", "self", ",", "F", ",", "inputs", ")", ":", "# pylint: disable=arguments-differ", "# the character id embedding", "# (batch_size * sequence_length, max_chars_per_token, embed_dim)", "character_embedding", "=", "self", ".", "_char_embedding", "(", "i...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
ELMoBiLM.hybrid_forward
Parameters ---------- inputs : NDArray Shape (batch_size, sequence_length, max_character_per_token) of character ids representing the current batch. states : (list of list of NDArray, list of list of NDArray) The states. First tuple element is the forward laye...
src/gluonnlp/model/elmo.py
def hybrid_forward(self, F, inputs, states=None, mask=None): # pylint: disable=arguments-differ """ Parameters ---------- inputs : NDArray Shape (batch_size, sequence_length, max_character_per_token) of character ids representing the current batch. ...
def hybrid_forward(self, F, inputs, states=None, mask=None): # pylint: disable=arguments-differ """ Parameters ---------- inputs : NDArray Shape (batch_size, sequence_length, max_character_per_token) of character ids representing the current batch. ...
[ "Parameters", "----------", "inputs", ":", "NDArray", "Shape", "(", "batch_size", "sequence_length", "max_character_per_token", ")", "of", "character", "ids", "representing", "the", "current", "batch", ".", "states", ":", "(", "list", "of", "list", "of", "NDArray"...
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/elmo.py#L243-L284
[ "def", "hybrid_forward", "(", "self", ",", "F", ",", "inputs", ",", "states", "=", "None", ",", "mask", "=", "None", ")", ":", "# pylint: disable=arguments-differ", "type_representation", "=", "self", ".", "_elmo_char_encoder", "(", "inputs", ")", "type_represen...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
awd_lstm_lm_1150
r"""3-layer LSTM language model with weight-drop, variational dropout, and tied weights. Embedding size is 400, and hidden layer size is 1150. Parameters ---------- dataset_name : str or None, default None The dataset name on which the pre-trained model is trained. Options are 'wikitex...
src/gluonnlp/model/language_model.py
def awd_lstm_lm_1150(dataset_name=None, vocab=None, pretrained=False, ctx=cpu(), root=os.path.join(get_home_dir(), 'models'), **kwargs): r"""3-layer LSTM language model with weight-drop, variational dropout, and tied weights. Embedding size is 400, and hidden layer size is 1150. Param...
def awd_lstm_lm_1150(dataset_name=None, vocab=None, pretrained=False, ctx=cpu(), root=os.path.join(get_home_dir(), 'models'), **kwargs): r"""3-layer LSTM language model with weight-drop, variational dropout, and tied weights. Embedding size is 400, and hidden layer size is 1150. Param...
[ "r", "3", "-", "layer", "LSTM", "language", "model", "with", "weight", "-", "drop", "variational", "dropout", "and", "tied", "weights", "." ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/language_model.py#L181-L226
[ "def", "awd_lstm_lm_1150", "(", "dataset_name", "=", "None", ",", "vocab", "=", "None", ",", "pretrained", "=", "False", ",", "ctx", "=", "cpu", "(", ")", ",", "root", "=", "os", ".", "path", ".", "join", "(", "get_home_dir", "(", ")", ",", "'models'...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
standard_lstm_lm_200
r"""Standard 2-layer LSTM language model with tied embedding and output weights. Both embedding and hidden dimensions are 200. Parameters ---------- dataset_name : str or None, default None The dataset name on which the pre-trained model is trained. Options are 'wikitext-2'. If specifi...
src/gluonnlp/model/language_model.py
def standard_lstm_lm_200(dataset_name=None, vocab=None, pretrained=False, ctx=cpu(), root=os.path.join(get_home_dir(), 'models'), **kwargs): r"""Standard 2-layer LSTM language model with tied embedding and output weights. Both embedding and hidden dimensions are 200. Parameters ...
def standard_lstm_lm_200(dataset_name=None, vocab=None, pretrained=False, ctx=cpu(), root=os.path.join(get_home_dir(), 'models'), **kwargs): r"""Standard 2-layer LSTM language model with tied embedding and output weights. Both embedding and hidden dimensions are 200. Parameters ...
[ "r", "Standard", "2", "-", "layer", "LSTM", "language", "model", "with", "tied", "embedding", "and", "output", "weights", "." ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/language_model.py#L276-L317
[ "def", "standard_lstm_lm_200", "(", "dataset_name", "=", "None", ",", "vocab", "=", "None", ",", "pretrained", "=", "False", ",", "ctx", "=", "cpu", "(", ")", ",", "root", "=", "os", ".", "path", ".", "join", "(", "get_home_dir", "(", ")", ",", "'mod...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
big_rnn_lm_2048_512
r"""Big 1-layer LSTMP language model. Both embedding and projection size are 512. Hidden size is 2048. Parameters ---------- dataset_name : str or None, default None The dataset name on which the pre-trained model is trained. Options are 'gbw'. If specified, then the returned vocabular...
src/gluonnlp/model/language_model.py
def big_rnn_lm_2048_512(dataset_name=None, vocab=None, pretrained=False, ctx=cpu(), root=os.path.join(get_home_dir(), 'models'), **kwargs): r"""Big 1-layer LSTMP language model. Both embedding and projection size are 512. Hidden size is 2048. Parameters ---------- dataset_n...
def big_rnn_lm_2048_512(dataset_name=None, vocab=None, pretrained=False, ctx=cpu(), root=os.path.join(get_home_dir(), 'models'), **kwargs): r"""Big 1-layer LSTMP language model. Both embedding and projection size are 512. Hidden size is 2048. Parameters ---------- dataset_n...
[ "r", "Big", "1", "-", "layer", "LSTMP", "language", "model", "." ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/language_model.py#L512-L553
[ "def", "big_rnn_lm_2048_512", "(", "dataset_name", "=", "None", ",", "vocab", "=", "None", ",", "pretrained", "=", "False", ",", "ctx", "=", "cpu", "(", ")", ",", "root", "=", "os", ".", "path", ".", "join", "(", "get_home_dir", "(", ")", ",", "'mode...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
AWDRNN.forward
Implement forward computation. Parameters ----------- inputs : NDArray input tensor with shape `(sequence_length, batch_size)` when `layout` is "TNC". begin_state : list initial recurrent state tensor with length equals to num_layers. the ...
src/gluonnlp/model/language_model.py
def forward(self, inputs, begin_state=None): # pylint: disable=arguments-differ """Implement forward computation. Parameters ----------- inputs : NDArray input tensor with shape `(sequence_length, batch_size)` when `layout` is "TNC". begin_state : list ...
def forward(self, inputs, begin_state=None): # pylint: disable=arguments-differ """Implement forward computation. Parameters ----------- inputs : NDArray input tensor with shape `(sequence_length, batch_size)` when `layout` is "TNC". begin_state : list ...
[ "Implement", "forward", "computation", "." ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/language_model.py#L74-L108
[ "def", "forward", "(", "self", ",", "inputs", ",", "begin_state", "=", "None", ")", ":", "# pylint: disable=arguments-differ", "encoded", "=", "self", ".", "embedding", "(", "inputs", ")", "if", "begin_state", "is", "None", ":", "begin_state", "=", "self", "...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
BigRNN.forward
Implement forward computation. Parameters ----------- inputs : NDArray input tensor with shape `(sequence_length, batch_size)` when `layout` is "TNC". begin_state : list initial recurrent state tensor with length equals to num_layers*2. Fo...
src/gluonnlp/model/language_model.py
def forward(self, inputs, begin_state): # pylint: disable=arguments-differ """Implement forward computation. Parameters ----------- inputs : NDArray input tensor with shape `(sequence_length, batch_size)` when `layout` is "TNC". begin_state : list ...
def forward(self, inputs, begin_state): # pylint: disable=arguments-differ """Implement forward computation. Parameters ----------- inputs : NDArray input tensor with shape `(sequence_length, batch_size)` when `layout` is "TNC". begin_state : list ...
[ "Implement", "forward", "computation", "." ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/language_model.py#L479-L510
[ "def", "forward", "(", "self", ",", "inputs", ",", "begin_state", ")", ":", "# pylint: disable=arguments-differ", "encoded", "=", "self", ".", "embedding", "(", "inputs", ")", "length", "=", "inputs", ".", "shape", "[", "0", "]", "batch_size", "=", "inputs",...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
_get_cell_type
Get the object type of the cell by parsing the input Parameters ---------- cell_type : str or type Returns ------- cell_constructor: type The constructor of the RNNCell
src/gluonnlp/model/seq2seq_encoder_decoder.py
def _get_cell_type(cell_type): """Get the object type of the cell by parsing the input Parameters ---------- cell_type : str or type Returns ------- cell_constructor: type The constructor of the RNNCell """ if isinstance(cell_type, str): if cell_type == 'lstm': ...
def _get_cell_type(cell_type): """Get the object type of the cell by parsing the input Parameters ---------- cell_type : str or type Returns ------- cell_constructor: type The constructor of the RNNCell """ if isinstance(cell_type, str): if cell_type == 'lstm': ...
[ "Get", "the", "object", "type", "of", "the", "cell", "by", "parsing", "the", "input" ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/seq2seq_encoder_decoder.py#L30-L54
[ "def", "_get_cell_type", "(", "cell_type", ")", ":", "if", "isinstance", "(", "cell_type", ",", "str", ")", ":", "if", "cell_type", "==", "'lstm'", ":", "return", "rnn", ".", "LSTMCell", "elif", "cell_type", "==", "'gru'", ":", "return", "rnn", ".", "GRU...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
_get_context
Compute the context with respect to a center word in a sentence. Takes an numpy array of sentences boundaries.
src/gluonnlp/data/batchify/embedding.py
def _get_context(center_idx, sentence_boundaries, window_size, random_window_size, seed): """Compute the context with respect to a center word in a sentence. Takes an numpy array of sentences boundaries. """ random.seed(seed + center_idx) sentence_index = np.searchsorted(sentence...
def _get_context(center_idx, sentence_boundaries, window_size, random_window_size, seed): """Compute the context with respect to a center word in a sentence. Takes an numpy array of sentences boundaries. """ random.seed(seed + center_idx) sentence_index = np.searchsorted(sentence...
[ "Compute", "the", "context", "with", "respect", "to", "a", "center", "word", "in", "a", "sentence", "." ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/data/batchify/embedding.py#L246-L274
[ "def", "_get_context", "(", "center_idx", ",", "sentence_boundaries", ",", "window_size", ",", "random_window_size", ",", "seed", ")", ":", "random", ".", "seed", "(", "seed", "+", "center_idx", ")", "sentence_index", "=", "np", ".", "searchsorted", "(", "sent...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
model
Construct the model.
scripts/sentiment_analysis/text_cnn.py
def model(dropout, vocab, model_mode, output_size): """Construct the model.""" textCNN = SentimentNet(dropout=dropout, vocab_size=len(vocab), model_mode=model_mode,\ output_size=output_size) textCNN.hybridize() return textCNN
def model(dropout, vocab, model_mode, output_size): """Construct the model.""" textCNN = SentimentNet(dropout=dropout, vocab_size=len(vocab), model_mode=model_mode,\ output_size=output_size) textCNN.hybridize() return textCNN
[ "Construct", "the", "model", "." ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/sentiment_analysis/text_cnn.py#L40-L46
[ "def", "model", "(", "dropout", ",", "vocab", ",", "model_mode", ",", "output_size", ")", ":", "textCNN", "=", "SentimentNet", "(", "dropout", "=", "dropout", ",", "vocab_size", "=", "len", "(", "vocab", ")", ",", "model_mode", "=", "model_mode", ",", "o...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
init
Initialize parameters.
scripts/sentiment_analysis/text_cnn.py
def init(textCNN, vocab, model_mode, context, lr): """Initialize parameters.""" textCNN.initialize(mx.init.Xavier(), ctx=context, force_reinit=True) if model_mode != 'rand': textCNN.embedding.weight.set_data(vocab.embedding.idx_to_vec) if model_mode == 'multichannel': textCNN.embedding_...
def init(textCNN, vocab, model_mode, context, lr): """Initialize parameters.""" textCNN.initialize(mx.init.Xavier(), ctx=context, force_reinit=True) if model_mode != 'rand': textCNN.embedding.weight.set_data(vocab.embedding.idx_to_vec) if model_mode == 'multichannel': textCNN.embedding_...
[ "Initialize", "parameters", "." ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/sentiment_analysis/text_cnn.py#L48-L60
[ "def", "init", "(", "textCNN", ",", "vocab", ",", "model_mode", ",", "context", ",", "lr", ")", ":", "textCNN", ".", "initialize", "(", "mx", ".", "init", ".", "Xavier", "(", ")", ",", "ctx", "=", "context", ",", "force_reinit", "=", "True", ")", "...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
preprocess_dataset
Use multiprocessing to perform transform for dataset. Parameters ---------- dataset: dataset-like object Source dataset. transform: callable Transformer function. num_workers: int, default 8 The number of multiprocessing workers to use for data preprocessing.
scripts/bert/bert_qa_dataset.py
def preprocess_dataset(dataset, transform, num_workers=8): """Use multiprocessing to perform transform for dataset. Parameters ---------- dataset: dataset-like object Source dataset. transform: callable Transformer function. num_workers: int, default 8 The number of mult...
def preprocess_dataset(dataset, transform, num_workers=8): """Use multiprocessing to perform transform for dataset. Parameters ---------- dataset: dataset-like object Source dataset. transform: callable Transformer function. num_workers: int, default 8 The number of mult...
[ "Use", "multiprocessing", "to", "perform", "transform", "for", "dataset", "." ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/bert_qa_dataset.py#L56-L86
[ "def", "preprocess_dataset", "(", "dataset", ",", "transform", ",", "num_workers", "=", "8", ")", ":", "worker_fn", "=", "partial", "(", "_worker_fn", ",", "transform", "=", "transform", ")", "start", "=", "time", ".", "time", "(", ")", "pool", "=", "mp"...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
get_model
Returns a pre-defined model by name. Parameters ---------- name : str Name of the model. dataset_name : str or None, default 'wikitext-2'. The dataset name on which the pre-trained model is trained. For language model, options are 'wikitext-2'. For ELMo, Options are 'gbw...
src/gluonnlp/model/__init__.py
def get_model(name, dataset_name='wikitext-2', **kwargs): """Returns a pre-defined model by name. Parameters ---------- name : str Name of the model. dataset_name : str or None, default 'wikitext-2'. The dataset name on which the pre-trained model is trained. For language mo...
def get_model(name, dataset_name='wikitext-2', **kwargs): """Returns a pre-defined model by name. Parameters ---------- name : str Name of the model. dataset_name : str or None, default 'wikitext-2'. The dataset name on which the pre-trained model is trained. For language mo...
[ "Returns", "a", "pre", "-", "defined", "model", "by", "name", "." ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/__init__.py#L99-L151
[ "def", "get_model", "(", "name", ",", "dataset_name", "=", "'wikitext-2'", ",", "*", "*", "kwargs", ")", ":", "models", "=", "{", "'standard_lstm_lm_200'", ":", "standard_lstm_lm_200", ",", "'standard_lstm_lm_650'", ":", "standard_lstm_lm_650", ",", "'standard_lstm_...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
_masked_softmax
Ignore the masked elements when calculating the softmax Parameters ---------- F : symbol or ndarray att_score : Symborl or NDArray Shape (batch_size, query_length, memory_length) mask : Symbol or NDArray or None Shape (batch_size, query_length, memory_length) Returns -------...
src/gluonnlp/model/attention_cell.py
def _masked_softmax(F, att_score, mask, dtype): """Ignore the masked elements when calculating the softmax Parameters ---------- F : symbol or ndarray att_score : Symborl or NDArray Shape (batch_size, query_length, memory_length) mask : Symbol or NDArray or None Shape (batch_siz...
def _masked_softmax(F, att_score, mask, dtype): """Ignore the masked elements when calculating the softmax Parameters ---------- F : symbol or ndarray att_score : Symborl or NDArray Shape (batch_size, query_length, memory_length) mask : Symbol or NDArray or None Shape (batch_siz...
[ "Ignore", "the", "masked", "elements", "when", "calculating", "the", "softmax" ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/attention_cell.py#L33-L55
[ "def", "_masked_softmax", "(", "F", ",", "att_score", ",", "mask", ",", "dtype", ")", ":", "if", "mask", "is", "not", "None", ":", "# Fill in the masked scores with a very small value", "neg", "=", "-", "1e4", "if", "np", ".", "dtype", "(", "dtype", ")", "...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
AttentionCell._read_by_weight
Read from the value matrix given the attention weights. Parameters ---------- F : symbol or ndarray att_weights : Symbol or NDArray Attention weights. For single-head attention, Shape (batch_size, query_length, memory_length). For mult...
src/gluonnlp/model/attention_cell.py
def _read_by_weight(self, F, att_weights, value): """Read from the value matrix given the attention weights. Parameters ---------- F : symbol or ndarray att_weights : Symbol or NDArray Attention weights. For single-head attention, Shape (b...
def _read_by_weight(self, F, att_weights, value): """Read from the value matrix given the attention weights. Parameters ---------- F : symbol or ndarray att_weights : Symbol or NDArray Attention weights. For single-head attention, Shape (b...
[ "Read", "from", "the", "value", "matrix", "given", "the", "attention", "weights", "." ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/attention_cell.py#L99-L120
[ "def", "_read_by_weight", "(", "self", ",", "F", ",", "att_weights", ",", "value", ")", ":", "output", "=", "F", ".", "batch_dot", "(", "att_weights", ",", "value", ")", "return", "output" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
BeamSearchTranslator.translate
Get the translation result given the input sentence. Parameters ---------- src_seq : mx.nd.NDArray Shape (batch_size, length) src_valid_length : mx.nd.NDArray Shape (batch_size,) Returns ------- samples : NDArray Samples draw ...
scripts/machine_translation/translation.py
def translate(self, src_seq, src_valid_length): """Get the translation result given the input sentence. Parameters ---------- src_seq : mx.nd.NDArray Shape (batch_size, length) src_valid_length : mx.nd.NDArray Shape (batch_size,) Returns ...
def translate(self, src_seq, src_valid_length): """Get the translation result given the input sentence. Parameters ---------- src_seq : mx.nd.NDArray Shape (batch_size, length) src_valid_length : mx.nd.NDArray Shape (batch_size,) Returns ...
[ "Get", "the", "translation", "result", "given", "the", "input", "sentence", "." ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/machine_translation/translation.py#L55-L82
[ "def", "translate", "(", "self", ",", "src_seq", ",", "src_valid_length", ")", ":", "batch_size", "=", "src_seq", ".", "shape", "[", "0", "]", "encoder_outputs", ",", "_", "=", "self", ".", "_model", ".", "encode", "(", "src_seq", ",", "valid_length", "=...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
evaluate_official_script
Evaluate parser on a data set Parameters ---------- parser : BiaffineParser biaffine parser vocab : ParserVocabulary vocabulary built from data set num_buckets_test : int size of buckets (cluster sentences into this number of clusters) test_batch_size : int batch...
scripts/parsing/parser/evaluate/evaluate.py
def evaluate_official_script(parser, vocab, num_buckets_test, test_batch_size, test_file, output_file, debug=False): """Evaluate parser on a data set Parameters ---------- parser : BiaffineParser biaffine parser vocab : ParserVocabulary vocabulary built ...
def evaluate_official_script(parser, vocab, num_buckets_test, test_batch_size, test_file, output_file, debug=False): """Evaluate parser on a data set Parameters ---------- parser : BiaffineParser biaffine parser vocab : ParserVocabulary vocabulary built ...
[ "Evaluate", "parser", "on", "a", "data", "set" ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/parser/evaluate/evaluate.py#L28-L102
[ "def", "evaluate_official_script", "(", "parser", ",", "vocab", ",", "num_buckets_test", ",", "test_batch_size", ",", "test_file", ",", "output_file", ",", "debug", "=", "False", ")", ":", "if", "output_file", "is", "None", ":", "output_file", "=", "tempfile", ...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
BiaffineParser.parameter_from_numpy
Create parameter with its value initialized according to a numpy tensor Parameters ---------- name : str parameter name array : np.ndarray initiation value Returns ------- mxnet.gluon.parameter a parameter object
scripts/parsing/parser/biaffine_parser.py
def parameter_from_numpy(self, name, array): """ Create parameter with its value initialized according to a numpy tensor Parameters ---------- name : str parameter name array : np.ndarray initiation value Returns ------- mxnet.glu...
def parameter_from_numpy(self, name, array): """ Create parameter with its value initialized according to a numpy tensor Parameters ---------- name : str parameter name array : np.ndarray initiation value Returns ------- mxnet.glu...
[ "Create", "parameter", "with", "its", "value", "initialized", "according", "to", "a", "numpy", "tensor" ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/parser/biaffine_parser.py#L122-L138
[ "def", "parameter_from_numpy", "(", "self", ",", "name", ",", "array", ")", ":", "p", "=", "self", ".", "params", ".", "get", "(", "name", ",", "shape", "=", "array", ".", "shape", ",", "init", "=", "mx", ".", "init", ".", "Constant", "(", "array",...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
BiaffineParser.parameter_init
Create parameter given name, shape and initiator Parameters ---------- name : str parameter name shape : tuple parameter shape init : mxnet.initializer an initializer Returns ------- mxnet.gluon.parameter a...
scripts/parsing/parser/biaffine_parser.py
def parameter_init(self, name, shape, init): """Create parameter given name, shape and initiator Parameters ---------- name : str parameter name shape : tuple parameter shape init : mxnet.initializer an initializer Returns ...
def parameter_init(self, name, shape, init): """Create parameter given name, shape and initiator Parameters ---------- name : str parameter name shape : tuple parameter shape init : mxnet.initializer an initializer Returns ...
[ "Create", "parameter", "given", "name", "shape", "and", "initiator" ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/parser/biaffine_parser.py#L140-L158
[ "def", "parameter_init", "(", "self", ",", "name", ",", "shape", ",", "init", ")", ":", "p", "=", "self", ".", "params", ".", "get", "(", "name", ",", "shape", "=", "shape", ",", "init", "=", "init", ")", "return", "p" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
BiaffineParser.forward
Run decoding Parameters ---------- word_inputs : mxnet.ndarray.NDArray word indices of seq_len x batch_size tag_inputs : mxnet.ndarray.NDArray tag indices of seq_len x batch_size arc_targets : mxnet.ndarray.NDArray gold arc indices of seq_len ...
scripts/parsing/parser/biaffine_parser.py
def forward(self, word_inputs, tag_inputs, arc_targets=None, rel_targets=None): """Run decoding Parameters ---------- word_inputs : mxnet.ndarray.NDArray word indices of seq_len x batch_size tag_inputs : mxnet.ndarray.NDArray tag indices of seq_len x batc...
def forward(self, word_inputs, tag_inputs, arc_targets=None, rel_targets=None): """Run decoding Parameters ---------- word_inputs : mxnet.ndarray.NDArray word indices of seq_len x batch_size tag_inputs : mxnet.ndarray.NDArray tag indices of seq_len x batc...
[ "Run", "decoding" ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/parser/biaffine_parser.py#L160-L302
[ "def", "forward", "(", "self", ",", "word_inputs", ",", "tag_inputs", ",", "arc_targets", "=", "None", ",", "rel_targets", "=", "None", ")", ":", "is_train", "=", "autograd", ".", "is_training", "(", ")", "def", "flatten_numpy", "(", "ndarray", ")", ":", ...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
BiaffineParser.save_parameters
Save model Parameters ---------- filename : str path to model file
scripts/parsing/parser/biaffine_parser.py
def save_parameters(self, filename): """Save model Parameters ---------- filename : str path to model file """ params = self._collect_params_with_prefix() if self.pret_word_embs: # don't save word embeddings inside model params.pop('pret_...
def save_parameters(self, filename): """Save model Parameters ---------- filename : str path to model file """ params = self._collect_params_with_prefix() if self.pret_word_embs: # don't save word embeddings inside model params.pop('pret_...
[ "Save", "model" ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/parser/biaffine_parser.py#L304-L316
[ "def", "save_parameters", "(", "self", ",", "filename", ")", ":", "params", "=", "self", ".", "_collect_params_with_prefix", "(", ")", "if", "self", ".", "pret_word_embs", ":", "# don't save word embeddings inside model", "params", ".", "pop", "(", "'pret_word_embs....
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
_worker_fn
Function for processing data in worker process.
src/gluonnlp/data/dataloader.py
def _worker_fn(samples, batchify_fn, dataset=None): """Function for processing data in worker process.""" # pylint: disable=unused-argument # it is required that each worker process has to fork a new MXIndexedRecordIO handle # preserving dataset as global variable can save tons of overhead and is safe i...
def _worker_fn(samples, batchify_fn, dataset=None): """Function for processing data in worker process.""" # pylint: disable=unused-argument # it is required that each worker process has to fork a new MXIndexedRecordIO handle # preserving dataset as global variable can save tons of overhead and is safe i...
[ "Function", "for", "processing", "data", "in", "worker", "process", "." ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/data/dataloader.py#L40-L52
[ "def", "_worker_fn", "(", "samples", ",", "batchify_fn", ",", "dataset", "=", "None", ")", ":", "# pylint: disable=unused-argument", "# it is required that each worker process has to fork a new MXIndexedRecordIO handle", "# preserving dataset as global variable can save tons of overhead ...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
_thread_worker_fn
Threadpool worker function for processing data.
src/gluonnlp/data/dataloader.py
def _thread_worker_fn(samples, batchify_fn, dataset): """Threadpool worker function for processing data.""" if isinstance(samples[0], (list, tuple)): batch = [batchify_fn([dataset[i] for i in shard]) for shard in samples] else: batch = batchify_fn([dataset[i] for i in samples]) return ba...
def _thread_worker_fn(samples, batchify_fn, dataset): """Threadpool worker function for processing data.""" if isinstance(samples[0], (list, tuple)): batch = [batchify_fn([dataset[i] for i in shard]) for shard in samples] else: batch = batchify_fn([dataset[i] for i in samples]) return ba...
[ "Threadpool", "worker", "function", "for", "processing", "data", "." ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/data/dataloader.py#L54-L60
[ "def", "_thread_worker_fn", "(", "samples", ",", "batchify_fn", ",", "dataset", ")", ":", "if", "isinstance", "(", "samples", "[", "0", "]", ",", "(", "list", ",", "tuple", ")", ")", ":", "batch", "=", "[", "batchify_fn", "(", "[", "dataset", "[", "i...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
create
Creates an instance of token embedding. Creates a token embedding instance by loading embedding vectors from an externally hosted pre-trained token embedding file, such as those of GloVe and FastText. To get all the valid `embedding_name` and `source`, use :func:`gluonnlp.embedding.list_sources`. Pa...
src/gluonnlp/embedding/token_embedding.py
def create(embedding_name, **kwargs): """Creates an instance of token embedding. Creates a token embedding instance by loading embedding vectors from an externally hosted pre-trained token embedding file, such as those of GloVe and FastText. To get all the valid `embedding_name` and `source`, use :fun...
def create(embedding_name, **kwargs): """Creates an instance of token embedding. Creates a token embedding instance by loading embedding vectors from an externally hosted pre-trained token embedding file, such as those of GloVe and FastText. To get all the valid `embedding_name` and `source`, use :fun...
[ "Creates", "an", "instance", "of", "token", "embedding", "." ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/embedding/token_embedding.py#L69-L97
[ "def", "create", "(", "embedding_name", ",", "*", "*", "kwargs", ")", ":", "create_text_embedding", "=", "registry", ".", "get_create_func", "(", "TokenEmbedding", ",", "'token embedding'", ")", "return", "create_text_embedding", "(", "embedding_name", ",", "*", "...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
list_sources
Get valid token embedding names and their pre-trained file names. To load token embedding vectors from an externally hosted pre-trained token embedding file, such as those of GloVe and FastText, one should use `gluonnlp.embedding.create(embedding_name, source)`. This method returns all the valid names...
src/gluonnlp/embedding/token_embedding.py
def list_sources(embedding_name=None): """Get valid token embedding names and their pre-trained file names. To load token embedding vectors from an externally hosted pre-trained token embedding file, such as those of GloVe and FastText, one should use `gluonnlp.embedding.create(embedding_name, source)...
def list_sources(embedding_name=None): """Get valid token embedding names and their pre-trained file names. To load token embedding vectors from an externally hosted pre-trained token embedding file, such as those of GloVe and FastText, one should use `gluonnlp.embedding.create(embedding_name, source)...
[ "Get", "valid", "token", "embedding", "names", "and", "their", "pre", "-", "trained", "file", "names", "." ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/embedding/token_embedding.py#L100-L139
[ "def", "list_sources", "(", "embedding_name", "=", "None", ")", ":", "text_embedding_reg", "=", "registry", ".", "get_registry", "(", "TokenEmbedding", ")", "if", "embedding_name", "is", "not", "None", ":", "embedding_name", "=", "embedding_name", ".", "lower", ...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
TokenEmbedding._load_embedding
Load embedding vectors from a pre-trained token embedding file. Both text files and TokenEmbedding serialization files are supported. elem_delim and encoding are ignored for non-text files. For every unknown token, if its representation `self.unknown_token` is encountered in the pre-tr...
src/gluonnlp/embedding/token_embedding.py
def _load_embedding(self, pretrained_file_path, elem_delim, encoding='utf8'): """Load embedding vectors from a pre-trained token embedding file. Both text files and TokenEmbedding serialization files are supported. elem_delim and encoding are ignored for non-text files. ...
def _load_embedding(self, pretrained_file_path, elem_delim, encoding='utf8'): """Load embedding vectors from a pre-trained token embedding file. Both text files and TokenEmbedding serialization files are supported. elem_delim and encoding are ignored for non-text files. ...
[ "Load", "embedding", "vectors", "from", "a", "pre", "-", "trained", "token", "embedding", "file", "." ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/embedding/token_embedding.py#L221-L253
[ "def", "_load_embedding", "(", "self", ",", "pretrained_file_path", ",", "elem_delim", ",", "encoding", "=", "'utf8'", ")", ":", "pretrained_file_path", "=", "os", ".", "path", ".", "expanduser", "(", "pretrained_file_path", ")", "if", "not", "os", ".", "path"...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
train
TokenEmbedding._load_embedding_txt
Load embedding vectors from a pre-trained token embedding file. For every unknown token, if its representation `self.unknown_token` is encountered in the pre-trained token embedding file, index 0 of `self.idx_to_vec` maps to the pre-trained token embedding vector loaded from the file; otherwise...
src/gluonnlp/embedding/token_embedding.py
def _load_embedding_txt(self, pretrained_file_path, elem_delim, encoding='utf8'): """Load embedding vectors from a pre-trained token embedding file. For every unknown token, if its representation `self.unknown_token` is encountered in the pre-trained token embedding file, index 0 of `self.idx_t...
def _load_embedding_txt(self, pretrained_file_path, elem_delim, encoding='utf8'): """Load embedding vectors from a pre-trained token embedding file. For every unknown token, if its representation `self.unknown_token` is encountered in the pre-trained token embedding file, index 0 of `self.idx_t...
[ "Load", "embedding", "vectors", "from", "a", "pre", "-", "trained", "token", "embedding", "file", "." ]
dmlc/gluon-nlp
python
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/embedding/token_embedding.py#L255-L321
[ "def", "_load_embedding_txt", "(", "self", ",", "pretrained_file_path", ",", "elem_delim", ",", "encoding", "=", "'utf8'", ")", ":", "vec_len", "=", "None", "all_elems", "=", "[", "]", "tokens", "=", "set", "(", ")", "loaded_unknown_vec", "=", "None", "with"...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba